python_code
stringlengths 0
1.8M
| repo_name
stringclasses 7
values | file_path
stringlengths 5
99
|
---|---|---|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Logitech PS/2++ mouse driver
*
* Copyright (c) 1999-2003 Vojtech Pavlik <[email protected]>
* Copyright (c) 2003 Eric Wong <[email protected]>
*/
#include <linux/bitops.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include <linux/types.h>
#include "psmouse.h"
#include "logips2pp.h"
/* Logitech mouse types */
#define PS2PP_KIND_WHEEL 1
#define PS2PP_KIND_MX 2
#define PS2PP_KIND_TP3 3
#define PS2PP_KIND_TRACKMAN 4
/* Logitech mouse features */
#define PS2PP_WHEEL BIT(0)
#define PS2PP_HWHEEL BIT(1)
#define PS2PP_SIDE_BTN BIT(2)
#define PS2PP_EXTRA_BTN BIT(3)
#define PS2PP_TASK_BTN BIT(4)
#define PS2PP_NAV_BTN BIT(5)
struct ps2pp_info {
u8 model;
u8 kind;
u16 features;
};
/*
* Process a PS2++ or PS2T++ packet.
*/
static psmouse_ret_t ps2pp_process_byte(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
u8 *packet = psmouse->packet;
if (psmouse->pktcnt < 3)
return PSMOUSE_GOOD_DATA;
/*
* Full packet accumulated, process it
*/
if ((packet[0] & 0x48) == 0x48 && (packet[1] & 0x02) == 0x02) {
/* Logitech extended packet */
switch ((packet[1] >> 4) | (packet[0] & 0x30)) {
case 0x0d: /* Mouse extra info */
input_report_rel(dev,
packet[2] & 0x80 ? REL_HWHEEL : REL_WHEEL,
-sign_extend32(packet[2], 3));
input_report_key(dev, BTN_SIDE, packet[2] & BIT(4));
input_report_key(dev, BTN_EXTRA, packet[2] & BIT(5));
break;
case 0x0e: /* buttons 4, 5, 6, 7, 8, 9, 10 info */
input_report_key(dev, BTN_SIDE, packet[2] & BIT(0));
input_report_key(dev, BTN_EXTRA, packet[2] & BIT(1));
input_report_key(dev, BTN_TASK, packet[2] & BIT(2));
input_report_key(dev, BTN_BACK, packet[2] & BIT(3));
input_report_key(dev, BTN_FORWARD, packet[2] & BIT(4));
break;
case 0x0f: /* TouchPad extra info */
input_report_rel(dev,
packet[2] & 0x08 ? REL_HWHEEL : REL_WHEEL,
-sign_extend32(packet[2] >> 4, 3));
packet[0] = packet[2] | BIT(3);
break;
default:
psmouse_dbg(psmouse,
"Received PS2++ packet #%x, but don't know how to handle.\n",
(packet[1] >> 4) | (packet[0] & 0x30));
break;
}
psmouse_report_standard_buttons(dev, packet[0]);
} else {
/* Standard PS/2 motion data */
psmouse_report_standard_packet(dev, packet);
}
input_sync(dev);
return PSMOUSE_FULL_PACKET;
}
/*
* ps2pp_cmd() sends a PS2++ command, sliced into two bit
* pieces through the SETRES command. This is needed to send extended
* commands to mice on notebooks that try to understand the PS/2 protocol
* Ugly.
*/
static int ps2pp_cmd(struct psmouse *psmouse, u8 *param, u8 command)
{
int error;
error = ps2_sliced_command(&psmouse->ps2dev, command);
if (error)
return error;
error = ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_POLL | 0x0300);
if (error)
return error;
return 0;
}
/*
* SmartScroll / CruiseControl for some newer Logitech mice Defaults to
* enabled if we do nothing to it. Of course I put this in because I want it
* disabled :P
* 1 - enabled (if previously disabled, also default)
* 0 - disabled
*/
static void ps2pp_set_smartscroll(struct psmouse *psmouse, bool smartscroll)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
u8 param[4];
ps2pp_cmd(psmouse, param, 0x32);
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
param[0] = smartscroll;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
}
static ssize_t ps2pp_attr_show_smartscroll(struct psmouse *psmouse,
void *data, char *buf)
{
return sprintf(buf, "%d\n", psmouse->smartscroll);
}
static ssize_t ps2pp_attr_set_smartscroll(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
ps2pp_set_smartscroll(psmouse, value);
psmouse->smartscroll = value;
return count;
}
PSMOUSE_DEFINE_ATTR(smartscroll, S_IWUSR | S_IRUGO, NULL,
ps2pp_attr_show_smartscroll, ps2pp_attr_set_smartscroll);
/*
* Support 800 dpi resolution _only_ if the user wants it (there are good
* reasons to not use it even if the mouse supports it, and of course there are
* also good reasons to use it, let the user decide).
*/
static void ps2pp_set_resolution(struct psmouse *psmouse,
unsigned int resolution)
{
if (resolution > 400) {
struct ps2dev *ps2dev = &psmouse->ps2dev;
u8 param = 3;
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, ¶m, PSMOUSE_CMD_SETRES);
psmouse->resolution = 800;
} else
psmouse_set_resolution(psmouse, resolution);
}
static void ps2pp_disconnect(struct psmouse *psmouse)
{
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_smartscroll.dattr);
}
static const struct ps2pp_info *get_model_info(unsigned char model)
{
static const struct ps2pp_info ps2pp_list[] = {
{ 1, 0, 0 }, /* Simple 2-button mouse */
{ 12, 0, PS2PP_SIDE_BTN},
{ 13, 0, 0 },
{ 15, PS2PP_KIND_MX, /* MX1000 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 40, 0, PS2PP_SIDE_BTN },
{ 41, 0, PS2PP_SIDE_BTN },
{ 42, 0, PS2PP_SIDE_BTN },
{ 43, 0, PS2PP_SIDE_BTN },
{ 50, 0, 0 },
{ 51, 0, 0 },
{ 52, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 53, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 56, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL }, /* Cordless MouseMan Wheel */
{ 61, PS2PP_KIND_MX, /* MX700 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 66, PS2PP_KIND_MX, /* MX3100 receiver */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 72, PS2PP_KIND_TRACKMAN, 0 }, /* T-CH11: TrackMan Marble */
{ 73, PS2PP_KIND_TRACKMAN, PS2PP_SIDE_BTN }, /* TrackMan FX */
{ 75, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 76, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 79, PS2PP_KIND_TRACKMAN, PS2PP_WHEEL }, /* TrackMan with wheel */
{ 80, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 81, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 83, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 85, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 86, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 87, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 88, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 96, 0, 0 },
{ 97, PS2PP_KIND_TP3, PS2PP_WHEEL | PS2PP_HWHEEL },
{ 99, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 100, PS2PP_KIND_MX, /* MX510 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 111, PS2PP_KIND_MX, PS2PP_WHEEL | PS2PP_SIDE_BTN }, /* MX300 reports task button as side */
{ 112, PS2PP_KIND_MX, /* MX500 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 114, PS2PP_KIND_MX, /* MX310 */
PS2PP_WHEEL | PS2PP_SIDE_BTN |
PS2PP_TASK_BTN | PS2PP_EXTRA_BTN }
};
int i;
for (i = 0; i < ARRAY_SIZE(ps2pp_list); i++)
if (model == ps2pp_list[i].model)
return &ps2pp_list[i];
return NULL;
}
/*
* Set up input device's properties based on the detected mouse model.
*/
static void ps2pp_set_model_properties(struct psmouse *psmouse,
const struct ps2pp_info *model_info,
bool using_ps2pp)
{
struct input_dev *input_dev = psmouse->dev;
if (model_info->features & PS2PP_SIDE_BTN)
input_set_capability(input_dev, EV_KEY, BTN_SIDE);
if (model_info->features & PS2PP_EXTRA_BTN)
input_set_capability(input_dev, EV_KEY, BTN_EXTRA);
if (model_info->features & PS2PP_TASK_BTN)
input_set_capability(input_dev, EV_KEY, BTN_TASK);
if (model_info->features & PS2PP_NAV_BTN) {
input_set_capability(input_dev, EV_KEY, BTN_FORWARD);
input_set_capability(input_dev, EV_KEY, BTN_BACK);
}
if (model_info->features & PS2PP_WHEEL)
input_set_capability(input_dev, EV_REL, REL_WHEEL);
if (model_info->features & PS2PP_HWHEEL)
input_set_capability(input_dev, EV_REL, REL_HWHEEL);
switch (model_info->kind) {
case PS2PP_KIND_WHEEL:
psmouse->name = "Wheel Mouse";
break;
case PS2PP_KIND_MX:
psmouse->name = "MX Mouse";
break;
case PS2PP_KIND_TP3:
psmouse->name = "TouchPad 3";
break;
case PS2PP_KIND_TRACKMAN:
psmouse->name = "TrackMan";
break;
default:
/*
* Set name to "Mouse" only when using PS2++,
* otherwise let other protocols define suitable
* name
*/
if (using_ps2pp)
psmouse->name = "Mouse";
break;
}
}
static int ps2pp_setup_protocol(struct psmouse *psmouse,
const struct ps2pp_info *model_info)
{
int error;
psmouse->protocol_handler = ps2pp_process_byte;
psmouse->pktsize = 3;
if (model_info->kind != PS2PP_KIND_TP3) {
psmouse->set_resolution = ps2pp_set_resolution;
psmouse->disconnect = ps2pp_disconnect;
error = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_smartscroll.dattr);
if (error) {
psmouse_err(psmouse,
"failed to create smartscroll sysfs attribute, error: %d\n",
error);
return error;
}
}
return 0;
}
/*
* Logitech magic init. Detect whether the mouse is a Logitech one
* and its exact model and try turning on extended protocol for ones
* that support it.
*/
int ps2pp_detect(struct psmouse *psmouse, bool set_properties)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
const struct ps2pp_info *model_info;
u8 param[4];
u8 model, buttons;
bool use_ps2pp = false;
int error;
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
param[1] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO);
model = ((param[0] >> 4) & 0x07) | ((param[0] << 3) & 0x78);
buttons = param[1];
if (!model || !buttons)
return -ENXIO;
model_info = get_model_info(model);
if (model_info) {
/*
* Do Logitech PS2++ / PS2T++ magic init.
*/
if (model_info->kind == PS2PP_KIND_TP3) { /* Touch Pad 3 */
/* Unprotect RAM */
param[0] = 0x11; param[1] = 0x04; param[2] = 0x68;
ps2_command(ps2dev, param, 0x30d1);
/* Enable features */
param[0] = 0x11; param[1] = 0x05; param[2] = 0x0b;
ps2_command(ps2dev, param, 0x30d1);
/* Enable PS2++ */
param[0] = 0x11; param[1] = 0x09; param[2] = 0xc3;
ps2_command(ps2dev, param, 0x30d1);
param[0] = 0;
if (!ps2_command(ps2dev, param, 0x13d1) &&
param[0] == 0x06 && param[1] == 0x00 &&
param[2] == 0x14) {
use_ps2pp = true;
}
} else {
param[0] = param[1] = param[2] = 0;
ps2pp_cmd(psmouse, param, 0x39); /* Magic knock */
ps2pp_cmd(psmouse, param, 0xDB);
if ((param[0] & 0x78) == 0x48 &&
(param[1] & 0xf3) == 0xc2 &&
(param[2] & 0x03) == ((param[1] >> 2) & 3)) {
ps2pp_set_smartscroll(psmouse, false);
use_ps2pp = true;
}
}
} else {
psmouse_warn(psmouse,
"Detected unknown Logitech mouse model %d\n",
model);
}
if (set_properties) {
psmouse->vendor = "Logitech";
psmouse->model = model;
if (use_ps2pp) {
error = ps2pp_setup_protocol(psmouse, model_info);
if (error)
return error;
}
if (buttons >= 3)
input_set_capability(psmouse->dev, EV_KEY, BTN_MIDDLE);
if (model_info)
ps2pp_set_model_properties(psmouse, model_info, use_ps2pp);
}
return use_ps2pp ? 0 : -ENXIO;
}
|
linux-master
|
drivers/input/mouse/logips2pp.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/* ----------------------------------------------------------------------------
* touchkit_ps2.c -- Driver for eGalax TouchKit PS/2 Touchscreens
*
* Copyright (C) 2005 by Stefan Lucke
* Copyright (C) 2004 by Daniel Ritz
* Copyright (C) by Todd E. Johnson (mtouchusb.c)
*
* Based upon touchkitusb.c
*
* Vendor documentation is available at:
* http://home.eeti.com.tw/web20/drivers/Software%20Programming%20Guide_v2.0.pdf
*/
#include <linux/kernel.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include "psmouse.h"
#include "touchkit_ps2.h"
#define TOUCHKIT_MAX_XC 0x07ff
#define TOUCHKIT_MAX_YC 0x07ff
#define TOUCHKIT_CMD 0x0a
#define TOUCHKIT_CMD_LENGTH 1
#define TOUCHKIT_CMD_ACTIVE 'A'
#define TOUCHKIT_CMD_FIRMWARE_VERSION 'D'
#define TOUCHKIT_CMD_CONTROLLER_TYPE 'E'
#define TOUCHKIT_SEND_PARMS(s, r, c) ((s) << 12 | (r) << 8 | (c))
#define TOUCHKIT_GET_TOUCHED(packet) (((packet)[0]) & 0x01)
#define TOUCHKIT_GET_X(packet) (((packet)[1] << 7) | (packet)[2])
#define TOUCHKIT_GET_Y(packet) (((packet)[3] << 7) | (packet)[4])
static psmouse_ret_t touchkit_ps2_process_byte(struct psmouse *psmouse)
{
unsigned char *packet = psmouse->packet;
struct input_dev *dev = psmouse->dev;
if (psmouse->pktcnt != 5)
return PSMOUSE_GOOD_DATA;
input_report_abs(dev, ABS_X, TOUCHKIT_GET_X(packet));
input_report_abs(dev, ABS_Y, TOUCHKIT_GET_Y(packet));
input_report_key(dev, BTN_TOUCH, TOUCHKIT_GET_TOUCHED(packet));
input_sync(dev);
return PSMOUSE_FULL_PACKET;
}
int touchkit_ps2_detect(struct psmouse *psmouse, bool set_properties)
{
struct input_dev *dev = psmouse->dev;
unsigned char param[3];
int command;
param[0] = TOUCHKIT_CMD_LENGTH;
param[1] = TOUCHKIT_CMD_ACTIVE;
command = TOUCHKIT_SEND_PARMS(2, 3, TOUCHKIT_CMD);
if (ps2_command(&psmouse->ps2dev, param, command))
return -ENODEV;
if (param[0] != TOUCHKIT_CMD || param[1] != 0x01 ||
param[2] != TOUCHKIT_CMD_ACTIVE)
return -ENODEV;
if (set_properties) {
dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
dev->keybit[BIT_WORD(BTN_MOUSE)] = 0;
dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(dev, ABS_X, 0, TOUCHKIT_MAX_XC, 0, 0);
input_set_abs_params(dev, ABS_Y, 0, TOUCHKIT_MAX_YC, 0, 0);
psmouse->vendor = "eGalax";
psmouse->name = "Touchscreen";
psmouse->protocol_handler = touchkit_ps2_process_byte;
psmouse->pktsize = 5;
}
return 0;
}
|
linux-master
|
drivers/input/mouse/touchkit_ps2.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (c) 2017 Red Hat, Inc
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/libps2.h>
#include <linux/i2c.h>
#include <linux/serio.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include "psmouse.h"
struct psmouse_smbus_dev {
struct i2c_board_info board;
struct psmouse *psmouse;
struct i2c_client *client;
struct list_head node;
bool dead;
bool need_deactivate;
};
static LIST_HEAD(psmouse_smbus_list);
static DEFINE_MUTEX(psmouse_smbus_mutex);
static struct workqueue_struct *psmouse_smbus_wq;
static void psmouse_smbus_check_adapter(struct i2c_adapter *adapter)
{
struct psmouse_smbus_dev *smbdev;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_HOST_NOTIFY))
return;
mutex_lock(&psmouse_smbus_mutex);
list_for_each_entry(smbdev, &psmouse_smbus_list, node) {
if (smbdev->dead)
continue;
if (smbdev->client)
continue;
/*
* Here would be a good place to check if device is actually
* present, but it seems that SMBus will not respond unless we
* fully reset PS/2 connection. So cross our fingers, and try
* to switch over, hopefully our system will not have too many
* "host notify" I2C adapters.
*/
psmouse_dbg(smbdev->psmouse,
"SMBus candidate adapter appeared, triggering rescan\n");
serio_rescan(smbdev->psmouse->ps2dev.serio);
}
mutex_unlock(&psmouse_smbus_mutex);
}
static void psmouse_smbus_detach_i2c_client(struct i2c_client *client)
{
struct psmouse_smbus_dev *smbdev, *tmp;
mutex_lock(&psmouse_smbus_mutex);
list_for_each_entry_safe(smbdev, tmp, &psmouse_smbus_list, node) {
if (smbdev->client != client)
continue;
kfree(client->dev.platform_data);
client->dev.platform_data = NULL;
if (!smbdev->dead) {
psmouse_dbg(smbdev->psmouse,
"Marking SMBus companion %s as gone\n",
dev_name(&smbdev->client->dev));
smbdev->dead = true;
device_link_remove(&smbdev->client->dev,
&smbdev->psmouse->ps2dev.serio->dev);
serio_rescan(smbdev->psmouse->ps2dev.serio);
} else {
list_del(&smbdev->node);
kfree(smbdev);
}
}
mutex_unlock(&psmouse_smbus_mutex);
}
static int psmouse_smbus_notifier_call(struct notifier_block *nb,
unsigned long action, void *data)
{
struct device *dev = data;
switch (action) {
case BUS_NOTIFY_ADD_DEVICE:
if (dev->type == &i2c_adapter_type)
psmouse_smbus_check_adapter(to_i2c_adapter(dev));
break;
case BUS_NOTIFY_REMOVED_DEVICE:
if (dev->type == &i2c_client_type)
psmouse_smbus_detach_i2c_client(to_i2c_client(dev));
break;
}
return 0;
}
static struct notifier_block psmouse_smbus_notifier = {
.notifier_call = psmouse_smbus_notifier_call,
};
static psmouse_ret_t psmouse_smbus_process_byte(struct psmouse *psmouse)
{
return PSMOUSE_FULL_PACKET;
}
static void psmouse_activate_smbus_mode(struct psmouse_smbus_dev *smbdev)
{
if (smbdev->need_deactivate) {
psmouse_deactivate(smbdev->psmouse);
/* Give the device time to switch into SMBus mode */
msleep(30);
}
}
static int psmouse_smbus_reconnect(struct psmouse *psmouse)
{
psmouse_activate_smbus_mode(psmouse->private);
return 0;
}
struct psmouse_smbus_removal_work {
struct work_struct work;
struct i2c_client *client;
};
static void psmouse_smbus_remove_i2c_device(struct work_struct *work)
{
struct psmouse_smbus_removal_work *rwork =
container_of(work, struct psmouse_smbus_removal_work, work);
dev_dbg(&rwork->client->dev, "destroying SMBus companion device\n");
i2c_unregister_device(rwork->client);
kfree(rwork);
}
/*
* This schedules removal of SMBus companion device. We have to do
* it in a separate tread to avoid deadlocking on psmouse_mutex in
* case the device has a trackstick (which is also driven by psmouse).
*
* Note that this may be racing with i2c adapter removal, but we
* can't do anything about that: i2c automatically destroys clients
* attached to an adapter that is being removed. This has to be
* fixed in i2c core.
*/
static void psmouse_smbus_schedule_remove(struct i2c_client *client)
{
struct psmouse_smbus_removal_work *rwork;
rwork = kzalloc(sizeof(*rwork), GFP_KERNEL);
if (rwork) {
INIT_WORK(&rwork->work, psmouse_smbus_remove_i2c_device);
rwork->client = client;
queue_work(psmouse_smbus_wq, &rwork->work);
}
}
static void psmouse_smbus_disconnect(struct psmouse *psmouse)
{
struct psmouse_smbus_dev *smbdev = psmouse->private;
mutex_lock(&psmouse_smbus_mutex);
if (smbdev->dead) {
list_del(&smbdev->node);
kfree(smbdev);
} else {
smbdev->dead = true;
device_link_remove(&smbdev->client->dev,
&psmouse->ps2dev.serio->dev);
psmouse_dbg(smbdev->psmouse,
"posting removal request for SMBus companion %s\n",
dev_name(&smbdev->client->dev));
psmouse_smbus_schedule_remove(smbdev->client);
}
mutex_unlock(&psmouse_smbus_mutex);
psmouse->private = NULL;
}
static int psmouse_smbus_create_companion(struct device *dev, void *data)
{
struct psmouse_smbus_dev *smbdev = data;
unsigned short addr_list[] = { smbdev->board.addr, I2C_CLIENT_END };
struct i2c_adapter *adapter;
struct i2c_client *client;
adapter = i2c_verify_adapter(dev);
if (!adapter)
return 0;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_HOST_NOTIFY))
return 0;
client = i2c_new_scanned_device(adapter, &smbdev->board,
addr_list, NULL);
if (IS_ERR(client))
return 0;
/* We have our(?) device, stop iterating i2c bus. */
smbdev->client = client;
return 1;
}
void psmouse_smbus_cleanup(struct psmouse *psmouse)
{
struct psmouse_smbus_dev *smbdev, *tmp;
mutex_lock(&psmouse_smbus_mutex);
list_for_each_entry_safe(smbdev, tmp, &psmouse_smbus_list, node) {
if (psmouse == smbdev->psmouse) {
list_del(&smbdev->node);
kfree(smbdev);
}
}
mutex_unlock(&psmouse_smbus_mutex);
}
int psmouse_smbus_init(struct psmouse *psmouse,
const struct i2c_board_info *board,
const void *pdata, size_t pdata_size,
bool need_deactivate,
bool leave_breadcrumbs)
{
struct psmouse_smbus_dev *smbdev;
int error;
smbdev = kzalloc(sizeof(*smbdev), GFP_KERNEL);
if (!smbdev)
return -ENOMEM;
smbdev->psmouse = psmouse;
smbdev->board = *board;
smbdev->need_deactivate = need_deactivate;
if (pdata) {
smbdev->board.platform_data = kmemdup(pdata, pdata_size,
GFP_KERNEL);
if (!smbdev->board.platform_data) {
kfree(smbdev);
return -ENOMEM;
}
}
psmouse_activate_smbus_mode(smbdev);
psmouse->private = smbdev;
psmouse->protocol_handler = psmouse_smbus_process_byte;
psmouse->reconnect = psmouse_smbus_reconnect;
psmouse->fast_reconnect = psmouse_smbus_reconnect;
psmouse->disconnect = psmouse_smbus_disconnect;
psmouse->resync_time = 0;
mutex_lock(&psmouse_smbus_mutex);
list_add_tail(&smbdev->node, &psmouse_smbus_list);
mutex_unlock(&psmouse_smbus_mutex);
/* Bind to already existing adapters right away */
error = i2c_for_each_dev(smbdev, psmouse_smbus_create_companion);
if (smbdev->client) {
/* We have our companion device */
if (!device_link_add(&smbdev->client->dev,
&psmouse->ps2dev.serio->dev,
DL_FLAG_STATELESS))
psmouse_warn(psmouse,
"failed to set up link with iSMBus companion %s\n",
dev_name(&smbdev->client->dev));
return 0;
}
/*
* If we did not create i2c device we will not need platform
* data even if we are leaving breadcrumbs.
*/
kfree(smbdev->board.platform_data);
smbdev->board.platform_data = NULL;
if (error < 0 || !leave_breadcrumbs) {
mutex_lock(&psmouse_smbus_mutex);
list_del(&smbdev->node);
mutex_unlock(&psmouse_smbus_mutex);
kfree(smbdev);
}
return error < 0 ? error : -EAGAIN;
}
int __init psmouse_smbus_module_init(void)
{
int error;
psmouse_smbus_wq = alloc_workqueue("psmouse-smbus", 0, 0);
if (!psmouse_smbus_wq)
return -ENOMEM;
error = bus_register_notifier(&i2c_bus_type, &psmouse_smbus_notifier);
if (error) {
pr_err("failed to register i2c bus notifier: %d\n", error);
destroy_workqueue(psmouse_smbus_wq);
return error;
}
return 0;
}
void psmouse_smbus_module_exit(void)
{
bus_unregister_notifier(&i2c_bus_type, &psmouse_smbus_notifier);
destroy_workqueue(psmouse_smbus_wq);
}
|
linux-master
|
drivers/input/mouse/psmouse-smbus.c
|
/*
* Cypress APA trackpad with I2C interface
*
* Author: Dudley Du <[email protected]>
*
* Copyright (C) 2014-2015 Cypress Semiconductor, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/mutex.h>
#include <linux/completion.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include <linux/crc-itu-t.h>
#include <linux/pm_runtime.h>
#include "cyapa.h"
/* Macro of TSG firmware image */
#define CYAPA_TSG_FLASH_MAP_BLOCK_SIZE 0x80
#define CYAPA_TSG_IMG_FW_HDR_SIZE 13
#define CYAPA_TSG_FW_ROW_SIZE (CYAPA_TSG_FLASH_MAP_BLOCK_SIZE)
#define CYAPA_TSG_IMG_START_ROW_NUM 0x002e
#define CYAPA_TSG_IMG_END_ROW_NUM 0x01fe
#define CYAPA_TSG_IMG_APP_INTEGRITY_ROW_NUM 0x01ff
#define CYAPA_TSG_IMG_MAX_RECORDS (CYAPA_TSG_IMG_END_ROW_NUM - \
CYAPA_TSG_IMG_START_ROW_NUM + 1 + 1)
#define CYAPA_TSG_IMG_READ_SIZE (CYAPA_TSG_FLASH_MAP_BLOCK_SIZE / 2)
#define CYAPA_TSG_START_OF_APPLICATION 0x1700
#define CYAPA_TSG_APP_INTEGRITY_SIZE 60
#define CYAPA_TSG_FLASH_MAP_METADATA_SIZE 60
#define CYAPA_TSG_BL_KEY_SIZE 8
#define CYAPA_TSG_MAX_CMD_SIZE 256
/* Macro of PIP interface */
#define PIP_BL_INITIATE_RESP_LEN 11
#define PIP_BL_FAIL_EXIT_RESP_LEN 11
#define PIP_BL_FAIL_EXIT_STATUS_CODE 0x0c
#define PIP_BL_VERIFY_INTEGRITY_RESP_LEN 12
#define PIP_BL_INTEGRITY_CHEKC_PASS 0x00
#define PIP_BL_BLOCK_WRITE_RESP_LEN 11
#define PIP_TOUCH_REPORT_ID 0x01
#define PIP_BTN_REPORT_ID 0x03
#define PIP_WAKEUP_EVENT_REPORT_ID 0x04
#define PIP_PUSH_BTN_REPORT_ID 0x06
#define GEN5_OLD_PUSH_BTN_REPORT_ID 0x05 /* Special for old Gen5 TP. */
#define PIP_PROXIMITY_REPORT_ID 0x07
#define PIP_PROXIMITY_REPORT_SIZE 6
#define PIP_PROXIMITY_DISTANCE_OFFSET 0x05
#define PIP_PROXIMITY_DISTANCE_MASK 0x01
#define PIP_TOUCH_REPORT_HEAD_SIZE 7
#define PIP_TOUCH_REPORT_MAX_SIZE 127
#define PIP_BTN_REPORT_HEAD_SIZE 6
#define PIP_BTN_REPORT_MAX_SIZE 14
#define PIP_WAKEUP_EVENT_SIZE 4
#define PIP_NUMBER_OF_TOUCH_OFFSET 5
#define PIP_NUMBER_OF_TOUCH_MASK 0x1f
#define PIP_BUTTONS_OFFSET 5
#define PIP_BUTTONS_MASK 0x0f
#define PIP_GET_EVENT_ID(reg) (((reg) >> 5) & 0x03)
#define PIP_GET_TOUCH_ID(reg) ((reg) & 0x1f)
#define PIP_TOUCH_TYPE_FINGER 0x00
#define PIP_TOUCH_TYPE_PROXIMITY 0x01
#define PIP_TOUCH_TYPE_HOVER 0x02
#define PIP_GET_TOUCH_TYPE(reg) ((reg) & 0x07)
#define RECORD_EVENT_NONE 0
#define RECORD_EVENT_TOUCHDOWN 1
#define RECORD_EVENT_DISPLACE 2
#define RECORD_EVENT_LIFTOFF 3
#define PIP_SENSING_MODE_MUTUAL_CAP_FINE 0x00
#define PIP_SENSING_MODE_SELF_CAP 0x02
#define PIP_SET_PROXIMITY 0x49
/* Macro of Gen5 */
#define GEN5_BL_MAX_OUTPUT_LENGTH 0x0100
#define GEN5_APP_MAX_OUTPUT_LENGTH 0x00fe
#define GEN5_POWER_STATE_ACTIVE 0x01
#define GEN5_POWER_STATE_LOOK_FOR_TOUCH 0x02
#define GEN5_POWER_STATE_READY 0x03
#define GEN5_POWER_STATE_IDLE 0x04
#define GEN5_POWER_STATE_BTN_ONLY 0x05
#define GEN5_POWER_STATE_OFF 0x06
#define GEN5_POWER_READY_MAX_INTRVL_TIME 50 /* Unit: ms */
#define GEN5_POWER_IDLE_MAX_INTRVL_TIME 250 /* Unit: ms */
#define GEN5_CMD_GET_PARAMETER 0x05
#define GEN5_CMD_SET_PARAMETER 0x06
#define GEN5_PARAMETER_ACT_INTERVL_ID 0x4d
#define GEN5_PARAMETER_ACT_INTERVL_SIZE 1
#define GEN5_PARAMETER_ACT_LFT_INTERVL_ID 0x4f
#define GEN5_PARAMETER_ACT_LFT_INTERVL_SIZE 2
#define GEN5_PARAMETER_LP_INTRVL_ID 0x4c
#define GEN5_PARAMETER_LP_INTRVL_SIZE 2
#define GEN5_PARAMETER_DISABLE_PIP_REPORT 0x08
#define GEN5_BL_REPORT_DESCRIPTOR_SIZE 0x1d
#define GEN5_BL_REPORT_DESCRIPTOR_ID 0xfe
#define GEN5_APP_REPORT_DESCRIPTOR_SIZE 0xee
#define GEN5_APP_CONTRACT_REPORT_DESCRIPTOR_SIZE 0xfa
#define GEN5_APP_REPORT_DESCRIPTOR_ID 0xf6
#define GEN5_RETRIEVE_MUTUAL_PWC_DATA 0x00
#define GEN5_RETRIEVE_SELF_CAP_PWC_DATA 0x01
#define GEN5_RETRIEVE_DATA_ELEMENT_SIZE_MASK 0x07
#define GEN5_CMD_EXECUTE_PANEL_SCAN 0x2a
#define GEN5_CMD_RETRIEVE_PANEL_SCAN 0x2b
#define GEN5_PANEL_SCAN_MUTUAL_RAW_DATA 0x00
#define GEN5_PANEL_SCAN_MUTUAL_BASELINE 0x01
#define GEN5_PANEL_SCAN_MUTUAL_DIFFCOUNT 0x02
#define GEN5_PANEL_SCAN_SELF_RAW_DATA 0x03
#define GEN5_PANEL_SCAN_SELF_BASELINE 0x04
#define GEN5_PANEL_SCAN_SELF_DIFFCOUNT 0x05
/* The offset only valid for retrieve PWC and panel scan commands */
#define GEN5_RESP_DATA_STRUCTURE_OFFSET 10
#define GEN5_PWC_DATA_ELEMENT_SIZE_MASK 0x07
struct cyapa_pip_touch_record {
/*
* Bit 7 - 3: reserved
* Bit 2 - 0: touch type;
* 0 : standard finger;
* 1 : proximity (Start supported in Gen5 TP).
* 2 : finger hover (defined, but not used yet.)
* 3 - 15 : reserved.
*/
u8 touch_type;
/*
* Bit 7: indicates touch liftoff status.
* 0 : touch is currently on the panel.
* 1 : touch record indicates a liftoff.
* Bit 6 - 5: indicates an event associated with this touch instance
* 0 : no event
* 1 : touchdown
* 2 : significant displacement (> active distance)
* 3 : liftoff (record reports last known coordinates)
* Bit 4 - 0: An arbitrary ID tag associated with a finger
* to allow tracking a touch as it moves around the panel.
*/
u8 touch_tip_event_id;
/* Bit 7 - 0 of X-axis coordinate of the touch in pixel. */
u8 x_lo;
/* Bit 15 - 8 of X-axis coordinate of the touch in pixel. */
u8 x_hi;
/* Bit 7 - 0 of Y-axis coordinate of the touch in pixel. */
u8 y_lo;
/* Bit 15 - 8 of Y-axis coordinate of the touch in pixel. */
u8 y_hi;
/*
* The meaning of this value is different when touch_type is different.
* For standard finger type:
* Touch intensity in counts, pressure value.
* For proximity type (Start supported in Gen5 TP):
* The distance, in surface units, between the contact and
* the surface.
**/
u8 z;
/*
* The length of the major axis of the ellipse of contact between
* the finger and the panel (ABS_MT_TOUCH_MAJOR).
*/
u8 major_axis_len;
/*
* The length of the minor axis of the ellipse of contact between
* the finger and the panel (ABS_MT_TOUCH_MINOR).
*/
u8 minor_axis_len;
/*
* The length of the major axis of the approaching tool.
* (ABS_MT_WIDTH_MAJOR)
*/
u8 major_tool_len;
/*
* The length of the minor axis of the approaching tool.
* (ABS_MT_WIDTH_MINOR)
*/
u8 minor_tool_len;
/*
* The angle between the panel vertical axis and
* the major axis of the contact ellipse. This value is an 8-bit
* signed integer. The range is -127 to +127 (corresponding to
* -90 degree and +90 degree respectively).
* The positive direction is clockwise from the vertical axis.
* If the ellipse of contact degenerates into a circle,
* orientation is reported as 0.
*/
u8 orientation;
} __packed;
struct cyapa_pip_report_data {
u8 report_head[PIP_TOUCH_REPORT_HEAD_SIZE];
struct cyapa_pip_touch_record touch_records[10];
} __packed;
struct cyapa_tsg_bin_image_head {
u8 head_size; /* Unit: bytes, including itself. */
u8 ttda_driver_major_version; /* Reserved as 0. */
u8 ttda_driver_minor_version; /* Reserved as 0. */
u8 fw_major_version;
u8 fw_minor_version;
u8 fw_revision_control_number[8];
u8 silicon_id_hi;
u8 silicon_id_lo;
u8 chip_revision;
u8 family_id;
u8 bl_ver_maj;
u8 bl_ver_min;
} __packed;
struct cyapa_tsg_bin_image_data_record {
u8 flash_array_id;
__be16 row_number;
/* The number of bytes of flash data contained in this record. */
__be16 record_len;
/* The flash program data. */
u8 record_data[CYAPA_TSG_FW_ROW_SIZE];
} __packed;
struct cyapa_tsg_bin_image {
struct cyapa_tsg_bin_image_head image_head;
struct cyapa_tsg_bin_image_data_record records[];
} __packed;
struct pip_bl_packet_start {
u8 sop; /* Start of packet, must be 01h */
u8 cmd_code;
__le16 data_length; /* Size of data parameter start from data[0] */
} __packed;
struct pip_bl_packet_end {
__le16 crc;
u8 eop; /* End of packet, must be 17h */
} __packed;
struct pip_bl_cmd_head {
__le16 addr; /* Output report register address, must be 0004h */
/* Size of packet not including output report register address */
__le16 length;
u8 report_id; /* Bootloader output report id, must be 40h */
u8 rsvd; /* Reserved, must be 0 */
struct pip_bl_packet_start packet_start;
u8 data[]; /* Command data variable based on commands */
} __packed;
/* Initiate bootload command data structure. */
struct pip_bl_initiate_cmd_data {
/* Key must be "A5h 01h 02h 03h FFh FEh FDh 5Ah" */
u8 key[CYAPA_TSG_BL_KEY_SIZE];
u8 metadata_raw_parameter[CYAPA_TSG_FLASH_MAP_METADATA_SIZE];
__le16 metadata_crc;
} __packed;
struct tsg_bl_metadata_row_params {
__le16 size;
__le16 maximum_size;
__le32 app_start;
__le16 app_len;
__le16 app_crc;
__le32 app_entry;
__le32 upgrade_start;
__le16 upgrade_len;
__le16 entry_row_crc;
u8 padding[36]; /* Padding data must be 0 */
__le16 metadata_crc; /* CRC starts at offset of 60 */
} __packed;
/* Bootload program and verify row command data structure */
struct tsg_bl_flash_row_head {
u8 flash_array_id;
__le16 flash_row_id;
u8 flash_data[];
} __packed;
struct pip_app_cmd_head {
__le16 addr; /* Output report register address, must be 0004h */
/* Size of packet not including output report register address */
__le16 length;
u8 report_id; /* Application output report id, must be 2Fh */
u8 rsvd; /* Reserved, must be 0 */
/*
* Bit 7: reserved, must be 0.
* Bit 6-0: command code.
*/
u8 cmd_code;
u8 parameter_data[]; /* Parameter data variable based on cmd_code */
} __packed;
/* Application get/set parameter command data structure */
struct gen5_app_set_parameter_data {
u8 parameter_id;
u8 parameter_size;
__le32 value;
} __packed;
struct gen5_app_get_parameter_data {
u8 parameter_id;
} __packed;
struct gen5_retrieve_panel_scan_data {
__le16 read_offset;
__le16 read_elements;
u8 data_id;
} __packed;
u8 pip_read_sys_info[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, 0x02 };
u8 pip_bl_read_app_info[] = { 0x04, 0x00, 0x0b, 0x00, 0x40, 0x00,
0x01, 0x3c, 0x00, 0x00, 0xb0, 0x42, 0x17
};
static u8 cyapa_pip_bl_cmd_key[] = { 0xa5, 0x01, 0x02, 0x03,
0xff, 0xfe, 0xfd, 0x5a };
static int cyapa_pip_event_process(struct cyapa *cyapa,
struct cyapa_pip_report_data *report_data);
int cyapa_pip_cmd_state_initialize(struct cyapa *cyapa)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
init_completion(&pip->cmd_ready);
atomic_set(&pip->cmd_issued, 0);
mutex_init(&pip->cmd_lock);
mutex_init(&pip->pm_stage_lock);
pip->pm_stage = CYAPA_PM_DEACTIVE;
pip->resp_sort_func = NULL;
pip->in_progress_cmd = PIP_INVALID_CMD;
pip->resp_data = NULL;
pip->resp_len = NULL;
cyapa->dev_pwr_mode = UNINIT_PWR_MODE;
cyapa->dev_sleep_time = UNINIT_SLEEP_TIME;
return 0;
}
/* Return negative errno, or else the number of bytes read. */
ssize_t cyapa_i2c_pip_read(struct cyapa *cyapa, u8 *buf, size_t size)
{
int ret;
if (size == 0)
return 0;
if (!buf || size > CYAPA_REG_MAP_SIZE)
return -EINVAL;
ret = i2c_master_recv(cyapa->client, buf, size);
if (ret != size)
return (ret < 0) ? ret : -EIO;
return size;
}
/*
* Return a negative errno code else zero on success.
*/
ssize_t cyapa_i2c_pip_write(struct cyapa *cyapa, u8 *buf, size_t size)
{
int ret;
if (!buf || !size)
return -EINVAL;
ret = i2c_master_send(cyapa->client, buf, size);
if (ret != size)
return (ret < 0) ? ret : -EIO;
return 0;
}
static void cyapa_set_pip_pm_state(struct cyapa *cyapa,
enum cyapa_pm_stage pm_stage)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
mutex_lock(&pip->pm_stage_lock);
pip->pm_stage = pm_stage;
mutex_unlock(&pip->pm_stage_lock);
}
static void cyapa_reset_pip_pm_state(struct cyapa *cyapa)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
/* Indicates the pip->pm_stage is not valid. */
mutex_lock(&pip->pm_stage_lock);
pip->pm_stage = CYAPA_PM_DEACTIVE;
mutex_unlock(&pip->pm_stage_lock);
}
static enum cyapa_pm_stage cyapa_get_pip_pm_state(struct cyapa *cyapa)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
enum cyapa_pm_stage pm_stage;
mutex_lock(&pip->pm_stage_lock);
pm_stage = pip->pm_stage;
mutex_unlock(&pip->pm_stage_lock);
return pm_stage;
}
/*
* This function is aimed to dump all not read data in Gen5 trackpad
* before send any command, otherwise, the interrupt line will be blocked.
*/
int cyapa_empty_pip_output_data(struct cyapa *cyapa,
u8 *buf, int *len, cb_sort func)
{
struct input_dev *input = cyapa->input;
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
enum cyapa_pm_stage pm_stage = cyapa_get_pip_pm_state(cyapa);
int length;
int report_count;
int empty_count;
int buf_len;
int error;
buf_len = 0;
if (len) {
buf_len = (*len < CYAPA_REG_MAP_SIZE) ?
*len : CYAPA_REG_MAP_SIZE;
*len = 0;
}
report_count = 8; /* max 7 pending data before command response data */
empty_count = 0;
do {
/*
* Depending on testing in cyapa driver, there are max 5 "02 00"
* packets between two valid buffered data report in firmware.
* So in order to dump all buffered data out and
* make interrupt line release for reassert again,
* we must set the empty_count check value bigger than 5 to
* make it work. Otherwise, in some situation,
* the interrupt line may unable to reactive again,
* which will cause trackpad device unable to
* report data any more.
* for example, it may happen in EFT and ESD testing.
*/
if (empty_count > 5)
return 0;
error = cyapa_i2c_pip_read(cyapa, pip->empty_buf,
PIP_RESP_LENGTH_SIZE);
if (error < 0)
return error;
length = get_unaligned_le16(pip->empty_buf);
if (length == PIP_RESP_LENGTH_SIZE) {
empty_count++;
continue;
} else if (length > CYAPA_REG_MAP_SIZE) {
/* Should not happen */
return -EINVAL;
} else if (length == 0) {
/* Application or bootloader launch data polled out. */
length = PIP_RESP_LENGTH_SIZE;
if (buf && buf_len && func &&
func(cyapa, pip->empty_buf, length)) {
length = min(buf_len, length);
memcpy(buf, pip->empty_buf, length);
*len = length;
/* Response found, success. */
return 0;
}
continue;
}
error = cyapa_i2c_pip_read(cyapa, pip->empty_buf, length);
if (error < 0)
return error;
report_count--;
empty_count = 0;
length = get_unaligned_le16(pip->empty_buf);
if (length <= PIP_RESP_LENGTH_SIZE) {
empty_count++;
} else if (buf && buf_len && func &&
func(cyapa, pip->empty_buf, length)) {
length = min(buf_len, length);
memcpy(buf, pip->empty_buf, length);
*len = length;
/* Response found, success. */
return 0;
} else if (cyapa->operational &&
input && input_device_enabled(input) &&
(pm_stage == CYAPA_PM_RUNTIME_RESUME ||
pm_stage == CYAPA_PM_RUNTIME_SUSPEND)) {
/* Parse the data and report it if it's valid. */
cyapa_pip_event_process(cyapa,
(struct cyapa_pip_report_data *)pip->empty_buf);
}
error = -EINVAL;
} while (report_count);
return error;
}
static int cyapa_do_i2c_pip_cmd_irq_sync(
struct cyapa *cyapa,
u8 *cmd, size_t cmd_len,
unsigned long timeout)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
int error;
/* Wait for interrupt to set ready completion */
init_completion(&pip->cmd_ready);
atomic_inc(&pip->cmd_issued);
error = cyapa_i2c_pip_write(cyapa, cmd, cmd_len);
if (error) {
atomic_dec(&pip->cmd_issued);
return (error < 0) ? error : -EIO;
}
/* Wait for interrupt to indicate command is completed. */
timeout = wait_for_completion_timeout(&pip->cmd_ready,
msecs_to_jiffies(timeout));
if (timeout == 0) {
atomic_dec(&pip->cmd_issued);
return -ETIMEDOUT;
}
return 0;
}
static int cyapa_do_i2c_pip_cmd_polling(
struct cyapa *cyapa,
u8 *cmd, size_t cmd_len,
u8 *resp_data, int *resp_len,
unsigned long timeout,
cb_sort func)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
int tries;
int length;
int error;
atomic_inc(&pip->cmd_issued);
error = cyapa_i2c_pip_write(cyapa, cmd, cmd_len);
if (error) {
atomic_dec(&pip->cmd_issued);
return error < 0 ? error : -EIO;
}
length = resp_len ? *resp_len : 0;
if (resp_data && resp_len && length != 0 && func) {
tries = timeout / 5;
do {
usleep_range(3000, 5000);
*resp_len = length;
error = cyapa_empty_pip_output_data(cyapa,
resp_data, resp_len, func);
if (error || *resp_len == 0)
continue;
else
break;
} while (--tries > 0);
if ((error || *resp_len == 0) || tries <= 0)
error = error ? error : -ETIMEDOUT;
}
atomic_dec(&pip->cmd_issued);
return error;
}
int cyapa_i2c_pip_cmd_irq_sync(
struct cyapa *cyapa,
u8 *cmd, int cmd_len,
u8 *resp_data, int *resp_len,
unsigned long timeout,
cb_sort func,
bool irq_mode)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
int error;
if (!cmd || !cmd_len)
return -EINVAL;
/* Commands must be serialized. */
error = mutex_lock_interruptible(&pip->cmd_lock);
if (error)
return error;
pip->resp_sort_func = func;
pip->resp_data = resp_data;
pip->resp_len = resp_len;
if (cmd_len >= PIP_MIN_APP_CMD_LENGTH &&
cmd[4] == PIP_APP_CMD_REPORT_ID) {
/* Application command */
pip->in_progress_cmd = cmd[6] & 0x7f;
} else if (cmd_len >= PIP_MIN_BL_CMD_LENGTH &&
cmd[4] == PIP_BL_CMD_REPORT_ID) {
/* Bootloader command */
pip->in_progress_cmd = cmd[7];
}
/* Send command data, wait and read output response data's length. */
if (irq_mode) {
pip->is_irq_mode = true;
error = cyapa_do_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
timeout);
if (error == -ETIMEDOUT && resp_data &&
resp_len && *resp_len != 0 && func) {
/*
* For some old version, there was no interrupt for
* the command response data, so need to poll here
* to try to get the response data.
*/
error = cyapa_empty_pip_output_data(cyapa,
resp_data, resp_len, func);
if (error || *resp_len == 0)
error = error ? error : -ETIMEDOUT;
}
} else {
pip->is_irq_mode = false;
error = cyapa_do_i2c_pip_cmd_polling(cyapa, cmd, cmd_len,
resp_data, resp_len, timeout, func);
}
pip->resp_sort_func = NULL;
pip->resp_data = NULL;
pip->resp_len = NULL;
pip->in_progress_cmd = PIP_INVALID_CMD;
mutex_unlock(&pip->cmd_lock);
return error;
}
bool cyapa_sort_tsg_pip_bl_resp_data(struct cyapa *cyapa,
u8 *data, int len)
{
if (!data || len < PIP_MIN_BL_RESP_LENGTH)
return false;
/* Bootloader input report id 30h */
if (data[PIP_RESP_REPORT_ID_OFFSET] == PIP_BL_RESP_REPORT_ID &&
data[PIP_RESP_RSVD_OFFSET] == PIP_RESP_RSVD_KEY &&
data[PIP_RESP_BL_SOP_OFFSET] == PIP_SOP_KEY)
return true;
return false;
}
bool cyapa_sort_tsg_pip_app_resp_data(struct cyapa *cyapa,
u8 *data, int len)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
int resp_len;
if (!data || len < PIP_MIN_APP_RESP_LENGTH)
return false;
if (data[PIP_RESP_REPORT_ID_OFFSET] == PIP_APP_RESP_REPORT_ID &&
data[PIP_RESP_RSVD_OFFSET] == PIP_RESP_RSVD_KEY) {
resp_len = get_unaligned_le16(&data[PIP_RESP_LENGTH_OFFSET]);
if (GET_PIP_CMD_CODE(data[PIP_RESP_APP_CMD_OFFSET]) == 0x00 &&
resp_len == PIP_UNSUPPORTED_CMD_RESP_LENGTH &&
data[5] == pip->in_progress_cmd) {
/* Unsupported command code */
return false;
} else if (GET_PIP_CMD_CODE(data[PIP_RESP_APP_CMD_OFFSET]) ==
pip->in_progress_cmd) {
/* Correct command response received */
return true;
}
}
return false;
}
static bool cyapa_sort_pip_application_launch_data(struct cyapa *cyapa,
u8 *buf, int len)
{
if (buf == NULL || len < PIP_RESP_LENGTH_SIZE)
return false;
/*
* After reset or power on, trackpad device always sets to 0x00 0x00
* to indicate a reset or power on event.
*/
if (buf[0] == 0 && buf[1] == 0)
return true;
return false;
}
static bool cyapa_sort_gen5_hid_descriptor_data(struct cyapa *cyapa,
u8 *buf, int len)
{
int resp_len;
int max_output_len;
/* Check hid descriptor. */
if (len != PIP_HID_DESCRIPTOR_SIZE)
return false;
resp_len = get_unaligned_le16(&buf[PIP_RESP_LENGTH_OFFSET]);
max_output_len = get_unaligned_le16(&buf[16]);
if (resp_len == PIP_HID_DESCRIPTOR_SIZE) {
if (buf[PIP_RESP_REPORT_ID_OFFSET] == PIP_HID_BL_REPORT_ID &&
max_output_len == GEN5_BL_MAX_OUTPUT_LENGTH) {
/* BL mode HID Descriptor */
return true;
} else if ((buf[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_HID_APP_REPORT_ID) &&
max_output_len == GEN5_APP_MAX_OUTPUT_LENGTH) {
/* APP mode HID Descriptor */
return true;
}
}
return false;
}
static bool cyapa_sort_pip_deep_sleep_data(struct cyapa *cyapa,
u8 *buf, int len)
{
if (len == PIP_DEEP_SLEEP_RESP_LENGTH &&
buf[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_APP_DEEP_SLEEP_REPORT_ID &&
(buf[4] & PIP_DEEP_SLEEP_OPCODE_MASK) ==
PIP_DEEP_SLEEP_OPCODE)
return true;
return false;
}
static int gen5_idle_state_parse(struct cyapa *cyapa)
{
u8 resp_data[PIP_HID_DESCRIPTOR_SIZE];
int max_output_len;
int length;
u8 cmd[2];
int ret;
int error;
/*
* Dump all buffered data firstly for the situation
* when the trackpad is just power on the cyapa go here.
*/
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
memset(resp_data, 0, sizeof(resp_data));
ret = cyapa_i2c_pip_read(cyapa, resp_data, 3);
if (ret != 3)
return ret < 0 ? ret : -EIO;
length = get_unaligned_le16(&resp_data[PIP_RESP_LENGTH_OFFSET]);
if (length == PIP_RESP_LENGTH_SIZE) {
/* Normal state of Gen5 with no data to response */
cyapa->gen = CYAPA_GEN5;
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
/* Read description from trackpad device */
cmd[0] = 0x01;
cmd[1] = 0x00;
length = PIP_HID_DESCRIPTOR_SIZE;
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, PIP_RESP_LENGTH_SIZE,
resp_data, &length,
300,
cyapa_sort_gen5_hid_descriptor_data,
false);
if (error)
return error;
length = get_unaligned_le16(
&resp_data[PIP_RESP_LENGTH_OFFSET]);
max_output_len = get_unaligned_le16(&resp_data[16]);
if ((length == PIP_HID_DESCRIPTOR_SIZE ||
length == PIP_RESP_LENGTH_SIZE) &&
(resp_data[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_HID_BL_REPORT_ID) &&
max_output_len == GEN5_BL_MAX_OUTPUT_LENGTH) {
/* BL mode HID Description read */
cyapa->state = CYAPA_STATE_GEN5_BL;
} else if ((length == PIP_HID_DESCRIPTOR_SIZE ||
length == PIP_RESP_LENGTH_SIZE) &&
(resp_data[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_HID_APP_REPORT_ID) &&
max_output_len == GEN5_APP_MAX_OUTPUT_LENGTH) {
/* APP mode HID Description read */
cyapa->state = CYAPA_STATE_GEN5_APP;
} else {
/* Should not happen!!! */
cyapa->state = CYAPA_STATE_NO_DEVICE;
}
}
return 0;
}
static int gen5_hid_description_header_parse(struct cyapa *cyapa, u8 *reg_data)
{
int length;
u8 resp_data[32];
int max_output_len;
int ret;
/* 0x20 0x00 0xF7 is Gen5 Application HID Description Header;
* 0x20 0x00 0xFF is Gen5 Bootloader HID Description Header.
*
* Must read HID Description content through out,
* otherwise Gen5 trackpad cannot response next command
* or report any touch or button data.
*/
ret = cyapa_i2c_pip_read(cyapa, resp_data,
PIP_HID_DESCRIPTOR_SIZE);
if (ret != PIP_HID_DESCRIPTOR_SIZE)
return ret < 0 ? ret : -EIO;
length = get_unaligned_le16(&resp_data[PIP_RESP_LENGTH_OFFSET]);
max_output_len = get_unaligned_le16(&resp_data[16]);
if (length == PIP_RESP_LENGTH_SIZE) {
if (reg_data[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_HID_BL_REPORT_ID) {
/*
* BL mode HID Description has been previously
* read out.
*/
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_BL;
} else {
/*
* APP mode HID Description has been previously
* read out.
*/
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_APP;
}
} else if (length == PIP_HID_DESCRIPTOR_SIZE &&
resp_data[2] == PIP_HID_BL_REPORT_ID &&
max_output_len == GEN5_BL_MAX_OUTPUT_LENGTH) {
/* BL mode HID Description read. */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_BL;
} else if (length == PIP_HID_DESCRIPTOR_SIZE &&
(resp_data[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_HID_APP_REPORT_ID) &&
max_output_len == GEN5_APP_MAX_OUTPUT_LENGTH) {
/* APP mode HID Description read. */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_APP;
} else {
/* Should not happen!!! */
cyapa->state = CYAPA_STATE_NO_DEVICE;
}
return 0;
}
static int gen5_report_data_header_parse(struct cyapa *cyapa, u8 *reg_data)
{
int length;
length = get_unaligned_le16(®_data[PIP_RESP_LENGTH_OFFSET]);
switch (reg_data[PIP_RESP_REPORT_ID_OFFSET]) {
case PIP_TOUCH_REPORT_ID:
if (length < PIP_TOUCH_REPORT_HEAD_SIZE ||
length > PIP_TOUCH_REPORT_MAX_SIZE)
return -EINVAL;
break;
case PIP_BTN_REPORT_ID:
case GEN5_OLD_PUSH_BTN_REPORT_ID:
case PIP_PUSH_BTN_REPORT_ID:
if (length < PIP_BTN_REPORT_HEAD_SIZE ||
length > PIP_BTN_REPORT_MAX_SIZE)
return -EINVAL;
break;
case PIP_WAKEUP_EVENT_REPORT_ID:
if (length != PIP_WAKEUP_EVENT_SIZE)
return -EINVAL;
break;
default:
return -EINVAL;
}
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_APP;
return 0;
}
static int gen5_cmd_resp_header_parse(struct cyapa *cyapa, u8 *reg_data)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
int length;
int ret;
/*
* Must read report data through out,
* otherwise Gen5 trackpad cannot response next command
* or report any touch or button data.
*/
length = get_unaligned_le16(®_data[PIP_RESP_LENGTH_OFFSET]);
ret = cyapa_i2c_pip_read(cyapa, pip->empty_buf, length);
if (ret != length)
return ret < 0 ? ret : -EIO;
if (length == PIP_RESP_LENGTH_SIZE) {
/* Previous command has read the data through out. */
if (reg_data[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_BL_RESP_REPORT_ID) {
/* Gen5 BL command response data detected */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_BL;
} else {
/* Gen5 APP command response data detected */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_APP;
}
} else if ((pip->empty_buf[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_BL_RESP_REPORT_ID) &&
(pip->empty_buf[PIP_RESP_RSVD_OFFSET] ==
PIP_RESP_RSVD_KEY) &&
(pip->empty_buf[PIP_RESP_BL_SOP_OFFSET] ==
PIP_SOP_KEY) &&
(pip->empty_buf[length - 1] ==
PIP_EOP_KEY)) {
/* Gen5 BL command response data detected */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_BL;
} else if (pip->empty_buf[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_APP_RESP_REPORT_ID &&
pip->empty_buf[PIP_RESP_RSVD_OFFSET] ==
PIP_RESP_RSVD_KEY) {
/* Gen5 APP command response data detected */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_APP;
} else {
/* Should not happen!!! */
cyapa->state = CYAPA_STATE_NO_DEVICE;
}
return 0;
}
static int cyapa_gen5_state_parse(struct cyapa *cyapa, u8 *reg_data, int len)
{
int length;
if (!reg_data || len < 3)
return -EINVAL;
cyapa->state = CYAPA_STATE_NO_DEVICE;
/* Parse based on Gen5 characteristic registers and bits */
length = get_unaligned_le16(®_data[PIP_RESP_LENGTH_OFFSET]);
if (length == 0 || length == PIP_RESP_LENGTH_SIZE) {
gen5_idle_state_parse(cyapa);
} else if (length == PIP_HID_DESCRIPTOR_SIZE &&
(reg_data[2] == PIP_HID_BL_REPORT_ID ||
reg_data[2] == PIP_HID_APP_REPORT_ID)) {
gen5_hid_description_header_parse(cyapa, reg_data);
} else if ((length == GEN5_APP_REPORT_DESCRIPTOR_SIZE ||
length == GEN5_APP_CONTRACT_REPORT_DESCRIPTOR_SIZE) &&
reg_data[2] == GEN5_APP_REPORT_DESCRIPTOR_ID) {
/* 0xEE 0x00 0xF6 is Gen5 APP report description header. */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_APP;
} else if (length == GEN5_BL_REPORT_DESCRIPTOR_SIZE &&
reg_data[2] == GEN5_BL_REPORT_DESCRIPTOR_ID) {
/* 0x1D 0x00 0xFE is Gen5 BL report descriptor header. */
cyapa->gen = CYAPA_GEN5;
cyapa->state = CYAPA_STATE_GEN5_BL;
} else if (reg_data[2] == PIP_TOUCH_REPORT_ID ||
reg_data[2] == PIP_BTN_REPORT_ID ||
reg_data[2] == GEN5_OLD_PUSH_BTN_REPORT_ID ||
reg_data[2] == PIP_PUSH_BTN_REPORT_ID ||
reg_data[2] == PIP_WAKEUP_EVENT_REPORT_ID) {
gen5_report_data_header_parse(cyapa, reg_data);
} else if (reg_data[2] == PIP_BL_RESP_REPORT_ID ||
reg_data[2] == PIP_APP_RESP_REPORT_ID) {
gen5_cmd_resp_header_parse(cyapa, reg_data);
}
if (cyapa->gen == CYAPA_GEN5) {
/*
* Must read the content (e.g.: report description and so on)
* from trackpad device throughout. Otherwise,
* Gen5 trackpad cannot response to next command or
* report any touch or button data later.
*/
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
if (cyapa->state == CYAPA_STATE_GEN5_APP ||
cyapa->state == CYAPA_STATE_GEN5_BL)
return 0;
}
return -EAGAIN;
}
static struct cyapa_tsg_bin_image_data_record *
cyapa_get_image_record_data_num(const struct firmware *fw,
int *record_num)
{
int head_size;
head_size = fw->data[0] + 1;
*record_num = (fw->size - head_size) /
sizeof(struct cyapa_tsg_bin_image_data_record);
return (struct cyapa_tsg_bin_image_data_record *)&fw->data[head_size];
}
int cyapa_pip_bl_initiate(struct cyapa *cyapa, const struct firmware *fw)
{
struct cyapa_tsg_bin_image_data_record *image_records;
struct pip_bl_cmd_head *bl_cmd_head;
struct pip_bl_packet_start *bl_packet_start;
struct pip_bl_initiate_cmd_data *cmd_data;
struct pip_bl_packet_end *bl_packet_end;
u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
int cmd_len;
u16 cmd_data_len;
u16 cmd_crc = 0;
u16 meta_data_crc = 0;
u8 resp_data[11];
int resp_len;
int records_num;
u8 *data;
int error;
/* Try to dump all buffered report data before any send command. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
bl_cmd_head = (struct pip_bl_cmd_head *)cmd;
cmd_data_len = CYAPA_TSG_BL_KEY_SIZE + CYAPA_TSG_FLASH_MAP_BLOCK_SIZE;
cmd_len = sizeof(struct pip_bl_cmd_head) + cmd_data_len +
sizeof(struct pip_bl_packet_end);
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &bl_cmd_head->addr);
put_unaligned_le16(cmd_len - 2, &bl_cmd_head->length);
bl_cmd_head->report_id = PIP_BL_CMD_REPORT_ID;
bl_packet_start = &bl_cmd_head->packet_start;
bl_packet_start->sop = PIP_SOP_KEY;
bl_packet_start->cmd_code = PIP_BL_CMD_INITIATE_BL;
/* 8 key bytes and 128 bytes block size */
put_unaligned_le16(cmd_data_len, &bl_packet_start->data_length);
cmd_data = (struct pip_bl_initiate_cmd_data *)bl_cmd_head->data;
memcpy(cmd_data->key, cyapa_pip_bl_cmd_key, CYAPA_TSG_BL_KEY_SIZE);
image_records = cyapa_get_image_record_data_num(fw, &records_num);
/* APP_INTEGRITY row is always the last row block */
data = image_records[records_num - 1].record_data;
memcpy(cmd_data->metadata_raw_parameter, data,
CYAPA_TSG_FLASH_MAP_METADATA_SIZE);
meta_data_crc = crc_itu_t(0xffff, cmd_data->metadata_raw_parameter,
CYAPA_TSG_FLASH_MAP_METADATA_SIZE);
put_unaligned_le16(meta_data_crc, &cmd_data->metadata_crc);
bl_packet_end = (struct pip_bl_packet_end *)(bl_cmd_head->data +
cmd_data_len);
cmd_crc = crc_itu_t(0xffff, (u8 *)bl_packet_start,
sizeof(struct pip_bl_packet_start) + cmd_data_len);
put_unaligned_le16(cmd_crc, &bl_packet_end->crc);
bl_packet_end->eop = PIP_EOP_KEY;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, cmd_len,
resp_data, &resp_len, 12000,
cyapa_sort_tsg_pip_bl_resp_data, true);
if (error || resp_len != PIP_BL_INITIATE_RESP_LEN ||
resp_data[2] != PIP_BL_RESP_REPORT_ID ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data))
return error ? error : -EAGAIN;
return 0;
}
static bool cyapa_sort_pip_bl_exit_data(struct cyapa *cyapa, u8 *buf, int len)
{
if (buf == NULL || len < PIP_RESP_LENGTH_SIZE)
return false;
if (buf[0] == 0 && buf[1] == 0)
return true;
/* Exit bootloader failed for some reason. */
if (len == PIP_BL_FAIL_EXIT_RESP_LEN &&
buf[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_BL_RESP_REPORT_ID &&
buf[PIP_RESP_RSVD_OFFSET] == PIP_RESP_RSVD_KEY &&
buf[PIP_RESP_BL_SOP_OFFSET] == PIP_SOP_KEY &&
buf[10] == PIP_EOP_KEY)
return true;
return false;
}
int cyapa_pip_bl_exit(struct cyapa *cyapa)
{
u8 bl_gen5_bl_exit[] = { 0x04, 0x00,
0x0B, 0x00, 0x40, 0x00, 0x01, 0x3b, 0x00, 0x00,
0x20, 0xc7, 0x17
};
u8 resp_data[11];
int resp_len;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
bl_gen5_bl_exit, sizeof(bl_gen5_bl_exit),
resp_data, &resp_len,
5000, cyapa_sort_pip_bl_exit_data, false);
if (error)
return error;
if (resp_len == PIP_BL_FAIL_EXIT_RESP_LEN ||
resp_data[PIP_RESP_REPORT_ID_OFFSET] ==
PIP_BL_RESP_REPORT_ID)
return -EAGAIN;
if (resp_data[0] == 0x00 && resp_data[1] == 0x00)
return 0;
return -ENODEV;
}
int cyapa_pip_bl_enter(struct cyapa *cyapa)
{
u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2F, 0x00, 0x01 };
u8 resp_data[2];
int resp_len;
int error;
error = cyapa_poll_state(cyapa, 500);
if (error < 0)
return error;
/* Already in bootloader mode, Skipping exit. */
if (cyapa_is_pip_bl_mode(cyapa))
return 0;
else if (!cyapa_is_pip_app_mode(cyapa))
return -EINVAL;
/* Try to dump all buffered report data before any send command. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
/*
* Send bootloader enter command to trackpad device,
* after enter bootloader, the response data is two bytes of 0x00 0x00.
*/
resp_len = sizeof(resp_data);
memset(resp_data, 0, resp_len);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
5000, cyapa_sort_pip_application_launch_data,
true);
if (error || resp_data[0] != 0x00 || resp_data[1] != 0x00)
return error < 0 ? error : -EAGAIN;
cyapa->operational = false;
if (cyapa->gen == CYAPA_GEN5)
cyapa->state = CYAPA_STATE_GEN5_BL;
else if (cyapa->gen == CYAPA_GEN6)
cyapa->state = CYAPA_STATE_GEN6_BL;
return 0;
}
static int cyapa_pip_fw_head_check(struct cyapa *cyapa,
struct cyapa_tsg_bin_image_head *image_head)
{
if (image_head->head_size != 0x0C && image_head->head_size != 0x12)
return -EINVAL;
switch (cyapa->gen) {
case CYAPA_GEN6:
if (image_head->family_id != 0x9B ||
image_head->silicon_id_hi != 0x0B)
return -EINVAL;
break;
case CYAPA_GEN5:
/* Gen5 without proximity support. */
if (cyapa->platform_ver < 2) {
if (image_head->head_size == 0x0C)
break;
return -EINVAL;
}
if (image_head->family_id != 0x91 ||
image_head->silicon_id_hi != 0x02)
return -EINVAL;
break;
default:
return -EINVAL;
}
return 0;
}
int cyapa_pip_check_fw(struct cyapa *cyapa, const struct firmware *fw)
{
struct device *dev = &cyapa->client->dev;
struct cyapa_tsg_bin_image_data_record *image_records;
const struct cyapa_tsg_bin_image_data_record *app_integrity;
const struct tsg_bl_metadata_row_params *metadata;
int flash_records_count;
u32 fw_app_start, fw_upgrade_start;
u16 fw_app_len, fw_upgrade_len;
u16 app_crc;
u16 app_integrity_crc;
int i;
/* Verify the firmware image not miss-used for Gen5 and Gen6. */
if (cyapa_pip_fw_head_check(cyapa,
(struct cyapa_tsg_bin_image_head *)fw->data)) {
dev_err(dev, "%s: firmware image not match TP device.\n",
__func__);
return -EINVAL;
}
image_records =
cyapa_get_image_record_data_num(fw, &flash_records_count);
/*
* APP_INTEGRITY row is always the last row block,
* and the row id must be 0x01ff.
*/
app_integrity = &image_records[flash_records_count - 1];
if (app_integrity->flash_array_id != 0x00 ||
get_unaligned_be16(&app_integrity->row_number) != 0x01ff) {
dev_err(dev, "%s: invalid app_integrity data.\n", __func__);
return -EINVAL;
}
metadata = (const void *)app_integrity->record_data;
/* Verify app_integrity crc */
app_integrity_crc = crc_itu_t(0xffff, app_integrity->record_data,
CYAPA_TSG_APP_INTEGRITY_SIZE);
if (app_integrity_crc != get_unaligned_le16(&metadata->metadata_crc)) {
dev_err(dev, "%s: invalid app_integrity crc.\n", __func__);
return -EINVAL;
}
fw_app_start = get_unaligned_le32(&metadata->app_start);
fw_app_len = get_unaligned_le16(&metadata->app_len);
fw_upgrade_start = get_unaligned_le32(&metadata->upgrade_start);
fw_upgrade_len = get_unaligned_le16(&metadata->upgrade_len);
if (fw_app_start % CYAPA_TSG_FW_ROW_SIZE ||
fw_app_len % CYAPA_TSG_FW_ROW_SIZE ||
fw_upgrade_start % CYAPA_TSG_FW_ROW_SIZE ||
fw_upgrade_len % CYAPA_TSG_FW_ROW_SIZE) {
dev_err(dev, "%s: invalid image alignment.\n", __func__);
return -EINVAL;
}
/* Verify application image CRC. */
app_crc = 0xffffU;
for (i = 0; i < fw_app_len / CYAPA_TSG_FW_ROW_SIZE; i++) {
const u8 *data = image_records[i].record_data;
app_crc = crc_itu_t(app_crc, data, CYAPA_TSG_FW_ROW_SIZE);
}
if (app_crc != get_unaligned_le16(&metadata->app_crc)) {
dev_err(dev, "%s: invalid firmware app crc check.\n", __func__);
return -EINVAL;
}
return 0;
}
static int cyapa_pip_write_fw_block(struct cyapa *cyapa,
struct cyapa_tsg_bin_image_data_record *flash_record)
{
struct pip_bl_cmd_head *bl_cmd_head;
struct pip_bl_packet_start *bl_packet_start;
struct tsg_bl_flash_row_head *flash_row_head;
struct pip_bl_packet_end *bl_packet_end;
u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
u16 cmd_len;
u8 flash_array_id;
u16 flash_row_id;
u16 record_len;
u8 *record_data;
u16 data_len;
u16 crc;
u8 resp_data[11];
int resp_len;
int error;
flash_array_id = flash_record->flash_array_id;
flash_row_id = get_unaligned_be16(&flash_record->row_number);
record_len = get_unaligned_be16(&flash_record->record_len);
record_data = flash_record->record_data;
memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
bl_cmd_head = (struct pip_bl_cmd_head *)cmd;
bl_packet_start = &bl_cmd_head->packet_start;
cmd_len = sizeof(struct pip_bl_cmd_head) +
sizeof(struct tsg_bl_flash_row_head) +
CYAPA_TSG_FLASH_MAP_BLOCK_SIZE +
sizeof(struct pip_bl_packet_end);
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &bl_cmd_head->addr);
/* Don't include 2 bytes register address */
put_unaligned_le16(cmd_len - 2, &bl_cmd_head->length);
bl_cmd_head->report_id = PIP_BL_CMD_REPORT_ID;
bl_packet_start->sop = PIP_SOP_KEY;
bl_packet_start->cmd_code = PIP_BL_CMD_PROGRAM_VERIFY_ROW;
/* 1 (Flash Array ID) + 2 (Flash Row ID) + 128 (flash data) */
data_len = sizeof(struct tsg_bl_flash_row_head) + record_len;
put_unaligned_le16(data_len, &bl_packet_start->data_length);
flash_row_head = (struct tsg_bl_flash_row_head *)bl_cmd_head->data;
flash_row_head->flash_array_id = flash_array_id;
put_unaligned_le16(flash_row_id, &flash_row_head->flash_row_id);
memcpy(flash_row_head->flash_data, record_data, record_len);
bl_packet_end = (struct pip_bl_packet_end *)(bl_cmd_head->data +
data_len);
crc = crc_itu_t(0xffff, (u8 *)bl_packet_start,
sizeof(struct pip_bl_packet_start) + data_len);
put_unaligned_le16(crc, &bl_packet_end->crc);
bl_packet_end->eop = PIP_EOP_KEY;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_bl_resp_data, true);
if (error || resp_len != PIP_BL_BLOCK_WRITE_RESP_LEN ||
resp_data[2] != PIP_BL_RESP_REPORT_ID ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data))
return error < 0 ? error : -EAGAIN;
return 0;
}
int cyapa_pip_do_fw_update(struct cyapa *cyapa,
const struct firmware *fw)
{
struct device *dev = &cyapa->client->dev;
struct cyapa_tsg_bin_image_data_record *image_records;
int flash_records_count;
int i;
int error;
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
image_records =
cyapa_get_image_record_data_num(fw, &flash_records_count);
/*
* The last flash row 0x01ff has been written through bl_initiate
* command, so DO NOT write flash 0x01ff to trackpad device.
*/
for (i = 0; i < (flash_records_count - 1); i++) {
error = cyapa_pip_write_fw_block(cyapa, &image_records[i]);
if (error) {
dev_err(dev, "%s: Gen5 FW update aborted: %d\n",
__func__, error);
return error;
}
}
return 0;
}
static int cyapa_gen5_change_power_state(struct cyapa *cyapa, u8 power_state)
{
u8 cmd[8] = { 0x04, 0x00, 0x06, 0x00, 0x2f, 0x00, 0x08, 0x01 };
u8 resp_data[6];
int resp_len;
int error;
cmd[7] = power_state;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error || !VALID_CMD_RESP_HEADER(resp_data, 0x08) ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data))
return error < 0 ? error : -EINVAL;
return 0;
}
static int cyapa_gen5_set_interval_time(struct cyapa *cyapa,
u8 parameter_id, u16 interval_time)
{
struct pip_app_cmd_head *app_cmd_head;
struct gen5_app_set_parameter_data *parameter_data;
u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
int cmd_len;
u8 resp_data[7];
int resp_len;
u8 parameter_size;
int error;
memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
app_cmd_head = (struct pip_app_cmd_head *)cmd;
parameter_data = (struct gen5_app_set_parameter_data *)
app_cmd_head->parameter_data;
cmd_len = sizeof(struct pip_app_cmd_head) +
sizeof(struct gen5_app_set_parameter_data);
switch (parameter_id) {
case GEN5_PARAMETER_ACT_INTERVL_ID:
parameter_size = GEN5_PARAMETER_ACT_INTERVL_SIZE;
break;
case GEN5_PARAMETER_ACT_LFT_INTERVL_ID:
parameter_size = GEN5_PARAMETER_ACT_LFT_INTERVL_SIZE;
break;
case GEN5_PARAMETER_LP_INTRVL_ID:
parameter_size = GEN5_PARAMETER_LP_INTRVL_SIZE;
break;
default:
return -EINVAL;
}
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
/*
* Don't include unused parameter value bytes and
* 2 bytes register address.
*/
put_unaligned_le16(cmd_len - (4 - parameter_size) - 2,
&app_cmd_head->length);
app_cmd_head->report_id = PIP_APP_CMD_REPORT_ID;
app_cmd_head->cmd_code = GEN5_CMD_SET_PARAMETER;
parameter_data->parameter_id = parameter_id;
parameter_data->parameter_size = parameter_size;
put_unaligned_le32((u32)interval_time, ¶meter_data->value);
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error || resp_data[5] != parameter_id ||
resp_data[6] != parameter_size ||
!VALID_CMD_RESP_HEADER(resp_data, GEN5_CMD_SET_PARAMETER))
return error < 0 ? error : -EINVAL;
return 0;
}
static int cyapa_gen5_get_interval_time(struct cyapa *cyapa,
u8 parameter_id, u16 *interval_time)
{
struct pip_app_cmd_head *app_cmd_head;
struct gen5_app_get_parameter_data *parameter_data;
u8 cmd[CYAPA_TSG_MAX_CMD_SIZE];
int cmd_len;
u8 resp_data[11];
int resp_len;
u8 parameter_size;
u16 mask, i;
int error;
memset(cmd, 0, CYAPA_TSG_MAX_CMD_SIZE);
app_cmd_head = (struct pip_app_cmd_head *)cmd;
parameter_data = (struct gen5_app_get_parameter_data *)
app_cmd_head->parameter_data;
cmd_len = sizeof(struct pip_app_cmd_head) +
sizeof(struct gen5_app_get_parameter_data);
*interval_time = 0;
switch (parameter_id) {
case GEN5_PARAMETER_ACT_INTERVL_ID:
parameter_size = GEN5_PARAMETER_ACT_INTERVL_SIZE;
break;
case GEN5_PARAMETER_ACT_LFT_INTERVL_ID:
parameter_size = GEN5_PARAMETER_ACT_LFT_INTERVL_SIZE;
break;
case GEN5_PARAMETER_LP_INTRVL_ID:
parameter_size = GEN5_PARAMETER_LP_INTRVL_SIZE;
break;
default:
return -EINVAL;
}
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
/* Don't include 2 bytes register address */
put_unaligned_le16(cmd_len - 2, &app_cmd_head->length);
app_cmd_head->report_id = PIP_APP_CMD_REPORT_ID;
app_cmd_head->cmd_code = GEN5_CMD_GET_PARAMETER;
parameter_data->parameter_id = parameter_id;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, cmd_len,
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error || resp_data[5] != parameter_id || resp_data[6] == 0 ||
!VALID_CMD_RESP_HEADER(resp_data, GEN5_CMD_GET_PARAMETER))
return error < 0 ? error : -EINVAL;
mask = 0;
for (i = 0; i < parameter_size; i++)
mask |= (0xff << (i * 8));
*interval_time = get_unaligned_le16(&resp_data[7]) & mask;
return 0;
}
static int cyapa_gen5_disable_pip_report(struct cyapa *cyapa)
{
struct pip_app_cmd_head *app_cmd_head;
u8 cmd[10];
u8 resp_data[7];
int resp_len;
int error;
memset(cmd, 0, sizeof(cmd));
app_cmd_head = (struct pip_app_cmd_head *)cmd;
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
app_cmd_head->report_id = PIP_APP_CMD_REPORT_ID;
app_cmd_head->cmd_code = GEN5_CMD_SET_PARAMETER;
app_cmd_head->parameter_data[0] = GEN5_PARAMETER_DISABLE_PIP_REPORT;
app_cmd_head->parameter_data[1] = 0x01;
app_cmd_head->parameter_data[2] = 0x01;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error || resp_data[5] != GEN5_PARAMETER_DISABLE_PIP_REPORT ||
!VALID_CMD_RESP_HEADER(resp_data, GEN5_CMD_SET_PARAMETER) ||
resp_data[6] != 0x01)
return error < 0 ? error : -EINVAL;
return 0;
}
int cyapa_pip_set_proximity(struct cyapa *cyapa, bool enable)
{
u8 cmd[] = { 0x04, 0x00, 0x06, 0x00, 0x2f, 0x00, PIP_SET_PROXIMITY,
(u8)!!enable
};
u8 resp_data[6];
int resp_len;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error || !VALID_CMD_RESP_HEADER(resp_data, PIP_SET_PROXIMITY) ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data)) {
error = (error == -ETIMEDOUT) ? -EOPNOTSUPP : error;
return error < 0 ? error : -EINVAL;
}
return 0;
}
int cyapa_pip_deep_sleep(struct cyapa *cyapa, u8 state)
{
u8 cmd[] = { 0x05, 0x00, 0x00, 0x08};
u8 resp_data[5];
int resp_len;
int error;
cmd[2] = state & PIP_DEEP_SLEEP_STATE_MASK;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_pip_deep_sleep_data, false);
if (error || ((resp_data[3] & PIP_DEEP_SLEEP_STATE_MASK) != state))
return -EINVAL;
return 0;
}
static int cyapa_gen5_set_power_mode(struct cyapa *cyapa,
u8 power_mode, u16 sleep_time, enum cyapa_pm_stage pm_stage)
{
struct device *dev = &cyapa->client->dev;
u8 power_state;
int error = 0;
if (cyapa->state != CYAPA_STATE_GEN5_APP)
return 0;
cyapa_set_pip_pm_state(cyapa, pm_stage);
if (PIP_DEV_GET_PWR_STATE(cyapa) == UNINIT_PWR_MODE) {
/*
* Assume TP in deep sleep mode when driver is loaded,
* avoid driver unload and reload command IO issue caused by TP
* has been set into deep sleep mode when unloading.
*/
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_OFF);
}
if (PIP_DEV_UNINIT_SLEEP_TIME(cyapa) &&
PIP_DEV_GET_PWR_STATE(cyapa) != PWR_MODE_OFF)
if (cyapa_gen5_get_interval_time(cyapa,
GEN5_PARAMETER_LP_INTRVL_ID,
&cyapa->dev_sleep_time) != 0)
PIP_DEV_SET_SLEEP_TIME(cyapa, UNINIT_SLEEP_TIME);
if (PIP_DEV_GET_PWR_STATE(cyapa) == power_mode) {
if (power_mode == PWR_MODE_OFF ||
power_mode == PWR_MODE_FULL_ACTIVE ||
power_mode == PWR_MODE_BTN_ONLY ||
PIP_DEV_GET_SLEEP_TIME(cyapa) == sleep_time) {
/* Has in correct power mode state, early return. */
goto out;
}
}
if (power_mode == PWR_MODE_OFF) {
error = cyapa_pip_deep_sleep(cyapa, PIP_DEEP_SLEEP_STATE_OFF);
if (error) {
dev_err(dev, "enter deep sleep fail: %d\n", error);
goto out;
}
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_OFF);
goto out;
}
/*
* When trackpad in power off mode, it cannot change to other power
* state directly, must be wake up from sleep firstly, then
* continue to do next power sate change.
*/
if (PIP_DEV_GET_PWR_STATE(cyapa) == PWR_MODE_OFF) {
error = cyapa_pip_deep_sleep(cyapa, PIP_DEEP_SLEEP_STATE_ON);
if (error) {
dev_err(dev, "deep sleep wake fail: %d\n", error);
goto out;
}
}
if (power_mode == PWR_MODE_FULL_ACTIVE) {
error = cyapa_gen5_change_power_state(cyapa,
GEN5_POWER_STATE_ACTIVE);
if (error) {
dev_err(dev, "change to active fail: %d\n", error);
goto out;
}
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_FULL_ACTIVE);
} else if (power_mode == PWR_MODE_BTN_ONLY) {
error = cyapa_gen5_change_power_state(cyapa,
GEN5_POWER_STATE_BTN_ONLY);
if (error) {
dev_err(dev, "fail to button only mode: %d\n", error);
goto out;
}
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_BTN_ONLY);
} else {
/*
* Continue to change power mode even failed to set
* interval time, it won't affect the power mode change.
* except the sleep interval time is not correct.
*/
if (PIP_DEV_UNINIT_SLEEP_TIME(cyapa) ||
sleep_time != PIP_DEV_GET_SLEEP_TIME(cyapa))
if (cyapa_gen5_set_interval_time(cyapa,
GEN5_PARAMETER_LP_INTRVL_ID,
sleep_time) == 0)
PIP_DEV_SET_SLEEP_TIME(cyapa, sleep_time);
if (sleep_time <= GEN5_POWER_READY_MAX_INTRVL_TIME)
power_state = GEN5_POWER_STATE_READY;
else
power_state = GEN5_POWER_STATE_IDLE;
error = cyapa_gen5_change_power_state(cyapa, power_state);
if (error) {
dev_err(dev, "set power state to 0x%02x failed: %d\n",
power_state, error);
goto out;
}
/*
* Disable pip report for a little time, firmware will
* re-enable it automatically. It's used to fix the issue
* that trackpad unable to report signal to wake system up
* in the special situation that system is in suspending, and
* at the same time, user touch trackpad to wake system up.
* This function can avoid the data to be buffered when system
* is suspending which may cause interrupt line unable to be
* asserted again.
*/
if (pm_stage == CYAPA_PM_SUSPEND)
cyapa_gen5_disable_pip_report(cyapa);
PIP_DEV_SET_PWR_STATE(cyapa,
cyapa_sleep_time_to_pwr_cmd(sleep_time));
}
out:
cyapa_reset_pip_pm_state(cyapa);
return error;
}
int cyapa_pip_resume_scanning(struct cyapa *cyapa)
{
u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, 0x04 };
u8 resp_data[6];
int resp_len;
int error;
/* Try to dump all buffered data before doing command. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, true);
if (error || !VALID_CMD_RESP_HEADER(resp_data, 0x04))
return -EINVAL;
/* Try to dump all buffered data when resuming scanning. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
return 0;
}
int cyapa_pip_suspend_scanning(struct cyapa *cyapa)
{
u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, 0x03 };
u8 resp_data[6];
int resp_len;
int error;
/* Try to dump all buffered data before doing command. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, true);
if (error || !VALID_CMD_RESP_HEADER(resp_data, 0x03))
return -EINVAL;
/* Try to dump all buffered data when suspending scanning. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
return 0;
}
static int cyapa_pip_calibrate_pwcs(struct cyapa *cyapa,
u8 calibrate_sensing_mode_type)
{
struct pip_app_cmd_head *app_cmd_head;
u8 cmd[8];
u8 resp_data[6];
int resp_len;
int error;
/* Try to dump all buffered data before doing command. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
memset(cmd, 0, sizeof(cmd));
app_cmd_head = (struct pip_app_cmd_head *)cmd;
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
app_cmd_head->report_id = PIP_APP_CMD_REPORT_ID;
app_cmd_head->cmd_code = PIP_CMD_CALIBRATE;
app_cmd_head->parameter_data[0] = calibrate_sensing_mode_type;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
5000, cyapa_sort_tsg_pip_app_resp_data, true);
if (error || !VALID_CMD_RESP_HEADER(resp_data, PIP_CMD_CALIBRATE) ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data))
return error < 0 ? error : -EAGAIN;
return 0;
}
ssize_t cyapa_pip_do_calibrate(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
int error, calibrate_error;
/* 1. Suspend Scanning*/
error = cyapa_pip_suspend_scanning(cyapa);
if (error)
return error;
/* 2. Do mutual capacitance fine calibrate. */
calibrate_error = cyapa_pip_calibrate_pwcs(cyapa,
PIP_SENSING_MODE_MUTUAL_CAP_FINE);
if (calibrate_error)
goto resume_scanning;
/* 3. Do self capacitance calibrate. */
calibrate_error = cyapa_pip_calibrate_pwcs(cyapa,
PIP_SENSING_MODE_SELF_CAP);
if (calibrate_error)
goto resume_scanning;
resume_scanning:
/* 4. Resume Scanning*/
error = cyapa_pip_resume_scanning(cyapa);
if (error || calibrate_error)
return error ? error : calibrate_error;
return count;
}
static s32 twos_complement_to_s32(s32 value, int num_bits)
{
if (value >> (num_bits - 1))
value |= -1 << num_bits;
return value;
}
static s32 cyapa_parse_structure_data(u8 data_format, u8 *buf, int buf_len)
{
int data_size;
bool big_endian;
bool unsigned_type;
s32 value;
data_size = (data_format & 0x07);
big_endian = ((data_format & 0x10) == 0x00);
unsigned_type = ((data_format & 0x20) == 0x00);
if (buf_len < data_size)
return 0;
switch (data_size) {
case 1:
value = buf[0];
break;
case 2:
if (big_endian)
value = get_unaligned_be16(buf);
else
value = get_unaligned_le16(buf);
break;
case 4:
if (big_endian)
value = get_unaligned_be32(buf);
else
value = get_unaligned_le32(buf);
break;
default:
/* Should not happen, just as default case here. */
value = 0;
break;
}
if (!unsigned_type)
value = twos_complement_to_s32(value, data_size * 8);
return value;
}
static void cyapa_gen5_guess_electrodes(struct cyapa *cyapa,
int *electrodes_rx, int *electrodes_tx)
{
if (cyapa->electrodes_rx != 0) {
*electrodes_rx = cyapa->electrodes_rx;
*electrodes_tx = (cyapa->electrodes_x == *electrodes_rx) ?
cyapa->electrodes_y : cyapa->electrodes_x;
} else {
*electrodes_tx = min(cyapa->electrodes_x, cyapa->electrodes_y);
*electrodes_rx = max(cyapa->electrodes_x, cyapa->electrodes_y);
}
}
/*
* Read all the global mutual or self idac data or mutual or self local PWC
* data based on the @idac_data_type.
* If the input value of @data_size is 0, then means read global mutual or
* self idac data. For read global mutual idac data, @idac_max, @idac_min and
* @idac_ave are in order used to return the max value of global mutual idac
* data, the min value of global mutual idac and the average value of the
* global mutual idac data. For read global self idac data, @idac_max is used
* to return the global self cap idac data in Rx direction, @idac_min is used
* to return the global self cap idac data in Tx direction. @idac_ave is not
* used.
* If the input value of @data_size is not 0, than means read the mutual or
* self local PWC data. The @idac_max, @idac_min and @idac_ave are used to
* return the max, min and average value of the mutual or self local PWC data.
* Note, in order to read mutual local PWC data, must read invoke this function
* to read the mutual global idac data firstly to set the correct Rx number
* value, otherwise, the read mutual idac and PWC data may not correct.
*/
static int cyapa_gen5_read_idac_data(struct cyapa *cyapa,
u8 cmd_code, u8 idac_data_type, int *data_size,
int *idac_max, int *idac_min, int *idac_ave)
{
struct pip_app_cmd_head *cmd_head;
u8 cmd[12];
u8 resp_data[256];
int resp_len;
int read_len;
int value;
u16 offset;
int read_elements;
bool read_global_idac;
int sum, count, max_element_cnt;
int tmp_max, tmp_min, tmp_ave, tmp_sum, tmp_count;
int electrodes_rx, electrodes_tx;
int i;
int error;
if (cmd_code != PIP_RETRIEVE_DATA_STRUCTURE ||
(idac_data_type != GEN5_RETRIEVE_MUTUAL_PWC_DATA &&
idac_data_type != GEN5_RETRIEVE_SELF_CAP_PWC_DATA) ||
!data_size || !idac_max || !idac_min || !idac_ave)
return -EINVAL;
*idac_max = INT_MIN;
*idac_min = INT_MAX;
sum = count = tmp_count = 0;
electrodes_rx = electrodes_tx = 0;
if (*data_size == 0) {
/*
* Read global idac values firstly.
* Currently, no idac data exceed 4 bytes.
*/
read_global_idac = true;
offset = 0;
*data_size = 4;
tmp_max = INT_MIN;
tmp_min = INT_MAX;
tmp_ave = tmp_sum = tmp_count = 0;
if (idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA) {
if (cyapa->aligned_electrodes_rx == 0) {
cyapa_gen5_guess_electrodes(cyapa,
&electrodes_rx, &electrodes_tx);
cyapa->aligned_electrodes_rx =
(electrodes_rx + 3) & ~3u;
}
max_element_cnt =
(cyapa->aligned_electrodes_rx + 7) & ~7u;
} else {
max_element_cnt = 2;
}
} else {
read_global_idac = false;
if (*data_size > 4)
*data_size = 4;
/* Calculate the start offset in bytes of local PWC data. */
if (idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA) {
offset = cyapa->aligned_electrodes_rx * (*data_size);
if (cyapa->electrodes_rx == cyapa->electrodes_x)
electrodes_tx = cyapa->electrodes_y;
else
electrodes_tx = cyapa->electrodes_x;
max_element_cnt = ((cyapa->aligned_electrodes_rx + 7) &
~7u) * electrodes_tx;
} else {
offset = 2;
max_element_cnt = cyapa->electrodes_x +
cyapa->electrodes_y;
max_element_cnt = (max_element_cnt + 3) & ~3u;
}
}
memset(cmd, 0, sizeof(cmd));
cmd_head = (struct pip_app_cmd_head *)cmd;
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &cmd_head->addr);
put_unaligned_le16(sizeof(cmd) - 2, &cmd_head->length);
cmd_head->report_id = PIP_APP_CMD_REPORT_ID;
cmd_head->cmd_code = cmd_code;
do {
read_elements = (256 - GEN5_RESP_DATA_STRUCTURE_OFFSET) /
(*data_size);
read_elements = min(read_elements, max_element_cnt - count);
read_len = read_elements * (*data_size);
put_unaligned_le16(offset, &cmd_head->parameter_data[0]);
put_unaligned_le16(read_len, &cmd_head->parameter_data[2]);
cmd_head->parameter_data[4] = idac_data_type;
resp_len = GEN5_RESP_DATA_STRUCTURE_OFFSET + read_len;
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data,
true);
if (error || resp_len < GEN5_RESP_DATA_STRUCTURE_OFFSET ||
!VALID_CMD_RESP_HEADER(resp_data, cmd_code) ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data) ||
resp_data[6] != idac_data_type)
return (error < 0) ? error : -EAGAIN;
read_len = get_unaligned_le16(&resp_data[7]);
if (read_len == 0)
break;
*data_size = (resp_data[9] & GEN5_PWC_DATA_ELEMENT_SIZE_MASK);
if (read_len < *data_size)
return -EINVAL;
if (read_global_idac &&
idac_data_type == GEN5_RETRIEVE_SELF_CAP_PWC_DATA) {
/* Rx's self global idac data. */
*idac_max = cyapa_parse_structure_data(
resp_data[9],
&resp_data[GEN5_RESP_DATA_STRUCTURE_OFFSET],
*data_size);
/* Tx's self global idac data. */
*idac_min = cyapa_parse_structure_data(
resp_data[9],
&resp_data[GEN5_RESP_DATA_STRUCTURE_OFFSET +
*data_size],
*data_size);
break;
}
/* Read mutual global idac or local mutual/self PWC data. */
offset += read_len;
for (i = 10; i < (read_len + GEN5_RESP_DATA_STRUCTURE_OFFSET);
i += *data_size) {
value = cyapa_parse_structure_data(resp_data[9],
&resp_data[i], *data_size);
*idac_min = min(value, *idac_min);
*idac_max = max(value, *idac_max);
if (idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA &&
tmp_count < cyapa->aligned_electrodes_rx &&
read_global_idac) {
/*
* The value gap between global and local mutual
* idac data must bigger than 50%.
* Normally, global value bigger than 50,
* local values less than 10.
*/
if (!tmp_ave || value > tmp_ave / 2) {
tmp_min = min(value, tmp_min);
tmp_max = max(value, tmp_max);
tmp_sum += value;
tmp_count++;
tmp_ave = tmp_sum / tmp_count;
}
}
sum += value;
count++;
if (count >= max_element_cnt)
goto out;
}
} while (true);
out:
*idac_ave = count ? (sum / count) : 0;
if (read_global_idac &&
idac_data_type == GEN5_RETRIEVE_MUTUAL_PWC_DATA) {
if (tmp_count == 0)
return 0;
if (tmp_count == cyapa->aligned_electrodes_rx) {
cyapa->electrodes_rx = cyapa->electrodes_rx ?
cyapa->electrodes_rx : electrodes_rx;
} else if (tmp_count == electrodes_rx) {
cyapa->electrodes_rx = cyapa->electrodes_rx ?
cyapa->electrodes_rx : electrodes_rx;
cyapa->aligned_electrodes_rx = electrodes_rx;
} else {
cyapa->electrodes_rx = cyapa->electrodes_rx ?
cyapa->electrodes_rx : electrodes_tx;
cyapa->aligned_electrodes_rx = tmp_count;
}
*idac_min = tmp_min;
*idac_max = tmp_max;
*idac_ave = tmp_ave;
}
return 0;
}
static int cyapa_gen5_read_mutual_idac_data(struct cyapa *cyapa,
int *gidac_mutual_max, int *gidac_mutual_min, int *gidac_mutual_ave,
int *lidac_mutual_max, int *lidac_mutual_min, int *lidac_mutual_ave)
{
int data_size;
int error;
*gidac_mutual_max = *gidac_mutual_min = *gidac_mutual_ave = 0;
*lidac_mutual_max = *lidac_mutual_min = *lidac_mutual_ave = 0;
data_size = 0;
error = cyapa_gen5_read_idac_data(cyapa,
PIP_RETRIEVE_DATA_STRUCTURE,
GEN5_RETRIEVE_MUTUAL_PWC_DATA,
&data_size,
gidac_mutual_max, gidac_mutual_min, gidac_mutual_ave);
if (error)
return error;
error = cyapa_gen5_read_idac_data(cyapa,
PIP_RETRIEVE_DATA_STRUCTURE,
GEN5_RETRIEVE_MUTUAL_PWC_DATA,
&data_size,
lidac_mutual_max, lidac_mutual_min, lidac_mutual_ave);
return error;
}
static int cyapa_gen5_read_self_idac_data(struct cyapa *cyapa,
int *gidac_self_rx, int *gidac_self_tx,
int *lidac_self_max, int *lidac_self_min, int *lidac_self_ave)
{
int data_size;
int error;
*gidac_self_rx = *gidac_self_tx = 0;
*lidac_self_max = *lidac_self_min = *lidac_self_ave = 0;
data_size = 0;
error = cyapa_gen5_read_idac_data(cyapa,
PIP_RETRIEVE_DATA_STRUCTURE,
GEN5_RETRIEVE_SELF_CAP_PWC_DATA,
&data_size,
lidac_self_max, lidac_self_min, lidac_self_ave);
if (error)
return error;
*gidac_self_rx = *lidac_self_max;
*gidac_self_tx = *lidac_self_min;
error = cyapa_gen5_read_idac_data(cyapa,
PIP_RETRIEVE_DATA_STRUCTURE,
GEN5_RETRIEVE_SELF_CAP_PWC_DATA,
&data_size,
lidac_self_max, lidac_self_min, lidac_self_ave);
return error;
}
static ssize_t cyapa_gen5_execute_panel_scan(struct cyapa *cyapa)
{
struct pip_app_cmd_head *app_cmd_head;
u8 cmd[7];
u8 resp_data[6];
int resp_len;
int error;
memset(cmd, 0, sizeof(cmd));
app_cmd_head = (struct pip_app_cmd_head *)cmd;
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
app_cmd_head->report_id = PIP_APP_CMD_REPORT_ID;
app_cmd_head->cmd_code = GEN5_CMD_EXECUTE_PANEL_SCAN;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, true);
if (error || resp_len != sizeof(resp_data) ||
!VALID_CMD_RESP_HEADER(resp_data,
GEN5_CMD_EXECUTE_PANEL_SCAN) ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data))
return error ? error : -EAGAIN;
return 0;
}
static int cyapa_gen5_read_panel_scan_raw_data(struct cyapa *cyapa,
u8 cmd_code, u8 raw_data_type, int raw_data_max_num,
int *raw_data_max, int *raw_data_min, int *raw_data_ave,
u8 *buffer)
{
struct pip_app_cmd_head *app_cmd_head;
struct gen5_retrieve_panel_scan_data *panel_sacn_data;
u8 cmd[12];
u8 resp_data[256]; /* Max bytes can transfer one time. */
int resp_len;
int read_elements;
int read_len;
u16 offset;
s32 value;
int sum, count;
int data_size;
s32 *intp;
int i;
int error;
if (cmd_code != GEN5_CMD_RETRIEVE_PANEL_SCAN ||
(raw_data_type > GEN5_PANEL_SCAN_SELF_DIFFCOUNT) ||
!raw_data_max || !raw_data_min || !raw_data_ave)
return -EINVAL;
intp = (s32 *)buffer;
*raw_data_max = INT_MIN;
*raw_data_min = INT_MAX;
sum = count = 0;
offset = 0;
/* Assume max element size is 4 currently. */
read_elements = (256 - GEN5_RESP_DATA_STRUCTURE_OFFSET) / 4;
read_len = read_elements * 4;
app_cmd_head = (struct pip_app_cmd_head *)cmd;
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &app_cmd_head->addr);
put_unaligned_le16(sizeof(cmd) - 2, &app_cmd_head->length);
app_cmd_head->report_id = PIP_APP_CMD_REPORT_ID;
app_cmd_head->cmd_code = cmd_code;
panel_sacn_data = (struct gen5_retrieve_panel_scan_data *)
app_cmd_head->parameter_data;
do {
put_unaligned_le16(offset, &panel_sacn_data->read_offset);
put_unaligned_le16(read_elements,
&panel_sacn_data->read_elements);
panel_sacn_data->data_id = raw_data_type;
resp_len = GEN5_RESP_DATA_STRUCTURE_OFFSET + read_len;
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, true);
if (error || resp_len < GEN5_RESP_DATA_STRUCTURE_OFFSET ||
!VALID_CMD_RESP_HEADER(resp_data, cmd_code) ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data) ||
resp_data[6] != raw_data_type)
return error ? error : -EAGAIN;
read_elements = get_unaligned_le16(&resp_data[7]);
if (read_elements == 0)
break;
data_size = (resp_data[9] & GEN5_PWC_DATA_ELEMENT_SIZE_MASK);
offset += read_elements;
if (read_elements) {
for (i = GEN5_RESP_DATA_STRUCTURE_OFFSET;
i < (read_elements * data_size +
GEN5_RESP_DATA_STRUCTURE_OFFSET);
i += data_size) {
value = cyapa_parse_structure_data(resp_data[9],
&resp_data[i], data_size);
*raw_data_min = min(value, *raw_data_min);
*raw_data_max = max(value, *raw_data_max);
if (intp)
put_unaligned_le32(value, &intp[count]);
sum += value;
count++;
}
}
if (count >= raw_data_max_num)
break;
read_elements = (sizeof(resp_data) -
GEN5_RESP_DATA_STRUCTURE_OFFSET) / data_size;
read_len = read_elements * data_size;
} while (true);
*raw_data_ave = count ? (sum / count) : 0;
return 0;
}
static ssize_t cyapa_gen5_show_baseline(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
int gidac_mutual_max, gidac_mutual_min, gidac_mutual_ave;
int lidac_mutual_max, lidac_mutual_min, lidac_mutual_ave;
int gidac_self_rx, gidac_self_tx;
int lidac_self_max, lidac_self_min, lidac_self_ave;
int raw_cap_mutual_max, raw_cap_mutual_min, raw_cap_mutual_ave;
int raw_cap_self_max, raw_cap_self_min, raw_cap_self_ave;
int mutual_diffdata_max, mutual_diffdata_min, mutual_diffdata_ave;
int self_diffdata_max, self_diffdata_min, self_diffdata_ave;
int mutual_baseline_max, mutual_baseline_min, mutual_baseline_ave;
int self_baseline_max, self_baseline_min, self_baseline_ave;
int error, resume_error;
int size;
if (!cyapa_is_pip_app_mode(cyapa))
return -EBUSY;
/* 1. Suspend Scanning*/
error = cyapa_pip_suspend_scanning(cyapa);
if (error)
return error;
/* 2. Read global and local mutual IDAC data. */
gidac_self_rx = gidac_self_tx = 0;
error = cyapa_gen5_read_mutual_idac_data(cyapa,
&gidac_mutual_max, &gidac_mutual_min,
&gidac_mutual_ave, &lidac_mutual_max,
&lidac_mutual_min, &lidac_mutual_ave);
if (error)
goto resume_scanning;
/* 3. Read global and local self IDAC data. */
error = cyapa_gen5_read_self_idac_data(cyapa,
&gidac_self_rx, &gidac_self_tx,
&lidac_self_max, &lidac_self_min,
&lidac_self_ave);
if (error)
goto resume_scanning;
/* 4. Execute panel scan. It must be executed before read data. */
error = cyapa_gen5_execute_panel_scan(cyapa);
if (error)
goto resume_scanning;
/* 5. Retrieve panel scan, mutual cap raw data. */
error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
GEN5_CMD_RETRIEVE_PANEL_SCAN,
GEN5_PANEL_SCAN_MUTUAL_RAW_DATA,
cyapa->electrodes_x * cyapa->electrodes_y,
&raw_cap_mutual_max, &raw_cap_mutual_min,
&raw_cap_mutual_ave,
NULL);
if (error)
goto resume_scanning;
/* 6. Retrieve panel scan, self cap raw data. */
error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
GEN5_CMD_RETRIEVE_PANEL_SCAN,
GEN5_PANEL_SCAN_SELF_RAW_DATA,
cyapa->electrodes_x + cyapa->electrodes_y,
&raw_cap_self_max, &raw_cap_self_min,
&raw_cap_self_ave,
NULL);
if (error)
goto resume_scanning;
/* 7. Retrieve panel scan, mutual cap diffcount raw data. */
error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
GEN5_CMD_RETRIEVE_PANEL_SCAN,
GEN5_PANEL_SCAN_MUTUAL_DIFFCOUNT,
cyapa->electrodes_x * cyapa->electrodes_y,
&mutual_diffdata_max, &mutual_diffdata_min,
&mutual_diffdata_ave,
NULL);
if (error)
goto resume_scanning;
/* 8. Retrieve panel scan, self cap diffcount raw data. */
error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
GEN5_CMD_RETRIEVE_PANEL_SCAN,
GEN5_PANEL_SCAN_SELF_DIFFCOUNT,
cyapa->electrodes_x + cyapa->electrodes_y,
&self_diffdata_max, &self_diffdata_min,
&self_diffdata_ave,
NULL);
if (error)
goto resume_scanning;
/* 9. Retrieve panel scan, mutual cap baseline raw data. */
error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
GEN5_CMD_RETRIEVE_PANEL_SCAN,
GEN5_PANEL_SCAN_MUTUAL_BASELINE,
cyapa->electrodes_x * cyapa->electrodes_y,
&mutual_baseline_max, &mutual_baseline_min,
&mutual_baseline_ave,
NULL);
if (error)
goto resume_scanning;
/* 10. Retrieve panel scan, self cap baseline raw data. */
error = cyapa_gen5_read_panel_scan_raw_data(cyapa,
GEN5_CMD_RETRIEVE_PANEL_SCAN,
GEN5_PANEL_SCAN_SELF_BASELINE,
cyapa->electrodes_x + cyapa->electrodes_y,
&self_baseline_max, &self_baseline_min,
&self_baseline_ave,
NULL);
if (error)
goto resume_scanning;
resume_scanning:
/* 11. Resume Scanning*/
resume_error = cyapa_pip_resume_scanning(cyapa);
if (resume_error || error)
return resume_error ? resume_error : error;
/* 12. Output data strings */
size = scnprintf(buf, PAGE_SIZE, "%d %d %d %d %d %d %d %d %d %d %d ",
gidac_mutual_min, gidac_mutual_max, gidac_mutual_ave,
lidac_mutual_min, lidac_mutual_max, lidac_mutual_ave,
gidac_self_rx, gidac_self_tx,
lidac_self_min, lidac_self_max, lidac_self_ave);
size += scnprintf(buf + size, PAGE_SIZE - size,
"%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n",
raw_cap_mutual_min, raw_cap_mutual_max, raw_cap_mutual_ave,
raw_cap_self_min, raw_cap_self_max, raw_cap_self_ave,
mutual_diffdata_min, mutual_diffdata_max, mutual_diffdata_ave,
self_diffdata_min, self_diffdata_max, self_diffdata_ave,
mutual_baseline_min, mutual_baseline_max, mutual_baseline_ave,
self_baseline_min, self_baseline_max, self_baseline_ave);
return size;
}
bool cyapa_pip_sort_system_info_data(struct cyapa *cyapa,
u8 *buf, int len)
{
/* Check the report id and command code */
if (VALID_CMD_RESP_HEADER(buf, 0x02))
return true;
return false;
}
static int cyapa_gen5_bl_query_data(struct cyapa *cyapa)
{
u8 resp_data[PIP_BL_APP_INFO_RESP_LENGTH];
int resp_len;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
pip_bl_read_app_info, PIP_BL_READ_APP_INFO_CMD_LENGTH,
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_bl_resp_data, false);
if (error || resp_len < PIP_BL_APP_INFO_RESP_LENGTH ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data))
return error ? error : -EIO;
memcpy(&cyapa->product_id[0], &resp_data[8], 5);
cyapa->product_id[5] = '-';
memcpy(&cyapa->product_id[6], &resp_data[13], 6);
cyapa->product_id[12] = '-';
memcpy(&cyapa->product_id[13], &resp_data[19], 2);
cyapa->product_id[15] = '\0';
cyapa->fw_maj_ver = resp_data[22];
cyapa->fw_min_ver = resp_data[23];
cyapa->platform_ver = (resp_data[26] >> PIP_BL_PLATFORM_VER_SHIFT) &
PIP_BL_PLATFORM_VER_MASK;
return 0;
}
static int cyapa_gen5_get_query_data(struct cyapa *cyapa)
{
u8 resp_data[PIP_READ_SYS_INFO_RESP_LENGTH];
int resp_len;
u16 product_family;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
pip_read_sys_info, PIP_READ_SYS_INFO_CMD_LENGTH,
resp_data, &resp_len,
2000, cyapa_pip_sort_system_info_data, false);
if (error || resp_len < sizeof(resp_data))
return error ? error : -EIO;
product_family = get_unaligned_le16(&resp_data[7]);
if ((product_family & PIP_PRODUCT_FAMILY_MASK) !=
PIP_PRODUCT_FAMILY_TRACKPAD)
return -EINVAL;
cyapa->platform_ver = (resp_data[49] >> PIP_BL_PLATFORM_VER_SHIFT) &
PIP_BL_PLATFORM_VER_MASK;
if (cyapa->gen == CYAPA_GEN5 && cyapa->platform_ver < 2) {
/* Gen5 firmware that does not support proximity. */
cyapa->fw_maj_ver = resp_data[15];
cyapa->fw_min_ver = resp_data[16];
} else {
cyapa->fw_maj_ver = resp_data[9];
cyapa->fw_min_ver = resp_data[10];
}
cyapa->electrodes_x = resp_data[52];
cyapa->electrodes_y = resp_data[53];
cyapa->physical_size_x = get_unaligned_le16(&resp_data[54]) / 100;
cyapa->physical_size_y = get_unaligned_le16(&resp_data[56]) / 100;
cyapa->max_abs_x = get_unaligned_le16(&resp_data[58]);
cyapa->max_abs_y = get_unaligned_le16(&resp_data[60]);
cyapa->max_z = get_unaligned_le16(&resp_data[62]);
cyapa->x_origin = resp_data[64] & 0x01;
cyapa->y_origin = resp_data[65] & 0x01;
cyapa->btn_capability = (resp_data[70] << 3) & CAPABILITY_BTN_MASK;
memcpy(&cyapa->product_id[0], &resp_data[33], 5);
cyapa->product_id[5] = '-';
memcpy(&cyapa->product_id[6], &resp_data[38], 6);
cyapa->product_id[12] = '-';
memcpy(&cyapa->product_id[13], &resp_data[44], 2);
cyapa->product_id[15] = '\0';
if (!cyapa->electrodes_x || !cyapa->electrodes_y ||
!cyapa->physical_size_x || !cyapa->physical_size_y ||
!cyapa->max_abs_x || !cyapa->max_abs_y || !cyapa->max_z)
return -EINVAL;
return 0;
}
static int cyapa_gen5_do_operational_check(struct cyapa *cyapa)
{
struct device *dev = &cyapa->client->dev;
int error;
if (cyapa->gen != CYAPA_GEN5)
return -ENODEV;
switch (cyapa->state) {
case CYAPA_STATE_GEN5_BL:
error = cyapa_pip_bl_exit(cyapa);
if (error) {
/* Try to update trackpad product information. */
cyapa_gen5_bl_query_data(cyapa);
goto out;
}
cyapa->state = CYAPA_STATE_GEN5_APP;
fallthrough;
case CYAPA_STATE_GEN5_APP:
/*
* If trackpad device in deep sleep mode,
* the app command will fail.
* So always try to reset trackpad device to full active when
* the device state is required.
*/
error = cyapa_gen5_set_power_mode(cyapa,
PWR_MODE_FULL_ACTIVE, 0, CYAPA_PM_ACTIVE);
if (error)
dev_warn(dev, "%s: failed to set power active mode.\n",
__func__);
/* By default, the trackpad proximity function is enabled. */
if (cyapa->platform_ver >= 2) {
error = cyapa_pip_set_proximity(cyapa, true);
if (error)
dev_warn(dev,
"%s: failed to enable proximity.\n",
__func__);
}
/* Get trackpad product information. */
error = cyapa_gen5_get_query_data(cyapa);
if (error)
goto out;
/* Only support product ID starting with CYTRA */
if (memcmp(cyapa->product_id, product_id,
strlen(product_id)) != 0) {
dev_err(dev, "%s: unknown product ID (%s)\n",
__func__, cyapa->product_id);
error = -EINVAL;
}
break;
default:
error = -EINVAL;
}
out:
return error;
}
/*
* Return false, do not continue process
* Return true, continue process.
*/
bool cyapa_pip_irq_cmd_handler(struct cyapa *cyapa)
{
struct cyapa_pip_cmd_states *pip = &cyapa->cmd_states.pip;
int length;
if (atomic_read(&pip->cmd_issued)) {
/* Polling command response data. */
if (pip->is_irq_mode == false)
return false;
/*
* Read out all none command response data.
* these output data may caused by user put finger on
* trackpad when host waiting the command response.
*/
cyapa_i2c_pip_read(cyapa, pip->irq_cmd_buf,
PIP_RESP_LENGTH_SIZE);
length = get_unaligned_le16(pip->irq_cmd_buf);
length = (length <= PIP_RESP_LENGTH_SIZE) ?
PIP_RESP_LENGTH_SIZE : length;
if (length > PIP_RESP_LENGTH_SIZE)
cyapa_i2c_pip_read(cyapa,
pip->irq_cmd_buf, length);
if (!(pip->resp_sort_func &&
pip->resp_sort_func(cyapa,
pip->irq_cmd_buf, length))) {
/*
* Cover the Gen5 V1 firmware issue.
* The issue is no interrupt would be asserted from
* trackpad device to host for the command response
* ready event. Because when there was a finger touch
* on trackpad device, and the firmware output queue
* won't be empty (always with touch report data), so
* the interrupt signal won't be asserted again until
* the output queue was previous emptied.
* This issue would happen in the scenario that
* user always has his/her fingers touched on the
* trackpad device during system booting/rebooting.
*/
length = 0;
if (pip->resp_len)
length = *pip->resp_len;
cyapa_empty_pip_output_data(cyapa,
pip->resp_data,
&length,
pip->resp_sort_func);
if (pip->resp_len && length != 0) {
*pip->resp_len = length;
atomic_dec(&pip->cmd_issued);
complete(&pip->cmd_ready);
}
return false;
}
if (pip->resp_data && pip->resp_len) {
*pip->resp_len = (*pip->resp_len < length) ?
*pip->resp_len : length;
memcpy(pip->resp_data, pip->irq_cmd_buf,
*pip->resp_len);
}
atomic_dec(&pip->cmd_issued);
complete(&pip->cmd_ready);
return false;
}
return true;
}
static void cyapa_pip_report_buttons(struct cyapa *cyapa,
const struct cyapa_pip_report_data *report_data)
{
struct input_dev *input = cyapa->input;
u8 buttons = report_data->report_head[PIP_BUTTONS_OFFSET];
buttons = (buttons << CAPABILITY_BTN_SHIFT) & CAPABILITY_BTN_MASK;
if (cyapa->btn_capability & CAPABILITY_LEFT_BTN_MASK) {
input_report_key(input, BTN_LEFT,
!!(buttons & CAPABILITY_LEFT_BTN_MASK));
}
if (cyapa->btn_capability & CAPABILITY_MIDDLE_BTN_MASK) {
input_report_key(input, BTN_MIDDLE,
!!(buttons & CAPABILITY_MIDDLE_BTN_MASK));
}
if (cyapa->btn_capability & CAPABILITY_RIGHT_BTN_MASK) {
input_report_key(input, BTN_RIGHT,
!!(buttons & CAPABILITY_RIGHT_BTN_MASK));
}
input_sync(input);
}
static void cyapa_pip_report_proximity(struct cyapa *cyapa,
const struct cyapa_pip_report_data *report_data)
{
struct input_dev *input = cyapa->input;
u8 distance = report_data->report_head[PIP_PROXIMITY_DISTANCE_OFFSET] &
PIP_PROXIMITY_DISTANCE_MASK;
input_report_abs(input, ABS_DISTANCE, distance);
input_sync(input);
}
static void cyapa_pip_report_slot_data(struct cyapa *cyapa,
const struct cyapa_pip_touch_record *touch)
{
struct input_dev *input = cyapa->input;
u8 event_id = PIP_GET_EVENT_ID(touch->touch_tip_event_id);
int slot = PIP_GET_TOUCH_ID(touch->touch_tip_event_id);
int x, y;
if (event_id == RECORD_EVENT_LIFTOFF)
return;
input_mt_slot(input, slot);
input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
x = (touch->x_hi << 8) | touch->x_lo;
if (cyapa->x_origin)
x = cyapa->max_abs_x - x;
y = (touch->y_hi << 8) | touch->y_lo;
if (cyapa->y_origin)
y = cyapa->max_abs_y - y;
input_report_abs(input, ABS_MT_POSITION_X, x);
input_report_abs(input, ABS_MT_POSITION_Y, y);
input_report_abs(input, ABS_DISTANCE, 0);
input_report_abs(input, ABS_MT_PRESSURE,
touch->z);
input_report_abs(input, ABS_MT_TOUCH_MAJOR,
touch->major_axis_len);
input_report_abs(input, ABS_MT_TOUCH_MINOR,
touch->minor_axis_len);
input_report_abs(input, ABS_MT_WIDTH_MAJOR,
touch->major_tool_len);
input_report_abs(input, ABS_MT_WIDTH_MINOR,
touch->minor_tool_len);
input_report_abs(input, ABS_MT_ORIENTATION,
touch->orientation);
}
static void cyapa_pip_report_touches(struct cyapa *cyapa,
const struct cyapa_pip_report_data *report_data)
{
struct input_dev *input = cyapa->input;
unsigned int touch_num;
int i;
touch_num = report_data->report_head[PIP_NUMBER_OF_TOUCH_OFFSET] &
PIP_NUMBER_OF_TOUCH_MASK;
for (i = 0; i < touch_num; i++)
cyapa_pip_report_slot_data(cyapa,
&report_data->touch_records[i]);
input_mt_sync_frame(input);
input_sync(input);
}
int cyapa_pip_irq_handler(struct cyapa *cyapa)
{
struct device *dev = &cyapa->client->dev;
struct cyapa_pip_report_data report_data;
unsigned int report_len;
int ret;
if (!cyapa_is_pip_app_mode(cyapa)) {
dev_err(dev, "invalid device state, gen=%d, state=0x%02x\n",
cyapa->gen, cyapa->state);
return -EINVAL;
}
ret = cyapa_i2c_pip_read(cyapa, (u8 *)&report_data,
PIP_RESP_LENGTH_SIZE);
if (ret != PIP_RESP_LENGTH_SIZE) {
dev_err(dev, "failed to read length bytes, (%d)\n", ret);
return -EINVAL;
}
report_len = get_unaligned_le16(
&report_data.report_head[PIP_RESP_LENGTH_OFFSET]);
if (report_len < PIP_RESP_LENGTH_SIZE) {
/* Invalid length or internal reset happened. */
dev_err(dev, "invalid report_len=%d. bytes: %02x %02x\n",
report_len, report_data.report_head[0],
report_data.report_head[1]);
return -EINVAL;
}
/* Idle, no data for report. */
if (report_len == PIP_RESP_LENGTH_SIZE)
return 0;
ret = cyapa_i2c_pip_read(cyapa, (u8 *)&report_data, report_len);
if (ret != report_len) {
dev_err(dev, "failed to read %d bytes report data, (%d)\n",
report_len, ret);
return -EINVAL;
}
return cyapa_pip_event_process(cyapa, &report_data);
}
static int cyapa_pip_event_process(struct cyapa *cyapa,
struct cyapa_pip_report_data *report_data)
{
struct device *dev = &cyapa->client->dev;
unsigned int report_len;
u8 report_id;
report_len = get_unaligned_le16(
&report_data->report_head[PIP_RESP_LENGTH_OFFSET]);
/* Idle, no data for report. */
if (report_len == PIP_RESP_LENGTH_SIZE)
return 0;
report_id = report_data->report_head[PIP_RESP_REPORT_ID_OFFSET];
if (report_id == PIP_WAKEUP_EVENT_REPORT_ID &&
report_len == PIP_WAKEUP_EVENT_SIZE) {
/*
* Device wake event from deep sleep mode for touch.
* This interrupt event is used to wake system up.
*
* Note:
* It will introduce about 20~40 ms additional delay
* time in receiving for first valid touch report data.
* The time is used to execute device runtime resume
* process.
*/
pm_runtime_get_sync(dev);
pm_runtime_mark_last_busy(dev);
pm_runtime_put_sync_autosuspend(dev);
return 0;
} else if (report_id != PIP_TOUCH_REPORT_ID &&
report_id != PIP_BTN_REPORT_ID &&
report_id != GEN5_OLD_PUSH_BTN_REPORT_ID &&
report_id != PIP_PUSH_BTN_REPORT_ID &&
report_id != PIP_PROXIMITY_REPORT_ID) {
/* Running in BL mode or unknown response data read. */
dev_err(dev, "invalid report_id=0x%02x\n", report_id);
return -EINVAL;
}
if (report_id == PIP_TOUCH_REPORT_ID &&
(report_len < PIP_TOUCH_REPORT_HEAD_SIZE ||
report_len > PIP_TOUCH_REPORT_MAX_SIZE)) {
/* Invalid report data length for finger packet. */
dev_err(dev, "invalid touch packet length=%d\n", report_len);
return 0;
}
if ((report_id == PIP_BTN_REPORT_ID ||
report_id == GEN5_OLD_PUSH_BTN_REPORT_ID ||
report_id == PIP_PUSH_BTN_REPORT_ID) &&
(report_len < PIP_BTN_REPORT_HEAD_SIZE ||
report_len > PIP_BTN_REPORT_MAX_SIZE)) {
/* Invalid report data length of button packet. */
dev_err(dev, "invalid button packet length=%d\n", report_len);
return 0;
}
if (report_id == PIP_PROXIMITY_REPORT_ID &&
report_len != PIP_PROXIMITY_REPORT_SIZE) {
/* Invalid report data length of proximity packet. */
dev_err(dev, "invalid proximity data, length=%d\n", report_len);
return 0;
}
if (report_id == PIP_TOUCH_REPORT_ID)
cyapa_pip_report_touches(cyapa, report_data);
else if (report_id == PIP_PROXIMITY_REPORT_ID)
cyapa_pip_report_proximity(cyapa, report_data);
else
cyapa_pip_report_buttons(cyapa, report_data);
return 0;
}
int cyapa_pip_bl_activate(struct cyapa *cyapa) { return 0; }
int cyapa_pip_bl_deactivate(struct cyapa *cyapa) { return 0; }
const struct cyapa_dev_ops cyapa_gen5_ops = {
.check_fw = cyapa_pip_check_fw,
.bl_enter = cyapa_pip_bl_enter,
.bl_initiate = cyapa_pip_bl_initiate,
.update_fw = cyapa_pip_do_fw_update,
.bl_activate = cyapa_pip_bl_activate,
.bl_deactivate = cyapa_pip_bl_deactivate,
.show_baseline = cyapa_gen5_show_baseline,
.calibrate_store = cyapa_pip_do_calibrate,
.initialize = cyapa_pip_cmd_state_initialize,
.state_parse = cyapa_gen5_state_parse,
.operational_check = cyapa_gen5_do_operational_check,
.irq_handler = cyapa_pip_irq_handler,
.irq_cmd_handler = cyapa_pip_irq_cmd_handler,
.sort_empty_output_data = cyapa_empty_pip_output_data,
.set_power_mode = cyapa_gen5_set_power_mode,
.set_proximity = cyapa_pip_set_proximity,
};
|
linux-master
|
drivers/input/mouse/cyapa_gen5.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Driver for DEC VSXXX-AA mouse (hockey-puck mouse, ball or two rollers)
* DEC VSXXX-GA mouse (rectangular mouse, with ball)
* DEC VSXXX-AB tablet (digitizer with hair cross or stylus)
*
* Copyright (C) 2003-2004 by Jan-Benedict Glaw <[email protected]>
*
* The packet format was initially taken from a patch to GPM which is (C) 2001
* by Karsten Merker <[email protected]>
* and Maciej W. Rozycki <[email protected]>
* Later on, I had access to the device's documentation (referenced below).
*/
/*
* Building an adaptor to DE9 / DB25 RS232
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* DISCLAIMER: Use this description AT YOUR OWN RISK! I'll not pay for
* anything if you break your mouse, your computer or whatever!
*
* In theory, this mouse is a simple RS232 device. In practice, it has got
* a quite uncommon plug and the requirement to additionally get a power
* supply at +5V and -12V.
*
* If you look at the socket/jack (_not_ at the plug), we use this pin
* numbering:
* _______
* / 7 6 5 \
* | 4 --- 3 |
* \ 2 1 /
* -------
*
* DEC socket DE9 DB25 Note
* 1 (GND) 5 7 -
* 2 (RxD) 2 3 -
* 3 (TxD) 3 2 -
* 4 (-12V) - - Somewhere from the PSU. At ATX, it's
* the thin blue wire at pin 12 of the
* ATX power connector. Only required for
* VSXXX-AA/-GA mice.
* 5 (+5V) - - PSU (red wires of ATX power connector
* on pin 4, 6, 19 or 20) or HDD power
* connector (also red wire).
* 6 (+12V) - - HDD power connector, yellow wire. Only
* required for VSXXX-AB digitizer.
* 7 (dev. avail.) - - The mouse shorts this one to pin 1.
* This way, the host computer can detect
* the mouse. To use it with the adaptor,
* simply don't connect this pin.
*
* So to get a working adaptor, you need to connect the mouse with three
* wires to a RS232 port and two or three additional wires for +5V, +12V and
* -12V to the PSU.
*
* Flow specification for the link is 4800, 8o1.
*
* The mice and tablet are described in "VCB02 Video Subsystem - Technical
* Manual", DEC EK-104AA-TM-001. You'll find it at MANX, a search engine
* specific for DEC documentation. Try
* http://www.vt100.net/manx/details?pn=EK-104AA-TM-001;id=21;cp=1
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Driver for DEC VSXXX-AA and -GA mice and VSXXX-AB tablet"
MODULE_AUTHOR("Jan-Benedict Glaw <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#undef VSXXXAA_DEBUG
#ifdef VSXXXAA_DEBUG
#define DBG(x...) printk(x)
#else
#define DBG(x...) do {} while (0)
#endif
#define VSXXXAA_INTRO_MASK 0x80
#define VSXXXAA_INTRO_HEAD 0x80
#define IS_HDR_BYTE(x) \
(((x) & VSXXXAA_INTRO_MASK) == VSXXXAA_INTRO_HEAD)
#define VSXXXAA_PACKET_MASK 0xe0
#define VSXXXAA_PACKET_REL 0x80
#define VSXXXAA_PACKET_ABS 0xc0
#define VSXXXAA_PACKET_POR 0xa0
#define MATCH_PACKET_TYPE(data, type) \
(((data) & VSXXXAA_PACKET_MASK) == (type))
struct vsxxxaa {
struct input_dev *dev;
struct serio *serio;
#define BUFLEN 15 /* At least 5 is needed for a full tablet packet */
unsigned char buf[BUFLEN];
unsigned char count;
unsigned char version;
unsigned char country;
unsigned char type;
char name[64];
char phys[32];
};
static void vsxxxaa_drop_bytes(struct vsxxxaa *mouse, int num)
{
if (num >= mouse->count) {
mouse->count = 0;
} else {
memmove(mouse->buf, mouse->buf + num, BUFLEN - num);
mouse->count -= num;
}
}
static void vsxxxaa_queue_byte(struct vsxxxaa *mouse, unsigned char byte)
{
if (mouse->count == BUFLEN) {
printk(KERN_ERR "%s on %s: Dropping a byte of full buffer.\n",
mouse->name, mouse->phys);
vsxxxaa_drop_bytes(mouse, 1);
}
DBG(KERN_INFO "Queueing byte 0x%02x\n", byte);
mouse->buf[mouse->count++] = byte;
}
static void vsxxxaa_detection_done(struct vsxxxaa *mouse)
{
switch (mouse->type) {
case 0x02:
strscpy(mouse->name, "DEC VSXXX-AA/-GA mouse",
sizeof(mouse->name));
break;
case 0x04:
strscpy(mouse->name, "DEC VSXXX-AB digitizer",
sizeof(mouse->name));
break;
default:
snprintf(mouse->name, sizeof(mouse->name),
"unknown DEC pointer device (type = 0x%02x)",
mouse->type);
break;
}
printk(KERN_INFO
"Found %s version 0x%02x from country 0x%02x on port %s\n",
mouse->name, mouse->version, mouse->country, mouse->phys);
}
/*
* Returns number of bytes to be dropped, 0 if packet is okay.
*/
static int vsxxxaa_check_packet(struct vsxxxaa *mouse, int packet_len)
{
int i;
/* First byte must be a header byte */
if (!IS_HDR_BYTE(mouse->buf[0])) {
DBG("vsck: len=%d, 1st=0x%02x\n", packet_len, mouse->buf[0]);
return 1;
}
/* Check all following bytes */
for (i = 1; i < packet_len; i++) {
if (IS_HDR_BYTE(mouse->buf[i])) {
printk(KERN_ERR
"Need to drop %d bytes of a broken packet.\n",
i - 1);
DBG(KERN_INFO "check: len=%d, b[%d]=0x%02x\n",
packet_len, i, mouse->buf[i]);
return i - 1;
}
}
return 0;
}
static inline int vsxxxaa_smells_like_packet(struct vsxxxaa *mouse,
unsigned char type, size_t len)
{
return mouse->count >= len && MATCH_PACKET_TYPE(mouse->buf[0], type);
}
static void vsxxxaa_handle_REL_packet(struct vsxxxaa *mouse)
{
struct input_dev *dev = mouse->dev;
unsigned char *buf = mouse->buf;
int left, middle, right;
int dx, dy;
/*
* Check for normal stream packets. This is three bytes,
* with the first byte's 3 MSB set to 100.
*
* [0]: 1 0 0 SignX SignY Left Middle Right
* [1]: 0 dx dx dx dx dx dx dx
* [2]: 0 dy dy dy dy dy dy dy
*/
/*
* Low 7 bit of byte 1 are abs(dx), bit 7 is
* 0, bit 4 of byte 0 is direction.
*/
dx = buf[1] & 0x7f;
dx *= ((buf[0] >> 4) & 0x01) ? 1 : -1;
/*
* Low 7 bit of byte 2 are abs(dy), bit 7 is
* 0, bit 3 of byte 0 is direction.
*/
dy = buf[2] & 0x7f;
dy *= ((buf[0] >> 3) & 0x01) ? -1 : 1;
/*
* Get button state. It's the low three bits
* (for three buttons) of byte 0.
*/
left = buf[0] & 0x04;
middle = buf[0] & 0x02;
right = buf[0] & 0x01;
vsxxxaa_drop_bytes(mouse, 3);
DBG(KERN_INFO "%s on %s: dx=%d, dy=%d, buttons=%s%s%s\n",
mouse->name, mouse->phys, dx, dy,
left ? "L" : "l", middle ? "M" : "m", right ? "R" : "r");
/*
* Report what we've found so far...
*/
input_report_key(dev, BTN_LEFT, left);
input_report_key(dev, BTN_MIDDLE, middle);
input_report_key(dev, BTN_RIGHT, right);
input_report_key(dev, BTN_TOUCH, 0);
input_report_rel(dev, REL_X, dx);
input_report_rel(dev, REL_Y, dy);
input_sync(dev);
}
static void vsxxxaa_handle_ABS_packet(struct vsxxxaa *mouse)
{
struct input_dev *dev = mouse->dev;
unsigned char *buf = mouse->buf;
int left, middle, right, touch;
int x, y;
/*
* Tablet position / button packet
*
* [0]: 1 1 0 B4 B3 B2 B1 Pr
* [1]: 0 0 X5 X4 X3 X2 X1 X0
* [2]: 0 0 X11 X10 X9 X8 X7 X6
* [3]: 0 0 Y5 Y4 Y3 Y2 Y1 Y0
* [4]: 0 0 Y11 Y10 Y9 Y8 Y7 Y6
*/
/*
* Get X/Y position. Y axis needs to be inverted since VSXXX-AB
* counts down->top while monitor counts top->bottom.
*/
x = ((buf[2] & 0x3f) << 6) | (buf[1] & 0x3f);
y = ((buf[4] & 0x3f) << 6) | (buf[3] & 0x3f);
y = 1023 - y;
/*
* Get button state. It's bits <4..1> of byte 0.
*/
left = buf[0] & 0x02;
middle = buf[0] & 0x04;
right = buf[0] & 0x08;
touch = buf[0] & 0x10;
vsxxxaa_drop_bytes(mouse, 5);
DBG(KERN_INFO "%s on %s: x=%d, y=%d, buttons=%s%s%s%s\n",
mouse->name, mouse->phys, x, y,
left ? "L" : "l", middle ? "M" : "m",
right ? "R" : "r", touch ? "T" : "t");
/*
* Report what we've found so far...
*/
input_report_key(dev, BTN_LEFT, left);
input_report_key(dev, BTN_MIDDLE, middle);
input_report_key(dev, BTN_RIGHT, right);
input_report_key(dev, BTN_TOUCH, touch);
input_report_abs(dev, ABS_X, x);
input_report_abs(dev, ABS_Y, y);
input_sync(dev);
}
static void vsxxxaa_handle_POR_packet(struct vsxxxaa *mouse)
{
struct input_dev *dev = mouse->dev;
unsigned char *buf = mouse->buf;
int left, middle, right;
unsigned char error;
/*
* Check for Power-On-Reset packets. These are sent out
* after plugging the mouse in, or when explicitly
* requested by sending 'T'.
*
* [0]: 1 0 1 0 R3 R2 R1 R0
* [1]: 0 M2 M1 M0 D3 D2 D1 D0
* [2]: 0 E6 E5 E4 E3 E2 E1 E0
* [3]: 0 0 0 0 0 Left Middle Right
*
* M: manufacturer location code
* R: revision code
* E: Error code. If it's in the range of 0x00..0x1f, only some
* minor problem occurred. Errors >= 0x20 are considered bad
* and the device may not work properly...
* D: <0010> == mouse, <0100> == tablet
*/
mouse->version = buf[0] & 0x0f;
mouse->country = (buf[1] >> 4) & 0x07;
mouse->type = buf[1] & 0x0f;
error = buf[2] & 0x7f;
/*
* Get button state. It's the low three bits
* (for three buttons) of byte 0. Maybe even the bit <3>
* has some meaning if a tablet is attached.
*/
left = buf[0] & 0x04;
middle = buf[0] & 0x02;
right = buf[0] & 0x01;
vsxxxaa_drop_bytes(mouse, 4);
vsxxxaa_detection_done(mouse);
if (error <= 0x1f) {
/* No (serious) error. Report buttons */
input_report_key(dev, BTN_LEFT, left);
input_report_key(dev, BTN_MIDDLE, middle);
input_report_key(dev, BTN_RIGHT, right);
input_report_key(dev, BTN_TOUCH, 0);
input_sync(dev);
if (error != 0)
printk(KERN_INFO "Your %s on %s reports error=0x%02x\n",
mouse->name, mouse->phys, error);
}
/*
* If the mouse was hot-plugged, we need to force differential mode
* now... However, give it a second to recover from it's reset.
*/
printk(KERN_NOTICE
"%s on %s: Forcing standard packet format, "
"incremental streaming mode and 72 samples/sec\n",
mouse->name, mouse->phys);
serio_write(mouse->serio, 'S'); /* Standard format */
mdelay(50);
serio_write(mouse->serio, 'R'); /* Incremental */
mdelay(50);
serio_write(mouse->serio, 'L'); /* 72 samples/sec */
}
static void vsxxxaa_parse_buffer(struct vsxxxaa *mouse)
{
unsigned char *buf = mouse->buf;
int stray_bytes;
/*
* Parse buffer to death...
*/
do {
/*
* Out of sync? Throw away what we don't understand. Each
* packet starts with a byte whose bit 7 is set. Unhandled
* packets (ie. which we don't know about or simply b0rk3d
* data...) will get shifted out of the buffer after some
* activity on the mouse.
*/
while (mouse->count > 0 && !IS_HDR_BYTE(buf[0])) {
printk(KERN_ERR "%s on %s: Dropping a byte to regain "
"sync with mouse data stream...\n",
mouse->name, mouse->phys);
vsxxxaa_drop_bytes(mouse, 1);
}
/*
* Check for packets we know about.
*/
if (vsxxxaa_smells_like_packet(mouse, VSXXXAA_PACKET_REL, 3)) {
/* Check for broken packet */
stray_bytes = vsxxxaa_check_packet(mouse, 3);
if (!stray_bytes)
vsxxxaa_handle_REL_packet(mouse);
} else if (vsxxxaa_smells_like_packet(mouse,
VSXXXAA_PACKET_ABS, 5)) {
/* Check for broken packet */
stray_bytes = vsxxxaa_check_packet(mouse, 5);
if (!stray_bytes)
vsxxxaa_handle_ABS_packet(mouse);
} else if (vsxxxaa_smells_like_packet(mouse,
VSXXXAA_PACKET_POR, 4)) {
/* Check for broken packet */
stray_bytes = vsxxxaa_check_packet(mouse, 4);
if (!stray_bytes)
vsxxxaa_handle_POR_packet(mouse);
} else {
break; /* No REL, ABS or POR packet found */
}
if (stray_bytes > 0) {
printk(KERN_ERR "Dropping %d bytes now...\n",
stray_bytes);
vsxxxaa_drop_bytes(mouse, stray_bytes);
}
} while (1);
}
static irqreturn_t vsxxxaa_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct vsxxxaa *mouse = serio_get_drvdata(serio);
vsxxxaa_queue_byte(mouse, data);
vsxxxaa_parse_buffer(mouse);
return IRQ_HANDLED;
}
static void vsxxxaa_disconnect(struct serio *serio)
{
struct vsxxxaa *mouse = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(mouse->dev);
kfree(mouse);
}
static int vsxxxaa_connect(struct serio *serio, struct serio_driver *drv)
{
struct vsxxxaa *mouse;
struct input_dev *input_dev;
int err = -ENOMEM;
mouse = kzalloc(sizeof(struct vsxxxaa), GFP_KERNEL);
input_dev = input_allocate_device();
if (!mouse || !input_dev)
goto fail1;
mouse->dev = input_dev;
mouse->serio = serio;
strlcat(mouse->name, "DEC VSXXX-AA/-GA mouse or VSXXX-AB digitizer",
sizeof(mouse->name));
snprintf(mouse->phys, sizeof(mouse->phys), "%s/input0", serio->phys);
input_dev->name = mouse->name;
input_dev->phys = mouse->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->dev.parent = &serio->dev;
__set_bit(EV_KEY, input_dev->evbit); /* We have buttons */
__set_bit(EV_REL, input_dev->evbit);
__set_bit(EV_ABS, input_dev->evbit);
__set_bit(BTN_LEFT, input_dev->keybit); /* We have 3 buttons */
__set_bit(BTN_MIDDLE, input_dev->keybit);
__set_bit(BTN_RIGHT, input_dev->keybit);
__set_bit(BTN_TOUCH, input_dev->keybit); /* ...and Tablet */
__set_bit(REL_X, input_dev->relbit);
__set_bit(REL_Y, input_dev->relbit);
input_set_abs_params(input_dev, ABS_X, 0, 1023, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 0, 1023, 0, 0);
serio_set_drvdata(serio, mouse);
err = serio_open(serio, drv);
if (err)
goto fail2;
/*
* Request selftest. Standard packet format and differential
* mode will be requested after the device ID'ed successfully.
*/
serio_write(serio, 'T'); /* Test */
err = input_register_device(input_dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(mouse);
return err;
}
static struct serio_device_id vsxxaa_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_VSXXXAA,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, vsxxaa_serio_ids);
static struct serio_driver vsxxxaa_drv = {
.driver = {
.name = "vsxxxaa",
},
.description = DRIVER_DESC,
.id_table = vsxxaa_serio_ids,
.connect = vsxxxaa_connect,
.interrupt = vsxxxaa_interrupt,
.disconnect = vsxxxaa_disconnect,
};
module_serio_driver(vsxxxaa_drv);
|
linux-master
|
drivers/input/mouse/vsxxxaa.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Elan I2C/SMBus Touchpad driver
*
* Copyright (c) 2013 ELAN Microelectronics Corp.
*
* Author: 林政維 (Duson Lin) <[email protected]>
* Author: KT Liao <[email protected]>
* Version: 1.6.3
*
* Based on cyapa driver:
* copyright (c) 2011-2012 Cypress Semiconductor, Inc.
* copyright (c) 2011-2012 Google, Inc.
*
* Trademarks are the property of their respective owners.
*/
#include <linux/acpi.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/firmware.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/input/mt.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/input.h>
#include <linux/uaccess.h>
#include <linux/jiffies.h>
#include <linux/completion.h>
#include <linux/of.h>
#include <linux/pm_wakeirq.h>
#include <linux/property.h>
#include <linux/regulator/consumer.h>
#include <asm/unaligned.h>
#include "elan_i2c.h"
#define DRIVER_NAME "elan_i2c"
#define ELAN_VENDOR_ID 0x04f3
#define ETP_MAX_PRESSURE 255
#define ETP_FWIDTH_REDUCE 90
#define ETP_FINGER_WIDTH 15
#define ETP_RETRY_COUNT 3
/* quirks to control the device */
#define ETP_QUIRK_QUICK_WAKEUP BIT(0)
/* The main device structure */
struct elan_tp_data {
struct i2c_client *client;
struct input_dev *input;
struct input_dev *tp_input; /* trackpoint input node */
struct regulator *vcc;
const struct elan_transport_ops *ops;
/* for fw update */
struct completion fw_completion;
bool in_fw_update;
struct mutex sysfs_mutex;
unsigned int max_x;
unsigned int max_y;
unsigned int width_x;
unsigned int width_y;
unsigned int x_res;
unsigned int y_res;
u8 pattern;
u16 product_id;
u8 fw_version;
u8 sm_version;
u8 iap_version;
u16 fw_checksum;
unsigned int report_features;
unsigned int report_len;
int pressure_adjustment;
u8 mode;
u16 ic_type;
u16 fw_validpage_count;
u16 fw_page_size;
u32 fw_signature_address;
u8 min_baseline;
u8 max_baseline;
bool baseline_ready;
u8 clickpad;
bool middle_button;
u32 quirks; /* Various quirks */
};
static u32 elan_i2c_lookup_quirks(u16 ic_type, u16 product_id)
{
static const struct {
u16 ic_type;
u16 product_id;
u32 quirks;
} elan_i2c_quirks[] = {
{ 0x0D, ETP_PRODUCT_ID_DELBIN, ETP_QUIRK_QUICK_WAKEUP },
{ 0x0D, ETP_PRODUCT_ID_WHITEBOX, ETP_QUIRK_QUICK_WAKEUP },
{ 0x10, ETP_PRODUCT_ID_VOXEL, ETP_QUIRK_QUICK_WAKEUP },
{ 0x14, ETP_PRODUCT_ID_MAGPIE, ETP_QUIRK_QUICK_WAKEUP },
{ 0x14, ETP_PRODUCT_ID_BOBBA, ETP_QUIRK_QUICK_WAKEUP },
};
u32 quirks = 0;
int i;
for (i = 0; i < ARRAY_SIZE(elan_i2c_quirks); i++) {
if (elan_i2c_quirks[i].ic_type == ic_type &&
elan_i2c_quirks[i].product_id == product_id) {
quirks = elan_i2c_quirks[i].quirks;
}
}
if (ic_type >= 0x0D && product_id >= 0x123)
quirks |= ETP_QUIRK_QUICK_WAKEUP;
return quirks;
}
static int elan_get_fwinfo(u16 ic_type, u8 iap_version, u16 *validpage_count,
u32 *signature_address, u16 *page_size)
{
switch (ic_type) {
case 0x00:
case 0x06:
case 0x08:
*validpage_count = 512;
break;
case 0x03:
case 0x07:
case 0x09:
case 0x0A:
case 0x0B:
case 0x0C:
*validpage_count = 768;
break;
case 0x0D:
*validpage_count = 896;
break;
case 0x0E:
*validpage_count = 640;
break;
case 0x10:
*validpage_count = 1024;
break;
case 0x11:
*validpage_count = 1280;
break;
case 0x13:
*validpage_count = 2048;
break;
case 0x14:
case 0x15:
*validpage_count = 1024;
break;
default:
/* unknown ic type clear value */
*validpage_count = 0;
*signature_address = 0;
*page_size = 0;
return -ENXIO;
}
*signature_address =
(*validpage_count * ETP_FW_PAGE_SIZE) - ETP_FW_SIGNATURE_SIZE;
if ((ic_type == 0x14 || ic_type == 0x15) && iap_version >= 2) {
*validpage_count /= 8;
*page_size = ETP_FW_PAGE_SIZE_512;
} else if (ic_type >= 0x0D && iap_version >= 1) {
*validpage_count /= 2;
*page_size = ETP_FW_PAGE_SIZE_128;
} else {
*page_size = ETP_FW_PAGE_SIZE;
}
return 0;
}
static int elan_set_power(struct elan_tp_data *data, bool on)
{
int repeat = ETP_RETRY_COUNT;
int error;
do {
error = data->ops->power_control(data->client, on);
if (error >= 0)
return 0;
msleep(30);
} while (--repeat > 0);
dev_err(&data->client->dev, "failed to set power %s: %d\n",
on ? "on" : "off", error);
return error;
}
static int elan_sleep(struct elan_tp_data *data)
{
int repeat = ETP_RETRY_COUNT;
int error;
do {
error = data->ops->sleep_control(data->client, true);
if (!error)
return 0;
msleep(30);
} while (--repeat > 0);
return error;
}
static int elan_query_product(struct elan_tp_data *data)
{
int error;
error = data->ops->get_product_id(data->client, &data->product_id);
if (error)
return error;
error = data->ops->get_pattern(data->client, &data->pattern);
if (error)
return error;
error = data->ops->get_sm_version(data->client, data->pattern,
&data->ic_type, &data->sm_version,
&data->clickpad);
if (error)
return error;
return 0;
}
static int elan_check_ASUS_special_fw(struct elan_tp_data *data)
{
if (data->ic_type == 0x0E) {
switch (data->product_id) {
case 0x05 ... 0x07:
case 0x09:
case 0x13:
return true;
}
} else if (data->ic_type == 0x08 && data->product_id == 0x26) {
/* ASUS EeeBook X205TA */
return true;
}
return false;
}
static int __elan_initialize(struct elan_tp_data *data, bool skip_reset)
{
struct i2c_client *client = data->client;
bool woken_up = false;
int error;
if (!skip_reset) {
error = data->ops->initialize(client);
if (error) {
dev_err(&client->dev, "device initialize failed: %d\n", error);
return error;
}
}
error = elan_query_product(data);
if (error)
return error;
/*
* Some ASUS devices were shipped with firmware that requires
* touchpads to be woken up first, before attempting to switch
* them into absolute reporting mode.
*/
if (elan_check_ASUS_special_fw(data)) {
error = data->ops->sleep_control(client, false);
if (error) {
dev_err(&client->dev,
"failed to wake device up: %d\n", error);
return error;
}
msleep(200);
woken_up = true;
}
data->mode |= ETP_ENABLE_ABS;
error = data->ops->set_mode(client, data->mode);
if (error) {
dev_err(&client->dev,
"failed to switch to absolute mode: %d\n", error);
return error;
}
if (!woken_up) {
error = data->ops->sleep_control(client, false);
if (error) {
dev_err(&client->dev,
"failed to wake device up: %d\n", error);
return error;
}
}
return 0;
}
static int elan_initialize(struct elan_tp_data *data, bool skip_reset)
{
int repeat = ETP_RETRY_COUNT;
int error;
do {
error = __elan_initialize(data, skip_reset);
if (!error)
return 0;
skip_reset = false;
msleep(30);
} while (--repeat > 0);
return error;
}
static int elan_query_device_info(struct elan_tp_data *data)
{
int error;
error = data->ops->get_version(data->client, data->pattern, false,
&data->fw_version);
if (error)
return error;
error = data->ops->get_checksum(data->client, false,
&data->fw_checksum);
if (error)
return error;
error = data->ops->get_version(data->client, data->pattern,
true, &data->iap_version);
if (error)
return error;
error = data->ops->get_pressure_adjustment(data->client,
&data->pressure_adjustment);
if (error)
return error;
error = data->ops->get_report_features(data->client, data->pattern,
&data->report_features,
&data->report_len);
if (error)
return error;
data->quirks = elan_i2c_lookup_quirks(data->ic_type, data->product_id);
error = elan_get_fwinfo(data->ic_type, data->iap_version,
&data->fw_validpage_count,
&data->fw_signature_address,
&data->fw_page_size);
if (error)
dev_warn(&data->client->dev,
"unexpected iap version %#04x (ic type: %#04x), firmware update will not work\n",
data->iap_version, data->ic_type);
return 0;
}
static unsigned int elan_convert_resolution(u8 val, u8 pattern)
{
/*
* pattern <= 0x01:
* (value from firmware) * 10 + 790 = dpi
* else
* ((value from firmware) + 3) * 100 = dpi
*/
int res = pattern <= 0x01 ?
(int)(char)val * 10 + 790 : ((int)(char)val + 3) * 100;
/*
* We also have to convert dpi to dots/mm (*10/254 to avoid floating
* point).
*/
return res * 10 / 254;
}
static int elan_query_device_parameters(struct elan_tp_data *data)
{
struct i2c_client *client = data->client;
unsigned int x_traces, y_traces;
u32 x_mm, y_mm;
u8 hw_x_res, hw_y_res;
int error;
if (device_property_read_u32(&client->dev,
"touchscreen-size-x", &data->max_x) ||
device_property_read_u32(&client->dev,
"touchscreen-size-y", &data->max_y)) {
error = data->ops->get_max(data->client,
&data->max_x,
&data->max_y);
if (error)
return error;
} else {
/* size is the maximum + 1 */
--data->max_x;
--data->max_y;
}
if (device_property_read_u32(&client->dev,
"elan,x_traces",
&x_traces) ||
device_property_read_u32(&client->dev,
"elan,y_traces",
&y_traces)) {
error = data->ops->get_num_traces(data->client,
&x_traces, &y_traces);
if (error)
return error;
}
data->width_x = data->max_x / x_traces;
data->width_y = data->max_y / y_traces;
if (device_property_read_u32(&client->dev,
"touchscreen-x-mm", &x_mm) ||
device_property_read_u32(&client->dev,
"touchscreen-y-mm", &y_mm)) {
error = data->ops->get_resolution(data->client,
&hw_x_res, &hw_y_res);
if (error)
return error;
data->x_res = elan_convert_resolution(hw_x_res, data->pattern);
data->y_res = elan_convert_resolution(hw_y_res, data->pattern);
} else {
data->x_res = (data->max_x + 1) / x_mm;
data->y_res = (data->max_y + 1) / y_mm;
}
if (device_property_read_bool(&client->dev, "elan,clickpad"))
data->clickpad = 1;
if (device_property_read_bool(&client->dev, "elan,middle-button"))
data->middle_button = true;
return 0;
}
/*
**********************************************************
* IAP firmware updater related routines
**********************************************************
*/
static int elan_write_fw_block(struct elan_tp_data *data, u16 page_size,
const u8 *page, u16 checksum, int idx)
{
int retry = ETP_RETRY_COUNT;
int error;
do {
error = data->ops->write_fw_block(data->client, page_size,
page, checksum, idx);
if (!error)
return 0;
dev_dbg(&data->client->dev,
"IAP retrying page %d (error: %d)\n", idx, error);
} while (--retry > 0);
return error;
}
static int __elan_update_firmware(struct elan_tp_data *data,
const struct firmware *fw)
{
struct i2c_client *client = data->client;
struct device *dev = &client->dev;
int i, j;
int error;
u16 iap_start_addr;
u16 boot_page_count;
u16 sw_checksum = 0, fw_checksum = 0;
error = data->ops->prepare_fw_update(client, data->ic_type,
data->iap_version,
data->fw_page_size);
if (error)
return error;
iap_start_addr = get_unaligned_le16(&fw->data[ETP_IAP_START_ADDR * 2]);
boot_page_count = (iap_start_addr * 2) / data->fw_page_size;
for (i = boot_page_count; i < data->fw_validpage_count; i++) {
u16 checksum = 0;
const u8 *page = &fw->data[i * data->fw_page_size];
for (j = 0; j < data->fw_page_size; j += 2)
checksum += ((page[j + 1] << 8) | page[j]);
error = elan_write_fw_block(data, data->fw_page_size,
page, checksum, i);
if (error) {
dev_err(dev, "write page %d fail: %d\n", i, error);
return error;
}
sw_checksum += checksum;
}
/* Wait WDT reset and power on reset */
msleep(600);
error = data->ops->finish_fw_update(client, &data->fw_completion);
if (error)
return error;
error = data->ops->get_checksum(client, true, &fw_checksum);
if (error)
return error;
if (sw_checksum != fw_checksum) {
dev_err(dev, "checksum diff sw=[%04X], fw=[%04X]\n",
sw_checksum, fw_checksum);
return -EIO;
}
return 0;
}
static int elan_update_firmware(struct elan_tp_data *data,
const struct firmware *fw)
{
struct i2c_client *client = data->client;
int retval;
dev_dbg(&client->dev, "Starting firmware update....\n");
disable_irq(client->irq);
data->in_fw_update = true;
retval = __elan_update_firmware(data, fw);
if (retval) {
dev_err(&client->dev, "firmware update failed: %d\n", retval);
data->ops->iap_reset(client);
} else {
/* Reinitialize TP after fw is updated */
elan_initialize(data, false);
elan_query_device_info(data);
}
data->in_fw_update = false;
enable_irq(client->irq);
return retval;
}
/*
*******************************************************************
* SYSFS attributes
*******************************************************************
*/
static ssize_t elan_sysfs_read_fw_checksum(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
return sprintf(buf, "0x%04x\n", data->fw_checksum);
}
static ssize_t elan_sysfs_read_product_id(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
return sprintf(buf, ETP_PRODUCT_ID_FORMAT_STRING "\n",
data->product_id);
}
static ssize_t elan_sysfs_read_fw_ver(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
return sprintf(buf, "%d.0\n", data->fw_version);
}
static ssize_t elan_sysfs_read_sm_ver(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
return sprintf(buf, "%d.0\n", data->sm_version);
}
static ssize_t elan_sysfs_read_iap_ver(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
return sprintf(buf, "%d.0\n", data->iap_version);
}
static ssize_t elan_sysfs_update_fw(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct elan_tp_data *data = dev_get_drvdata(dev);
const struct firmware *fw;
char *fw_name;
int error;
const u8 *fw_signature;
static const u8 signature[] = {0xAA, 0x55, 0xCC, 0x33, 0xFF, 0xFF};
if (data->fw_validpage_count == 0)
return -EINVAL;
/* Look for a firmware with the product id appended. */
fw_name = kasprintf(GFP_KERNEL, ETP_FW_NAME, data->product_id);
if (!fw_name) {
dev_err(dev, "failed to allocate memory for firmware name\n");
return -ENOMEM;
}
dev_info(dev, "requesting fw '%s'\n", fw_name);
error = request_firmware(&fw, fw_name, dev);
kfree(fw_name);
if (error) {
dev_err(dev, "failed to request firmware: %d\n", error);
return error;
}
/* Firmware file must match signature data */
fw_signature = &fw->data[data->fw_signature_address];
if (memcmp(fw_signature, signature, sizeof(signature)) != 0) {
dev_err(dev, "signature mismatch (expected %*ph, got %*ph)\n",
(int)sizeof(signature), signature,
(int)sizeof(signature), fw_signature);
error = -EBADF;
goto out_release_fw;
}
error = mutex_lock_interruptible(&data->sysfs_mutex);
if (error)
goto out_release_fw;
error = elan_update_firmware(data, fw);
mutex_unlock(&data->sysfs_mutex);
out_release_fw:
release_firmware(fw);
return error ?: count;
}
static ssize_t calibrate_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
int tries = 20;
int retval;
int error;
u8 val[ETP_CALIBRATE_MAX_LEN];
retval = mutex_lock_interruptible(&data->sysfs_mutex);
if (retval)
return retval;
disable_irq(client->irq);
data->mode |= ETP_ENABLE_CALIBRATE;
retval = data->ops->set_mode(client, data->mode);
if (retval) {
dev_err(dev, "failed to enable calibration mode: %d\n",
retval);
goto out;
}
retval = data->ops->calibrate(client);
if (retval) {
dev_err(dev, "failed to start calibration: %d\n",
retval);
goto out_disable_calibrate;
}
val[0] = 0xff;
do {
/* Wait 250ms before checking if calibration has completed. */
msleep(250);
retval = data->ops->calibrate_result(client, val);
if (retval)
dev_err(dev, "failed to check calibration result: %d\n",
retval);
else if (val[0] == 0)
break; /* calibration done */
} while (--tries);
if (tries == 0) {
dev_err(dev, "failed to calibrate. Timeout.\n");
retval = -ETIMEDOUT;
}
out_disable_calibrate:
data->mode &= ~ETP_ENABLE_CALIBRATE;
error = data->ops->set_mode(data->client, data->mode);
if (error) {
dev_err(dev, "failed to disable calibration mode: %d\n",
error);
if (!retval)
retval = error;
}
out:
enable_irq(client->irq);
mutex_unlock(&data->sysfs_mutex);
return retval ?: count;
}
static ssize_t elan_sysfs_read_mode(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
int error;
enum tp_mode mode;
error = mutex_lock_interruptible(&data->sysfs_mutex);
if (error)
return error;
error = data->ops->iap_get_mode(data->client, &mode);
mutex_unlock(&data->sysfs_mutex);
if (error)
return error;
return sprintf(buf, "%d\n", (int)mode);
}
static DEVICE_ATTR(product_id, S_IRUGO, elan_sysfs_read_product_id, NULL);
static DEVICE_ATTR(firmware_version, S_IRUGO, elan_sysfs_read_fw_ver, NULL);
static DEVICE_ATTR(sample_version, S_IRUGO, elan_sysfs_read_sm_ver, NULL);
static DEVICE_ATTR(iap_version, S_IRUGO, elan_sysfs_read_iap_ver, NULL);
static DEVICE_ATTR(fw_checksum, S_IRUGO, elan_sysfs_read_fw_checksum, NULL);
static DEVICE_ATTR(mode, S_IRUGO, elan_sysfs_read_mode, NULL);
static DEVICE_ATTR(update_fw, S_IWUSR, NULL, elan_sysfs_update_fw);
static DEVICE_ATTR_WO(calibrate);
static struct attribute *elan_sysfs_entries[] = {
&dev_attr_product_id.attr,
&dev_attr_firmware_version.attr,
&dev_attr_sample_version.attr,
&dev_attr_iap_version.attr,
&dev_attr_fw_checksum.attr,
&dev_attr_calibrate.attr,
&dev_attr_mode.attr,
&dev_attr_update_fw.attr,
NULL,
};
static const struct attribute_group elan_sysfs_group = {
.attrs = elan_sysfs_entries,
};
static ssize_t acquire_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
int error;
int retval;
retval = mutex_lock_interruptible(&data->sysfs_mutex);
if (retval)
return retval;
disable_irq(client->irq);
data->baseline_ready = false;
data->mode |= ETP_ENABLE_CALIBRATE;
retval = data->ops->set_mode(data->client, data->mode);
if (retval) {
dev_err(dev, "Failed to enable calibration mode to get baseline: %d\n",
retval);
goto out;
}
msleep(250);
retval = data->ops->get_baseline_data(data->client, true,
&data->max_baseline);
if (retval) {
dev_err(dev, "Failed to read max baseline form device: %d\n",
retval);
goto out_disable_calibrate;
}
retval = data->ops->get_baseline_data(data->client, false,
&data->min_baseline);
if (retval) {
dev_err(dev, "Failed to read min baseline form device: %d\n",
retval);
goto out_disable_calibrate;
}
data->baseline_ready = true;
out_disable_calibrate:
data->mode &= ~ETP_ENABLE_CALIBRATE;
error = data->ops->set_mode(data->client, data->mode);
if (error) {
dev_err(dev, "Failed to disable calibration mode after acquiring baseline: %d\n",
error);
if (!retval)
retval = error;
}
out:
enable_irq(client->irq);
mutex_unlock(&data->sysfs_mutex);
return retval ?: count;
}
static ssize_t min_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
int retval;
retval = mutex_lock_interruptible(&data->sysfs_mutex);
if (retval)
return retval;
if (!data->baseline_ready) {
retval = -ENODATA;
goto out;
}
retval = snprintf(buf, PAGE_SIZE, "%d", data->min_baseline);
out:
mutex_unlock(&data->sysfs_mutex);
return retval;
}
static ssize_t max_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
int retval;
retval = mutex_lock_interruptible(&data->sysfs_mutex);
if (retval)
return retval;
if (!data->baseline_ready) {
retval = -ENODATA;
goto out;
}
retval = snprintf(buf, PAGE_SIZE, "%d", data->max_baseline);
out:
mutex_unlock(&data->sysfs_mutex);
return retval;
}
static DEVICE_ATTR_WO(acquire);
static DEVICE_ATTR_RO(min);
static DEVICE_ATTR_RO(max);
static struct attribute *elan_baseline_sysfs_entries[] = {
&dev_attr_acquire.attr,
&dev_attr_min.attr,
&dev_attr_max.attr,
NULL,
};
static const struct attribute_group elan_baseline_sysfs_group = {
.name = "baseline",
.attrs = elan_baseline_sysfs_entries,
};
static const struct attribute_group *elan_sysfs_groups[] = {
&elan_sysfs_group,
&elan_baseline_sysfs_group,
NULL
};
/*
******************************************************************
* Elan isr functions
******************************************************************
*/
static void elan_report_contact(struct elan_tp_data *data, int contact_num,
bool contact_valid, bool high_precision,
u8 *packet, u8 *finger_data)
{
struct input_dev *input = data->input;
unsigned int pos_x, pos_y;
unsigned int pressure, scaled_pressure;
if (contact_valid) {
if (high_precision) {
pos_x = get_unaligned_be16(&finger_data[0]);
pos_y = get_unaligned_be16(&finger_data[2]);
} else {
pos_x = ((finger_data[0] & 0xf0) << 4) | finger_data[1];
pos_y = ((finger_data[0] & 0x0f) << 8) | finger_data[2];
}
if (pos_x > data->max_x || pos_y > data->max_y) {
dev_dbg(input->dev.parent,
"[%d] x=%d y=%d over max (%d, %d)",
contact_num, pos_x, pos_y,
data->max_x, data->max_y);
return;
}
pressure = finger_data[4];
scaled_pressure = pressure + data->pressure_adjustment;
if (scaled_pressure > ETP_MAX_PRESSURE)
scaled_pressure = ETP_MAX_PRESSURE;
input_mt_slot(input, contact_num);
input_mt_report_slot_state(input, MT_TOOL_FINGER, true);
input_report_abs(input, ABS_MT_POSITION_X, pos_x);
input_report_abs(input, ABS_MT_POSITION_Y, data->max_y - pos_y);
input_report_abs(input, ABS_MT_PRESSURE, scaled_pressure);
if (data->report_features & ETP_FEATURE_REPORT_MK) {
unsigned int mk_x, mk_y, area_x, area_y;
u8 mk_data = high_precision ?
packet[ETP_MK_DATA_OFFSET + contact_num] :
finger_data[3];
mk_x = mk_data & 0x0f;
mk_y = mk_data >> 4;
/*
* To avoid treating large finger as palm, let's reduce
* the width x and y per trace.
*/
area_x = mk_x * (data->width_x - ETP_FWIDTH_REDUCE);
area_y = mk_y * (data->width_y - ETP_FWIDTH_REDUCE);
input_report_abs(input, ABS_TOOL_WIDTH, mk_x);
input_report_abs(input, ABS_MT_TOUCH_MAJOR,
max(area_x, area_y));
input_report_abs(input, ABS_MT_TOUCH_MINOR,
min(area_x, area_y));
}
} else {
input_mt_slot(input, contact_num);
input_mt_report_slot_inactive(input);
}
}
static void elan_report_absolute(struct elan_tp_data *data, u8 *packet,
bool high_precision)
{
struct input_dev *input = data->input;
u8 *finger_data = &packet[ETP_FINGER_DATA_OFFSET];
int i;
u8 tp_info = packet[ETP_TOUCH_INFO_OFFSET];
u8 hover_info = packet[ETP_HOVER_INFO_OFFSET];
bool contact_valid, hover_event;
pm_wakeup_event(&data->client->dev, 0);
hover_event = hover_info & BIT(6);
for (i = 0; i < ETP_MAX_FINGERS; i++) {
contact_valid = tp_info & BIT(3 + i);
elan_report_contact(data, i, contact_valid, high_precision,
packet, finger_data);
if (contact_valid)
finger_data += ETP_FINGER_DATA_LEN;
}
input_report_key(input, BTN_LEFT, tp_info & BIT(0));
input_report_key(input, BTN_MIDDLE, tp_info & BIT(2));
input_report_key(input, BTN_RIGHT, tp_info & BIT(1));
input_report_abs(input, ABS_DISTANCE, hover_event != 0);
input_mt_report_pointer_emulation(input, true);
input_sync(input);
}
static void elan_report_trackpoint(struct elan_tp_data *data, u8 *report)
{
struct input_dev *input = data->tp_input;
u8 *packet = &report[ETP_REPORT_ID_OFFSET + 1];
int x, y;
pm_wakeup_event(&data->client->dev, 0);
if (!data->tp_input) {
dev_warn_once(&data->client->dev,
"received a trackpoint report while no trackpoint device has been created. Please report upstream.\n");
return;
}
input_report_key(input, BTN_LEFT, packet[0] & 0x01);
input_report_key(input, BTN_RIGHT, packet[0] & 0x02);
input_report_key(input, BTN_MIDDLE, packet[0] & 0x04);
if ((packet[3] & 0x0F) == 0x06) {
x = packet[4] - (int)((packet[1] ^ 0x80) << 1);
y = (int)((packet[2] ^ 0x80) << 1) - packet[5];
input_report_rel(input, REL_X, x);
input_report_rel(input, REL_Y, y);
}
input_sync(input);
}
static irqreturn_t elan_isr(int irq, void *dev_id)
{
struct elan_tp_data *data = dev_id;
int error;
u8 report[ETP_MAX_REPORT_LEN];
/*
* When device is connected to i2c bus, when all IAP page writes
* complete, the driver will receive interrupt and must read
* 0000 to confirm that IAP is finished.
*/
if (data->in_fw_update) {
complete(&data->fw_completion);
goto out;
}
error = data->ops->get_report(data->client, report, data->report_len);
if (error)
goto out;
switch (report[ETP_REPORT_ID_OFFSET]) {
case ETP_REPORT_ID:
elan_report_absolute(data, report, false);
break;
case ETP_REPORT_ID2:
elan_report_absolute(data, report, true);
break;
case ETP_TP_REPORT_ID:
case ETP_TP_REPORT_ID2:
elan_report_trackpoint(data, report);
break;
default:
dev_err(&data->client->dev, "invalid report id data (%x)\n",
report[ETP_REPORT_ID_OFFSET]);
}
out:
return IRQ_HANDLED;
}
/*
******************************************************************
* Elan initialization functions
******************************************************************
*/
static int elan_setup_trackpoint_input_device(struct elan_tp_data *data)
{
struct device *dev = &data->client->dev;
struct input_dev *input;
input = devm_input_allocate_device(dev);
if (!input)
return -ENOMEM;
input->name = "Elan TrackPoint";
input->id.bustype = BUS_I2C;
input->id.vendor = ELAN_VENDOR_ID;
input->id.product = data->product_id;
input_set_drvdata(input, data);
input_set_capability(input, EV_REL, REL_X);
input_set_capability(input, EV_REL, REL_Y);
input_set_capability(input, EV_KEY, BTN_LEFT);
input_set_capability(input, EV_KEY, BTN_RIGHT);
input_set_capability(input, EV_KEY, BTN_MIDDLE);
__set_bit(INPUT_PROP_POINTER, input->propbit);
__set_bit(INPUT_PROP_POINTING_STICK, input->propbit);
data->tp_input = input;
return 0;
}
static int elan_setup_input_device(struct elan_tp_data *data)
{
struct device *dev = &data->client->dev;
struct input_dev *input;
unsigned int max_width = max(data->width_x, data->width_y);
unsigned int min_width = min(data->width_x, data->width_y);
int error;
input = devm_input_allocate_device(dev);
if (!input)
return -ENOMEM;
input->name = "Elan Touchpad";
input->id.bustype = BUS_I2C;
input->id.vendor = ELAN_VENDOR_ID;
input->id.product = data->product_id;
input_set_drvdata(input, data);
error = input_mt_init_slots(input, ETP_MAX_FINGERS,
INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED);
if (error) {
dev_err(dev, "failed to initialize MT slots: %d\n", error);
return error;
}
__set_bit(EV_ABS, input->evbit);
__set_bit(INPUT_PROP_POINTER, input->propbit);
if (data->clickpad) {
__set_bit(INPUT_PROP_BUTTONPAD, input->propbit);
} else {
__set_bit(BTN_RIGHT, input->keybit);
if (data->middle_button)
__set_bit(BTN_MIDDLE, input->keybit);
}
__set_bit(BTN_LEFT, input->keybit);
/* Set up ST parameters */
input_set_abs_params(input, ABS_X, 0, data->max_x, 0, 0);
input_set_abs_params(input, ABS_Y, 0, data->max_y, 0, 0);
input_abs_set_res(input, ABS_X, data->x_res);
input_abs_set_res(input, ABS_Y, data->y_res);
input_set_abs_params(input, ABS_PRESSURE, 0, ETP_MAX_PRESSURE, 0, 0);
if (data->report_features & ETP_FEATURE_REPORT_MK)
input_set_abs_params(input, ABS_TOOL_WIDTH,
0, ETP_FINGER_WIDTH, 0, 0);
input_set_abs_params(input, ABS_DISTANCE, 0, 1, 0, 0);
/* And MT parameters */
input_set_abs_params(input, ABS_MT_POSITION_X, 0, data->max_x, 0, 0);
input_set_abs_params(input, ABS_MT_POSITION_Y, 0, data->max_y, 0, 0);
input_abs_set_res(input, ABS_MT_POSITION_X, data->x_res);
input_abs_set_res(input, ABS_MT_POSITION_Y, data->y_res);
input_set_abs_params(input, ABS_MT_PRESSURE, 0,
ETP_MAX_PRESSURE, 0, 0);
if (data->report_features & ETP_FEATURE_REPORT_MK) {
input_set_abs_params(input, ABS_MT_TOUCH_MAJOR,
0, ETP_FINGER_WIDTH * max_width, 0, 0);
input_set_abs_params(input, ABS_MT_TOUCH_MINOR,
0, ETP_FINGER_WIDTH * min_width, 0, 0);
}
data->input = input;
return 0;
}
static void elan_disable_regulator(void *_data)
{
struct elan_tp_data *data = _data;
regulator_disable(data->vcc);
}
static int elan_probe(struct i2c_client *client)
{
const struct elan_transport_ops *transport_ops;
struct device *dev = &client->dev;
struct elan_tp_data *data;
unsigned long irqflags;
int error;
if (IS_ENABLED(CONFIG_MOUSE_ELAN_I2C_I2C) &&
i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
transport_ops = &elan_i2c_ops;
} else if (IS_ENABLED(CONFIG_MOUSE_ELAN_I2C_SMBUS) &&
i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_BLOCK_DATA |
I2C_FUNC_SMBUS_I2C_BLOCK)) {
transport_ops = &elan_smbus_ops;
} else {
dev_err(dev, "not a supported I2C/SMBus adapter\n");
return -EIO;
}
data = devm_kzalloc(dev, sizeof(struct elan_tp_data), GFP_KERNEL);
if (!data)
return -ENOMEM;
i2c_set_clientdata(client, data);
data->ops = transport_ops;
data->client = client;
init_completion(&data->fw_completion);
mutex_init(&data->sysfs_mutex);
data->vcc = devm_regulator_get(dev, "vcc");
if (IS_ERR(data->vcc))
return dev_err_probe(dev, PTR_ERR(data->vcc), "Failed to get 'vcc' regulator\n");
error = regulator_enable(data->vcc);
if (error) {
dev_err(dev, "Failed to enable regulator: %d\n", error);
return error;
}
error = devm_add_action_or_reset(dev, elan_disable_regulator, data);
if (error) {
dev_err(dev, "Failed to add disable regulator action: %d\n",
error);
return error;
}
/* Make sure there is something at this address */
error = i2c_smbus_read_byte(client);
if (error < 0) {
dev_dbg(&client->dev, "nothing at this address: %d\n", error);
return -ENXIO;
}
/* Initialize the touchpad. */
error = elan_initialize(data, false);
if (error)
return error;
error = elan_query_device_info(data);
if (error)
return error;
error = elan_query_device_parameters(data);
if (error)
return error;
dev_info(dev,
"Elan Touchpad: Module ID: 0x%04x, Firmware: 0x%04x, Sample: 0x%04x, IAP: 0x%04x\n",
data->product_id,
data->fw_version,
data->sm_version,
data->iap_version);
dev_dbg(dev,
"Elan Touchpad Extra Information:\n"
" Max ABS X,Y: %d,%d\n"
" Width X,Y: %d,%d\n"
" Resolution X,Y: %d,%d (dots/mm)\n"
" ic type: 0x%x\n"
" info pattern: 0x%x\n",
data->max_x, data->max_y,
data->width_x, data->width_y,
data->x_res, data->y_res,
data->ic_type, data->pattern);
/* Set up input device properties based on queried parameters. */
error = elan_setup_input_device(data);
if (error)
return error;
if (device_property_read_bool(&client->dev, "elan,trackpoint")) {
error = elan_setup_trackpoint_input_device(data);
if (error)
return error;
}
/*
* Platform code (ACPI, DTS) should normally set up interrupt
* for us, but in case it did not let's fall back to using falling
* edge to be compatible with older Chromebooks.
*/
irqflags = irq_get_trigger_type(client->irq);
if (!irqflags)
irqflags = IRQF_TRIGGER_FALLING;
error = devm_request_threaded_irq(dev, client->irq, NULL, elan_isr,
irqflags | IRQF_ONESHOT,
client->name, data);
if (error) {
dev_err(dev, "cannot register irq=%d\n", client->irq);
return error;
}
error = input_register_device(data->input);
if (error) {
dev_err(dev, "failed to register input device: %d\n", error);
return error;
}
if (data->tp_input) {
error = input_register_device(data->tp_input);
if (error) {
dev_err(&client->dev,
"failed to register TrackPoint input device: %d\n",
error);
return error;
}
}
return 0;
}
static int elan_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
int ret;
/*
* We are taking the mutex to make sure sysfs operations are
* complete before we attempt to bring the device into low[er]
* power mode.
*/
ret = mutex_lock_interruptible(&data->sysfs_mutex);
if (ret)
return ret;
disable_irq(client->irq);
if (device_may_wakeup(dev)) {
ret = elan_sleep(data);
} else {
ret = elan_set_power(data, false);
if (ret)
goto err;
ret = regulator_disable(data->vcc);
if (ret) {
dev_err(dev, "error %d disabling regulator\n", ret);
/* Attempt to power the chip back up */
elan_set_power(data, true);
}
}
err:
mutex_unlock(&data->sysfs_mutex);
return ret;
}
static int elan_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct elan_tp_data *data = i2c_get_clientdata(client);
int error;
if (!device_may_wakeup(dev)) {
error = regulator_enable(data->vcc);
if (error) {
dev_err(dev, "error %d enabling regulator\n", error);
goto err;
}
}
error = elan_set_power(data, true);
if (error) {
dev_err(dev, "power up when resuming failed: %d\n", error);
goto err;
}
error = elan_initialize(data, data->quirks & ETP_QUIRK_QUICK_WAKEUP);
if (error)
dev_err(dev, "initialize when resuming failed: %d\n", error);
err:
enable_irq(data->client->irq);
return error;
}
static DEFINE_SIMPLE_DEV_PM_OPS(elan_pm_ops, elan_suspend, elan_resume);
static const struct i2c_device_id elan_id[] = {
{ DRIVER_NAME, 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, elan_id);
#ifdef CONFIG_ACPI
#include <linux/input/elan-i2c-ids.h>
MODULE_DEVICE_TABLE(acpi, elan_acpi_id);
#endif
#ifdef CONFIG_OF
static const struct of_device_id elan_of_match[] = {
{ .compatible = "elan,ekth3000" },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, elan_of_match);
#endif
static struct i2c_driver elan_driver = {
.driver = {
.name = DRIVER_NAME,
.pm = pm_sleep_ptr(&elan_pm_ops),
.acpi_match_table = ACPI_PTR(elan_acpi_id),
.of_match_table = of_match_ptr(elan_of_match),
.probe_type = PROBE_PREFER_ASYNCHRONOUS,
.dev_groups = elan_sysfs_groups,
},
.probe = elan_probe,
.id_table = elan_id,
};
module_i2c_driver(elan_driver);
MODULE_AUTHOR("Duson Lin <[email protected]>");
MODULE_DESCRIPTION("Elan I2C/SMBus Touchpad driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/mouse/elan_i2c_core.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* ALPS touchpad PS/2 mouse driver
*
* Copyright (c) 2003 Neil Brown <[email protected]>
* Copyright (c) 2003-2005 Peter Osterlund <[email protected]>
* Copyright (c) 2004 Dmitry Torokhov <[email protected]>
* Copyright (c) 2005 Vojtech Pavlik <[email protected]>
* Copyright (c) 2009 Sebastian Kapfer <[email protected]>
*
* ALPS detection, tap switching and status querying info is taken from
* tpconfig utility (by C. Scott Ananian and Bruce Kall).
*/
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include <linux/dmi.h>
#include "psmouse.h"
#include "alps.h"
#include "trackpoint.h"
/*
* Definitions for ALPS version 3 and 4 command mode protocol
*/
#define ALPS_CMD_NIBBLE_10 0x01f2
#define ALPS_REG_BASE_RUSHMORE 0xc2c0
#define ALPS_REG_BASE_V7 0xc2c0
#define ALPS_REG_BASE_PINNACLE 0x0000
static const struct alps_nibble_commands alps_v3_nibble_commands[] = {
{ PSMOUSE_CMD_SETPOLL, 0x00 }, /* 0 */
{ PSMOUSE_CMD_RESET_DIS, 0x00 }, /* 1 */
{ PSMOUSE_CMD_SETSCALE21, 0x00 }, /* 2 */
{ PSMOUSE_CMD_SETRATE, 0x0a }, /* 3 */
{ PSMOUSE_CMD_SETRATE, 0x14 }, /* 4 */
{ PSMOUSE_CMD_SETRATE, 0x28 }, /* 5 */
{ PSMOUSE_CMD_SETRATE, 0x3c }, /* 6 */
{ PSMOUSE_CMD_SETRATE, 0x50 }, /* 7 */
{ PSMOUSE_CMD_SETRATE, 0x64 }, /* 8 */
{ PSMOUSE_CMD_SETRATE, 0xc8 }, /* 9 */
{ ALPS_CMD_NIBBLE_10, 0x00 }, /* a */
{ PSMOUSE_CMD_SETRES, 0x00 }, /* b */
{ PSMOUSE_CMD_SETRES, 0x01 }, /* c */
{ PSMOUSE_CMD_SETRES, 0x02 }, /* d */
{ PSMOUSE_CMD_SETRES, 0x03 }, /* e */
{ PSMOUSE_CMD_SETSCALE11, 0x00 }, /* f */
};
static const struct alps_nibble_commands alps_v4_nibble_commands[] = {
{ PSMOUSE_CMD_ENABLE, 0x00 }, /* 0 */
{ PSMOUSE_CMD_RESET_DIS, 0x00 }, /* 1 */
{ PSMOUSE_CMD_SETSCALE21, 0x00 }, /* 2 */
{ PSMOUSE_CMD_SETRATE, 0x0a }, /* 3 */
{ PSMOUSE_CMD_SETRATE, 0x14 }, /* 4 */
{ PSMOUSE_CMD_SETRATE, 0x28 }, /* 5 */
{ PSMOUSE_CMD_SETRATE, 0x3c }, /* 6 */
{ PSMOUSE_CMD_SETRATE, 0x50 }, /* 7 */
{ PSMOUSE_CMD_SETRATE, 0x64 }, /* 8 */
{ PSMOUSE_CMD_SETRATE, 0xc8 }, /* 9 */
{ ALPS_CMD_NIBBLE_10, 0x00 }, /* a */
{ PSMOUSE_CMD_SETRES, 0x00 }, /* b */
{ PSMOUSE_CMD_SETRES, 0x01 }, /* c */
{ PSMOUSE_CMD_SETRES, 0x02 }, /* d */
{ PSMOUSE_CMD_SETRES, 0x03 }, /* e */
{ PSMOUSE_CMD_SETSCALE11, 0x00 }, /* f */
};
static const struct alps_nibble_commands alps_v6_nibble_commands[] = {
{ PSMOUSE_CMD_ENABLE, 0x00 }, /* 0 */
{ PSMOUSE_CMD_SETRATE, 0x0a }, /* 1 */
{ PSMOUSE_CMD_SETRATE, 0x14 }, /* 2 */
{ PSMOUSE_CMD_SETRATE, 0x28 }, /* 3 */
{ PSMOUSE_CMD_SETRATE, 0x3c }, /* 4 */
{ PSMOUSE_CMD_SETRATE, 0x50 }, /* 5 */
{ PSMOUSE_CMD_SETRATE, 0x64 }, /* 6 */
{ PSMOUSE_CMD_SETRATE, 0xc8 }, /* 7 */
{ PSMOUSE_CMD_GETID, 0x00 }, /* 8 */
{ PSMOUSE_CMD_GETINFO, 0x00 }, /* 9 */
{ PSMOUSE_CMD_SETRES, 0x00 }, /* a */
{ PSMOUSE_CMD_SETRES, 0x01 }, /* b */
{ PSMOUSE_CMD_SETRES, 0x02 }, /* c */
{ PSMOUSE_CMD_SETRES, 0x03 }, /* d */
{ PSMOUSE_CMD_SETSCALE21, 0x00 }, /* e */
{ PSMOUSE_CMD_SETSCALE11, 0x00 }, /* f */
};
#define ALPS_DUALPOINT 0x02 /* touchpad has trackstick */
#define ALPS_PASS 0x04 /* device has a pass-through port */
#define ALPS_WHEEL 0x08 /* hardware wheel present */
#define ALPS_FW_BK_1 0x10 /* front & back buttons present */
#define ALPS_FW_BK_2 0x20 /* front & back buttons present */
#define ALPS_FOUR_BUTTONS 0x40 /* 4 direction button present */
#define ALPS_PS2_INTERLEAVED 0x80 /* 3-byte PS/2 packet interleaved with
6-byte ALPS packet */
#define ALPS_STICK_BITS 0x100 /* separate stick button bits */
#define ALPS_BUTTONPAD 0x200 /* device is a clickpad */
#define ALPS_DUALPOINT_WITH_PRESSURE 0x400 /* device can report trackpoint pressure */
static const struct alps_model_info alps_model_data[] = {
/*
* XXX This entry is suspicious. First byte has zero lower nibble,
* which is what a normal mouse would report. Also, the value 0x0e
* isn't valid per PS/2 spec.
*/
{ { 0x20, 0x02, 0x0e }, { ALPS_PROTO_V2, 0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT } },
{ { 0x22, 0x02, 0x0a }, { ALPS_PROTO_V2, 0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT } },
{ { 0x22, 0x02, 0x14 }, { ALPS_PROTO_V2, 0xff, 0xff, ALPS_PASS | ALPS_DUALPOINT } }, /* Dell Latitude D600 */
{ { 0x32, 0x02, 0x14 }, { ALPS_PROTO_V2, 0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT } }, /* Toshiba Salellite Pro M10 */
{ { 0x33, 0x02, 0x0a }, { ALPS_PROTO_V1, 0x88, 0xf8, 0 } }, /* UMAX-530T */
{ { 0x52, 0x01, 0x14 }, { ALPS_PROTO_V2, 0xff, 0xff,
ALPS_PASS | ALPS_DUALPOINT | ALPS_PS2_INTERLEAVED } }, /* Toshiba Tecra A11-11L */
{ { 0x53, 0x02, 0x0a }, { ALPS_PROTO_V2, 0xf8, 0xf8, 0 } },
{ { 0x53, 0x02, 0x14 }, { ALPS_PROTO_V2, 0xf8, 0xf8, 0 } },
{ { 0x60, 0x03, 0xc8 }, { ALPS_PROTO_V2, 0xf8, 0xf8, 0 } }, /* HP ze1115 */
{ { 0x62, 0x02, 0x14 }, { ALPS_PROTO_V2, 0xcf, 0xcf,
ALPS_PASS | ALPS_DUALPOINT | ALPS_PS2_INTERLEAVED } }, /* Dell Latitude E5500, E6400, E6500, Precision M4400 */
{ { 0x63, 0x02, 0x0a }, { ALPS_PROTO_V2, 0xf8, 0xf8, 0 } },
{ { 0x63, 0x02, 0x14 }, { ALPS_PROTO_V2, 0xf8, 0xf8, 0 } },
{ { 0x63, 0x02, 0x28 }, { ALPS_PROTO_V2, 0xf8, 0xf8, ALPS_FW_BK_2 } }, /* Fujitsu Siemens S6010 */
{ { 0x63, 0x02, 0x3c }, { ALPS_PROTO_V2, 0x8f, 0x8f, ALPS_WHEEL } }, /* Toshiba Satellite S2400-103 */
{ { 0x63, 0x02, 0x50 }, { ALPS_PROTO_V2, 0xef, 0xef, ALPS_FW_BK_1 } }, /* NEC Versa L320 */
{ { 0x63, 0x02, 0x64 }, { ALPS_PROTO_V2, 0xf8, 0xf8, 0 } },
{ { 0x63, 0x03, 0xc8 }, { ALPS_PROTO_V2, 0xf8, 0xf8, ALPS_PASS | ALPS_DUALPOINT } }, /* Dell Latitude D800 */
{ { 0x73, 0x00, 0x0a }, { ALPS_PROTO_V2, 0xf8, 0xf8, ALPS_DUALPOINT } }, /* ThinkPad R61 8918-5QG */
{ { 0x73, 0x00, 0x14 }, { ALPS_PROTO_V6, 0xff, 0xff, ALPS_DUALPOINT } }, /* Dell XT2 */
{ { 0x73, 0x02, 0x0a }, { ALPS_PROTO_V2, 0xf8, 0xf8, 0 } },
{ { 0x73, 0x02, 0x14 }, { ALPS_PROTO_V2, 0xf8, 0xf8, ALPS_FW_BK_2 } }, /* Ahtec Laptop */
{ { 0x73, 0x02, 0x50 }, { ALPS_PROTO_V2, 0xcf, 0xcf, ALPS_FOUR_BUTTONS } }, /* Dell Vostro 1400 */
};
static const struct alps_protocol_info alps_v3_protocol_data = {
ALPS_PROTO_V3, 0x8f, 0x8f, ALPS_DUALPOINT | ALPS_DUALPOINT_WITH_PRESSURE
};
static const struct alps_protocol_info alps_v3_rushmore_data = {
ALPS_PROTO_V3_RUSHMORE, 0x8f, 0x8f, ALPS_DUALPOINT | ALPS_DUALPOINT_WITH_PRESSURE
};
static const struct alps_protocol_info alps_v4_protocol_data = {
ALPS_PROTO_V4, 0x8f, 0x8f, 0
};
static const struct alps_protocol_info alps_v5_protocol_data = {
ALPS_PROTO_V5, 0xc8, 0xd8, 0
};
static const struct alps_protocol_info alps_v7_protocol_data = {
ALPS_PROTO_V7, 0x48, 0x48, ALPS_DUALPOINT | ALPS_DUALPOINT_WITH_PRESSURE
};
static const struct alps_protocol_info alps_v8_protocol_data = {
ALPS_PROTO_V8, 0x18, 0x18, 0
};
static const struct alps_protocol_info alps_v9_protocol_data = {
ALPS_PROTO_V9, 0xc8, 0xc8, 0
};
/*
* Some v2 models report the stick buttons in separate bits
*/
static const struct dmi_system_id alps_dmi_has_separate_stick_buttons[] = {
#if defined(CONFIG_DMI) && defined(CONFIG_X86)
{
/* Extrapolated from other entries */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Latitude D420"),
},
},
{
/* Reported-by: Hans de Bruin <[email protected]> */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Latitude D430"),
},
},
{
/* Reported-by: Hans de Goede <[email protected]> */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Latitude D620"),
},
},
{
/* Extrapolated from other entries */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
DMI_MATCH(DMI_PRODUCT_NAME, "Latitude D630"),
},
},
#endif
{ }
};
static void alps_set_abs_params_st(struct alps_data *priv,
struct input_dev *dev1);
static void alps_set_abs_params_semi_mt(struct alps_data *priv,
struct input_dev *dev1);
static void alps_set_abs_params_v7(struct alps_data *priv,
struct input_dev *dev1);
static void alps_set_abs_params_ss4_v2(struct alps_data *priv,
struct input_dev *dev1);
/* Packet formats are described in Documentation/input/devices/alps.rst */
static bool alps_is_valid_first_byte(struct alps_data *priv,
unsigned char data)
{
return (data & priv->mask0) == priv->byte0;
}
static void alps_report_buttons(struct input_dev *dev1, struct input_dev *dev2,
int left, int right, int middle)
{
struct input_dev *dev;
/*
* If shared button has already been reported on the
* other device (dev2) then this event should be also
* sent through that device.
*/
dev = (dev2 && test_bit(BTN_LEFT, dev2->key)) ? dev2 : dev1;
input_report_key(dev, BTN_LEFT, left);
dev = (dev2 && test_bit(BTN_RIGHT, dev2->key)) ? dev2 : dev1;
input_report_key(dev, BTN_RIGHT, right);
dev = (dev2 && test_bit(BTN_MIDDLE, dev2->key)) ? dev2 : dev1;
input_report_key(dev, BTN_MIDDLE, middle);
/*
* Sync the _other_ device now, we'll do the first
* device later once we report the rest of the events.
*/
if (dev2)
input_sync(dev2);
}
static void alps_process_packet_v1_v2(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char *packet = psmouse->packet;
struct input_dev *dev = psmouse->dev;
struct input_dev *dev2 = priv->dev2;
int x, y, z, ges, fin, left, right, middle;
int back = 0, forward = 0;
if (priv->proto_version == ALPS_PROTO_V1) {
left = packet[2] & 0x10;
right = packet[2] & 0x08;
middle = 0;
x = packet[1] | ((packet[0] & 0x07) << 7);
y = packet[4] | ((packet[3] & 0x07) << 7);
z = packet[5];
} else {
left = packet[3] & 1;
right = packet[3] & 2;
middle = packet[3] & 4;
x = packet[1] | ((packet[2] & 0x78) << (7 - 3));
y = packet[4] | ((packet[3] & 0x70) << (7 - 4));
z = packet[5];
}
if (priv->flags & ALPS_FW_BK_1) {
back = packet[0] & 0x10;
forward = packet[2] & 4;
}
if (priv->flags & ALPS_FW_BK_2) {
back = packet[3] & 4;
forward = packet[2] & 4;
if ((middle = forward && back))
forward = back = 0;
}
ges = packet[2] & 1;
fin = packet[2] & 2;
if ((priv->flags & ALPS_DUALPOINT) && z == 127) {
input_report_rel(dev2, REL_X, (x > 383 ? (x - 768) : x));
input_report_rel(dev2, REL_Y, -(y > 255 ? (y - 512) : y));
alps_report_buttons(dev2, dev, left, right, middle);
input_sync(dev2);
return;
}
/* Some models have separate stick button bits */
if (priv->flags & ALPS_STICK_BITS) {
left |= packet[0] & 1;
right |= packet[0] & 2;
middle |= packet[0] & 4;
}
alps_report_buttons(dev, dev2, left, right, middle);
/* Convert hardware tap to a reasonable Z value */
if (ges && !fin)
z = 40;
/*
* A "tap and drag" operation is reported by the hardware as a transition
* from (!fin && ges) to (fin && ges). This should be translated to the
* sequence Z>0, Z==0, Z>0, so the Z==0 event has to be generated manually.
*/
if (ges && fin && !priv->prev_fin) {
input_report_abs(dev, ABS_X, x);
input_report_abs(dev, ABS_Y, y);
input_report_abs(dev, ABS_PRESSURE, 0);
input_report_key(dev, BTN_TOOL_FINGER, 0);
input_sync(dev);
}
priv->prev_fin = fin;
if (z > 30)
input_report_key(dev, BTN_TOUCH, 1);
if (z < 25)
input_report_key(dev, BTN_TOUCH, 0);
if (z > 0) {
input_report_abs(dev, ABS_X, x);
input_report_abs(dev, ABS_Y, y);
}
input_report_abs(dev, ABS_PRESSURE, z);
input_report_key(dev, BTN_TOOL_FINGER, z > 0);
if (priv->flags & ALPS_WHEEL)
input_report_rel(dev, REL_WHEEL, ((packet[2] << 1) & 0x08) - ((packet[0] >> 4) & 0x07));
if (priv->flags & (ALPS_FW_BK_1 | ALPS_FW_BK_2)) {
input_report_key(dev, BTN_FORWARD, forward);
input_report_key(dev, BTN_BACK, back);
}
if (priv->flags & ALPS_FOUR_BUTTONS) {
input_report_key(dev, BTN_0, packet[2] & 4);
input_report_key(dev, BTN_1, packet[0] & 0x10);
input_report_key(dev, BTN_2, packet[3] & 4);
input_report_key(dev, BTN_3, packet[0] & 0x20);
}
input_sync(dev);
}
static void alps_get_bitmap_points(unsigned int map,
struct alps_bitmap_point *low,
struct alps_bitmap_point *high,
int *fingers)
{
struct alps_bitmap_point *point;
int i, bit, prev_bit = 0;
point = low;
for (i = 0; map != 0; i++, map >>= 1) {
bit = map & 1;
if (bit) {
if (!prev_bit) {
point->start_bit = i;
point->num_bits = 0;
(*fingers)++;
}
point->num_bits++;
} else {
if (prev_bit)
point = high;
}
prev_bit = bit;
}
}
/*
* Process bitmap data from semi-mt protocols. Returns the number of
* fingers detected. A return value of 0 means at least one of the
* bitmaps was empty.
*
* The bitmaps don't have enough data to track fingers, so this function
* only generates points representing a bounding box of all contacts.
* These points are returned in fields->mt when the return value
* is greater than 0.
*/
static int alps_process_bitmap(struct alps_data *priv,
struct alps_fields *fields)
{
int i, fingers_x = 0, fingers_y = 0, fingers, closest;
struct alps_bitmap_point x_low = {0,}, x_high = {0,};
struct alps_bitmap_point y_low = {0,}, y_high = {0,};
struct input_mt_pos corner[4];
if (!fields->x_map || !fields->y_map)
return 0;
alps_get_bitmap_points(fields->x_map, &x_low, &x_high, &fingers_x);
alps_get_bitmap_points(fields->y_map, &y_low, &y_high, &fingers_y);
/*
* Fingers can overlap, so we use the maximum count of fingers
* on either axis as the finger count.
*/
fingers = max(fingers_x, fingers_y);
/*
* If an axis reports only a single contact, we have overlapping or
* adjacent fingers. Divide the single contact between the two points.
*/
if (fingers_x == 1) {
i = (x_low.num_bits - 1) / 2;
x_low.num_bits = x_low.num_bits - i;
x_high.start_bit = x_low.start_bit + i;
x_high.num_bits = max(i, 1);
}
if (fingers_y == 1) {
i = (y_low.num_bits - 1) / 2;
y_low.num_bits = y_low.num_bits - i;
y_high.start_bit = y_low.start_bit + i;
y_high.num_bits = max(i, 1);
}
/* top-left corner */
corner[0].x =
(priv->x_max * (2 * x_low.start_bit + x_low.num_bits - 1)) /
(2 * (priv->x_bits - 1));
corner[0].y =
(priv->y_max * (2 * y_low.start_bit + y_low.num_bits - 1)) /
(2 * (priv->y_bits - 1));
/* top-right corner */
corner[1].x =
(priv->x_max * (2 * x_high.start_bit + x_high.num_bits - 1)) /
(2 * (priv->x_bits - 1));
corner[1].y =
(priv->y_max * (2 * y_low.start_bit + y_low.num_bits - 1)) /
(2 * (priv->y_bits - 1));
/* bottom-right corner */
corner[2].x =
(priv->x_max * (2 * x_high.start_bit + x_high.num_bits - 1)) /
(2 * (priv->x_bits - 1));
corner[2].y =
(priv->y_max * (2 * y_high.start_bit + y_high.num_bits - 1)) /
(2 * (priv->y_bits - 1));
/* bottom-left corner */
corner[3].x =
(priv->x_max * (2 * x_low.start_bit + x_low.num_bits - 1)) /
(2 * (priv->x_bits - 1));
corner[3].y =
(priv->y_max * (2 * y_high.start_bit + y_high.num_bits - 1)) /
(2 * (priv->y_bits - 1));
/* x-bitmap order is reversed on v5 touchpads */
if (priv->proto_version == ALPS_PROTO_V5) {
for (i = 0; i < 4; i++)
corner[i].x = priv->x_max - corner[i].x;
}
/* y-bitmap order is reversed on v3 and v4 touchpads */
if (priv->proto_version == ALPS_PROTO_V3 ||
priv->proto_version == ALPS_PROTO_V4) {
for (i = 0; i < 4; i++)
corner[i].y = priv->y_max - corner[i].y;
}
/*
* We only select a corner for the second touch once per 2 finger
* touch sequence to avoid the chosen corner (and thus the coordinates)
* jumping around when the first touch is in the middle.
*/
if (priv->second_touch == -1) {
/* Find corner closest to our st coordinates */
closest = 0x7fffffff;
for (i = 0; i < 4; i++) {
int dx = fields->st.x - corner[i].x;
int dy = fields->st.y - corner[i].y;
int distance = dx * dx + dy * dy;
if (distance < closest) {
priv->second_touch = i;
closest = distance;
}
}
/* And select the opposite corner to use for the 2nd touch */
priv->second_touch = (priv->second_touch + 2) % 4;
}
fields->mt[0] = fields->st;
fields->mt[1] = corner[priv->second_touch];
return fingers;
}
static void alps_set_slot(struct input_dev *dev, int slot, int x, int y)
{
input_mt_slot(dev, slot);
input_mt_report_slot_state(dev, MT_TOOL_FINGER, true);
input_report_abs(dev, ABS_MT_POSITION_X, x);
input_report_abs(dev, ABS_MT_POSITION_Y, y);
}
static void alps_report_mt_data(struct psmouse *psmouse, int n)
{
struct alps_data *priv = psmouse->private;
struct input_dev *dev = psmouse->dev;
struct alps_fields *f = &priv->f;
int i, slot[MAX_TOUCHES];
input_mt_assign_slots(dev, slot, f->mt, n, 0);
for (i = 0; i < n; i++)
alps_set_slot(dev, slot[i], f->mt[i].x, f->mt[i].y);
input_mt_sync_frame(dev);
}
static void alps_report_semi_mt_data(struct psmouse *psmouse, int fingers)
{
struct alps_data *priv = psmouse->private;
struct input_dev *dev = psmouse->dev;
struct alps_fields *f = &priv->f;
/* Use st data when we don't have mt data */
if (fingers < 2) {
f->mt[0].x = f->st.x;
f->mt[0].y = f->st.y;
fingers = f->pressure > 0 ? 1 : 0;
priv->second_touch = -1;
}
if (fingers >= 1)
alps_set_slot(dev, 0, f->mt[0].x, f->mt[0].y);
if (fingers >= 2)
alps_set_slot(dev, 1, f->mt[1].x, f->mt[1].y);
input_mt_sync_frame(dev);
input_mt_report_finger_count(dev, fingers);
input_report_key(dev, BTN_LEFT, f->left);
input_report_key(dev, BTN_RIGHT, f->right);
input_report_key(dev, BTN_MIDDLE, f->middle);
input_report_abs(dev, ABS_PRESSURE, f->pressure);
input_sync(dev);
}
static void alps_process_trackstick_packet_v3(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char *packet = psmouse->packet;
struct input_dev *dev = priv->dev2;
int x, y, z, left, right, middle;
/* It should be a DualPoint when received trackstick packet */
if (!(priv->flags & ALPS_DUALPOINT)) {
psmouse_warn(psmouse,
"Rejected trackstick packet from non DualPoint device");
return;
}
/* Sanity check packet */
if (!(packet[0] & 0x40)) {
psmouse_dbg(psmouse, "Bad trackstick packet, discarding\n");
return;
}
/*
* There's a special packet that seems to indicate the end
* of a stream of trackstick data. Filter these out.
*/
if (packet[1] == 0x7f && packet[2] == 0x7f && packet[4] == 0x7f)
return;
x = (s8)(((packet[0] & 0x20) << 2) | (packet[1] & 0x7f));
y = (s8)(((packet[0] & 0x10) << 3) | (packet[2] & 0x7f));
z = packet[4] & 0x7f;
/*
* The x and y values tend to be quite large, and when used
* alone the trackstick is difficult to use. Scale them down
* to compensate.
*/
x /= 8;
y /= 8;
input_report_rel(dev, REL_X, x);
input_report_rel(dev, REL_Y, -y);
input_report_abs(dev, ABS_PRESSURE, z);
/*
* Most ALPS models report the trackstick buttons in the touchpad
* packets, but a few report them here. No reliable way has been
* found to differentiate between the models upfront, so we enable
* the quirk in response to seeing a button press in the trackstick
* packet.
*/
left = packet[3] & 0x01;
right = packet[3] & 0x02;
middle = packet[3] & 0x04;
if (!(priv->quirks & ALPS_QUIRK_TRACKSTICK_BUTTONS) &&
(left || right || middle))
priv->quirks |= ALPS_QUIRK_TRACKSTICK_BUTTONS;
if (priv->quirks & ALPS_QUIRK_TRACKSTICK_BUTTONS) {
input_report_key(dev, BTN_LEFT, left);
input_report_key(dev, BTN_RIGHT, right);
input_report_key(dev, BTN_MIDDLE, middle);
}
input_sync(dev);
return;
}
static void alps_decode_buttons_v3(struct alps_fields *f, unsigned char *p)
{
f->left = !!(p[3] & 0x01);
f->right = !!(p[3] & 0x02);
f->middle = !!(p[3] & 0x04);
f->ts_left = !!(p[3] & 0x10);
f->ts_right = !!(p[3] & 0x20);
f->ts_middle = !!(p[3] & 0x40);
}
static int alps_decode_pinnacle(struct alps_fields *f, unsigned char *p,
struct psmouse *psmouse)
{
f->first_mp = !!(p[4] & 0x40);
f->is_mp = !!(p[0] & 0x40);
if (f->is_mp) {
f->fingers = (p[5] & 0x3) + 1;
f->x_map = ((p[4] & 0x7e) << 8) |
((p[1] & 0x7f) << 2) |
((p[0] & 0x30) >> 4);
f->y_map = ((p[3] & 0x70) << 4) |
((p[2] & 0x7f) << 1) |
(p[4] & 0x01);
} else {
f->st.x = ((p[1] & 0x7f) << 4) | ((p[4] & 0x30) >> 2) |
((p[0] & 0x30) >> 4);
f->st.y = ((p[2] & 0x7f) << 4) | (p[4] & 0x0f);
f->pressure = p[5] & 0x7f;
alps_decode_buttons_v3(f, p);
}
return 0;
}
static int alps_decode_rushmore(struct alps_fields *f, unsigned char *p,
struct psmouse *psmouse)
{
f->first_mp = !!(p[4] & 0x40);
f->is_mp = !!(p[5] & 0x40);
if (f->is_mp) {
f->fingers = max((p[5] & 0x3), ((p[5] >> 2) & 0x3)) + 1;
f->x_map = ((p[5] & 0x10) << 11) |
((p[4] & 0x7e) << 8) |
((p[1] & 0x7f) << 2) |
((p[0] & 0x30) >> 4);
f->y_map = ((p[5] & 0x20) << 6) |
((p[3] & 0x70) << 4) |
((p[2] & 0x7f) << 1) |
(p[4] & 0x01);
} else {
f->st.x = ((p[1] & 0x7f) << 4) | ((p[4] & 0x30) >> 2) |
((p[0] & 0x30) >> 4);
f->st.y = ((p[2] & 0x7f) << 4) | (p[4] & 0x0f);
f->pressure = p[5] & 0x7f;
alps_decode_buttons_v3(f, p);
}
return 0;
}
static int alps_decode_dolphin(struct alps_fields *f, unsigned char *p,
struct psmouse *psmouse)
{
u64 palm_data = 0;
struct alps_data *priv = psmouse->private;
f->first_mp = !!(p[0] & 0x02);
f->is_mp = !!(p[0] & 0x20);
if (!f->is_mp) {
f->st.x = ((p[1] & 0x7f) | ((p[4] & 0x0f) << 7));
f->st.y = ((p[2] & 0x7f) | ((p[4] & 0xf0) << 3));
f->pressure = (p[0] & 4) ? 0 : p[5] & 0x7f;
alps_decode_buttons_v3(f, p);
} else {
f->fingers = ((p[0] & 0x6) >> 1 |
(p[0] & 0x10) >> 2);
palm_data = (p[1] & 0x7f) |
((p[2] & 0x7f) << 7) |
((p[4] & 0x7f) << 14) |
((p[5] & 0x7f) << 21) |
((p[3] & 0x07) << 28) |
(((u64)p[3] & 0x70) << 27) |
(((u64)p[0] & 0x01) << 34);
/* Y-profile is stored in P(0) to p(n-1), n = y_bits; */
f->y_map = palm_data & (BIT(priv->y_bits) - 1);
/* X-profile is stored in p(n) to p(n+m-1), m = x_bits; */
f->x_map = (palm_data >> priv->y_bits) &
(BIT(priv->x_bits) - 1);
}
return 0;
}
static void alps_process_touchpad_packet_v3_v5(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char *packet = psmouse->packet;
struct input_dev *dev2 = priv->dev2;
struct alps_fields *f = &priv->f;
int fingers = 0;
memset(f, 0, sizeof(*f));
priv->decode_fields(f, packet, psmouse);
/*
* There's no single feature of touchpad position and bitmap packets
* that can be used to distinguish between them. We rely on the fact
* that a bitmap packet should always follow a position packet with
* bit 6 of packet[4] set.
*/
if (priv->multi_packet) {
/*
* Sometimes a position packet will indicate a multi-packet
* sequence, but then what follows is another position
* packet. Check for this, and when it happens process the
* position packet as usual.
*/
if (f->is_mp) {
fingers = f->fingers;
/*
* Bitmap processing uses position packet's coordinate
* data, so we need to do decode it first.
*/
priv->decode_fields(f, priv->multi_data, psmouse);
if (alps_process_bitmap(priv, f) == 0)
fingers = 0; /* Use st data */
} else {
priv->multi_packet = 0;
}
}
/*
* Bit 6 of byte 0 is not usually set in position packets. The only
* times it seems to be set is in situations where the data is
* suspect anyway, e.g. a palm resting flat on the touchpad. Given
* this combined with the fact that this bit is useful for filtering
* out misidentified bitmap packets, we reject anything with this
* bit set.
*/
if (f->is_mp)
return;
if (!priv->multi_packet && f->first_mp) {
priv->multi_packet = 1;
memcpy(priv->multi_data, packet, sizeof(priv->multi_data));
return;
}
priv->multi_packet = 0;
/*
* Sometimes the hardware sends a single packet with z = 0
* in the middle of a stream. Real releases generate packets
* with x, y, and z all zero, so these seem to be flukes.
* Ignore them.
*/
if (f->st.x && f->st.y && !f->pressure)
return;
alps_report_semi_mt_data(psmouse, fingers);
if ((priv->flags & ALPS_DUALPOINT) &&
!(priv->quirks & ALPS_QUIRK_TRACKSTICK_BUTTONS)) {
input_report_key(dev2, BTN_LEFT, f->ts_left);
input_report_key(dev2, BTN_RIGHT, f->ts_right);
input_report_key(dev2, BTN_MIDDLE, f->ts_middle);
input_sync(dev2);
}
}
static void alps_process_packet_v3(struct psmouse *psmouse)
{
unsigned char *packet = psmouse->packet;
/*
* v3 protocol packets come in three types, two representing
* touchpad data and one representing trackstick data.
* Trackstick packets seem to be distinguished by always
* having 0x3f in the last byte. This value has never been
* observed in the last byte of either of the other types
* of packets.
*/
if (packet[5] == 0x3f) {
alps_process_trackstick_packet_v3(psmouse);
return;
}
alps_process_touchpad_packet_v3_v5(psmouse);
}
static void alps_process_packet_v6(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char *packet = psmouse->packet;
struct input_dev *dev = psmouse->dev;
struct input_dev *dev2 = priv->dev2;
int x, y, z;
/*
* We can use Byte5 to distinguish if the packet is from Touchpad
* or Trackpoint.
* Touchpad: 0 - 0x7E
* Trackpoint: 0x7F
*/
if (packet[5] == 0x7F) {
/* It should be a DualPoint when received Trackpoint packet */
if (!(priv->flags & ALPS_DUALPOINT)) {
psmouse_warn(psmouse,
"Rejected trackstick packet from non DualPoint device");
return;
}
/* Trackpoint packet */
x = packet[1] | ((packet[3] & 0x20) << 2);
y = packet[2] | ((packet[3] & 0x40) << 1);
z = packet[4];
/* To prevent the cursor jump when finger lifted */
if (x == 0x7F && y == 0x7F && z == 0x7F)
x = y = z = 0;
/* Divide 4 since trackpoint's speed is too fast */
input_report_rel(dev2, REL_X, (s8)x / 4);
input_report_rel(dev2, REL_Y, -((s8)y / 4));
psmouse_report_standard_buttons(dev2, packet[3]);
input_sync(dev2);
return;
}
/* Touchpad packet */
x = packet[1] | ((packet[3] & 0x78) << 4);
y = packet[2] | ((packet[4] & 0x78) << 4);
z = packet[5];
if (z > 30)
input_report_key(dev, BTN_TOUCH, 1);
if (z < 25)
input_report_key(dev, BTN_TOUCH, 0);
if (z > 0) {
input_report_abs(dev, ABS_X, x);
input_report_abs(dev, ABS_Y, y);
}
input_report_abs(dev, ABS_PRESSURE, z);
input_report_key(dev, BTN_TOOL_FINGER, z > 0);
/* v6 touchpad does not have middle button */
packet[3] &= ~BIT(2);
psmouse_report_standard_buttons(dev2, packet[3]);
input_sync(dev);
}
static void alps_process_packet_v4(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char *packet = psmouse->packet;
struct alps_fields *f = &priv->f;
int offset;
/*
* v4 has a 6-byte encoding for bitmap data, but this data is
* broken up between 3 normal packets. Use priv->multi_packet to
* track our position in the bitmap packet.
*/
if (packet[6] & 0x40) {
/* sync, reset position */
priv->multi_packet = 0;
}
if (WARN_ON_ONCE(priv->multi_packet > 2))
return;
offset = 2 * priv->multi_packet;
priv->multi_data[offset] = packet[6];
priv->multi_data[offset + 1] = packet[7];
f->left = !!(packet[4] & 0x01);
f->right = !!(packet[4] & 0x02);
f->st.x = ((packet[1] & 0x7f) << 4) | ((packet[3] & 0x30) >> 2) |
((packet[0] & 0x30) >> 4);
f->st.y = ((packet[2] & 0x7f) << 4) | (packet[3] & 0x0f);
f->pressure = packet[5] & 0x7f;
if (++priv->multi_packet > 2) {
priv->multi_packet = 0;
f->x_map = ((priv->multi_data[2] & 0x1f) << 10) |
((priv->multi_data[3] & 0x60) << 3) |
((priv->multi_data[0] & 0x3f) << 2) |
((priv->multi_data[1] & 0x60) >> 5);
f->y_map = ((priv->multi_data[5] & 0x01) << 10) |
((priv->multi_data[3] & 0x1f) << 5) |
(priv->multi_data[1] & 0x1f);
f->fingers = alps_process_bitmap(priv, f);
}
alps_report_semi_mt_data(psmouse, f->fingers);
}
static bool alps_is_valid_package_v7(struct psmouse *psmouse)
{
switch (psmouse->pktcnt) {
case 3:
return (psmouse->packet[2] & 0x40) == 0x40;
case 4:
return (psmouse->packet[3] & 0x48) == 0x48;
case 6:
return (psmouse->packet[5] & 0x40) == 0x00;
}
return true;
}
static unsigned char alps_get_packet_id_v7(char *byte)
{
unsigned char packet_id;
if (byte[4] & 0x40)
packet_id = V7_PACKET_ID_TWO;
else if (byte[4] & 0x01)
packet_id = V7_PACKET_ID_MULTI;
else if ((byte[0] & 0x10) && !(byte[4] & 0x43))
packet_id = V7_PACKET_ID_NEW;
else if (byte[1] == 0x00 && byte[4] == 0x00)
packet_id = V7_PACKET_ID_IDLE;
else
packet_id = V7_PACKET_ID_UNKNOWN;
return packet_id;
}
static void alps_get_finger_coordinate_v7(struct input_mt_pos *mt,
unsigned char *pkt,
unsigned char pkt_id)
{
mt[0].x = ((pkt[2] & 0x80) << 4);
mt[0].x |= ((pkt[2] & 0x3F) << 5);
mt[0].x |= ((pkt[3] & 0x30) >> 1);
mt[0].x |= (pkt[3] & 0x07);
mt[0].y = (pkt[1] << 3) | (pkt[0] & 0x07);
mt[1].x = ((pkt[3] & 0x80) << 4);
mt[1].x |= ((pkt[4] & 0x80) << 3);
mt[1].x |= ((pkt[4] & 0x3F) << 4);
mt[1].y = ((pkt[5] & 0x80) << 3);
mt[1].y |= ((pkt[5] & 0x3F) << 4);
switch (pkt_id) {
case V7_PACKET_ID_TWO:
mt[1].x &= ~0x000F;
mt[1].y |= 0x000F;
/* Detect false-positive touches where x & y report max value */
if (mt[1].y == 0x7ff && mt[1].x == 0xff0) {
mt[1].x = 0;
/* y gets set to 0 at the end of this function */
}
break;
case V7_PACKET_ID_MULTI:
mt[1].x &= ~0x003F;
mt[1].y &= ~0x0020;
mt[1].y |= ((pkt[4] & 0x02) << 4);
mt[1].y |= 0x001F;
break;
case V7_PACKET_ID_NEW:
mt[1].x &= ~0x003F;
mt[1].x |= (pkt[0] & 0x20);
mt[1].y |= 0x000F;
break;
}
mt[0].y = 0x7FF - mt[0].y;
mt[1].y = 0x7FF - mt[1].y;
}
static int alps_get_mt_count(struct input_mt_pos *mt)
{
int i, fingers = 0;
for (i = 0; i < MAX_TOUCHES; i++) {
if (mt[i].x != 0 || mt[i].y != 0)
fingers++;
}
return fingers;
}
static int alps_decode_packet_v7(struct alps_fields *f,
unsigned char *p,
struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char pkt_id;
pkt_id = alps_get_packet_id_v7(p);
if (pkt_id == V7_PACKET_ID_IDLE)
return 0;
if (pkt_id == V7_PACKET_ID_UNKNOWN)
return -1;
/*
* NEW packets are send to indicate a discontinuity in the finger
* coordinate reporting. Specifically a finger may have moved from
* slot 0 to 1 or vice versa. INPUT_MT_TRACK takes care of this for
* us.
*
* NEW packets have 3 problems:
* 1) They do not contain middle / right button info (on non clickpads)
* this can be worked around by preserving the old button state
* 2) They do not contain an accurate fingercount, and they are
* typically send when the number of fingers changes. We cannot use
* the old finger count as that may mismatch with the amount of
* touch coordinates we've available in the NEW packet
* 3) Their x data for the second touch is inaccurate leading to
* a possible jump of the x coordinate by 16 units when the first
* non NEW packet comes in
* Since problems 2 & 3 cannot be worked around, just ignore them.
*/
if (pkt_id == V7_PACKET_ID_NEW)
return 1;
alps_get_finger_coordinate_v7(f->mt, p, pkt_id);
if (pkt_id == V7_PACKET_ID_TWO)
f->fingers = alps_get_mt_count(f->mt);
else /* pkt_id == V7_PACKET_ID_MULTI */
f->fingers = 3 + (p[5] & 0x03);
f->left = (p[0] & 0x80) >> 7;
if (priv->flags & ALPS_BUTTONPAD) {
if (p[0] & 0x20)
f->fingers++;
if (p[0] & 0x10)
f->fingers++;
} else {
f->right = (p[0] & 0x20) >> 5;
f->middle = (p[0] & 0x10) >> 4;
}
/* Sometimes a single touch is reported in mt[1] rather then mt[0] */
if (f->fingers == 1 && f->mt[0].x == 0 && f->mt[0].y == 0) {
f->mt[0].x = f->mt[1].x;
f->mt[0].y = f->mt[1].y;
f->mt[1].x = 0;
f->mt[1].y = 0;
}
return 0;
}
static void alps_process_trackstick_packet_v7(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char *packet = psmouse->packet;
struct input_dev *dev2 = priv->dev2;
int x, y, z;
/* It should be a DualPoint when received trackstick packet */
if (!(priv->flags & ALPS_DUALPOINT)) {
psmouse_warn(psmouse,
"Rejected trackstick packet from non DualPoint device");
return;
}
x = ((packet[2] & 0xbf)) | ((packet[3] & 0x10) << 2);
y = (packet[3] & 0x07) | (packet[4] & 0xb8) |
((packet[3] & 0x20) << 1);
z = (packet[5] & 0x3f) | ((packet[3] & 0x80) >> 1);
input_report_rel(dev2, REL_X, (s8)x);
input_report_rel(dev2, REL_Y, -((s8)y));
input_report_abs(dev2, ABS_PRESSURE, z);
psmouse_report_standard_buttons(dev2, packet[1]);
input_sync(dev2);
}
static void alps_process_touchpad_packet_v7(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
struct input_dev *dev = psmouse->dev;
struct alps_fields *f = &priv->f;
memset(f, 0, sizeof(*f));
if (priv->decode_fields(f, psmouse->packet, psmouse))
return;
alps_report_mt_data(psmouse, alps_get_mt_count(f->mt));
input_mt_report_finger_count(dev, f->fingers);
input_report_key(dev, BTN_LEFT, f->left);
input_report_key(dev, BTN_RIGHT, f->right);
input_report_key(dev, BTN_MIDDLE, f->middle);
input_sync(dev);
}
static void alps_process_packet_v7(struct psmouse *psmouse)
{
unsigned char *packet = psmouse->packet;
if (packet[0] == 0x48 && (packet[4] & 0x47) == 0x06)
alps_process_trackstick_packet_v7(psmouse);
else
alps_process_touchpad_packet_v7(psmouse);
}
static enum SS4_PACKET_ID alps_get_pkt_id_ss4_v2(unsigned char *byte)
{
enum SS4_PACKET_ID pkt_id = SS4_PACKET_ID_IDLE;
switch (byte[3] & 0x30) {
case 0x00:
if (SS4_IS_IDLE_V2(byte)) {
pkt_id = SS4_PACKET_ID_IDLE;
} else {
pkt_id = SS4_PACKET_ID_ONE;
}
break;
case 0x10:
/* two-finger finger positions */
pkt_id = SS4_PACKET_ID_TWO;
break;
case 0x20:
/* stick pointer */
pkt_id = SS4_PACKET_ID_STICK;
break;
case 0x30:
/* third and fourth finger positions */
pkt_id = SS4_PACKET_ID_MULTI;
break;
}
return pkt_id;
}
static int alps_decode_ss4_v2(struct alps_fields *f,
unsigned char *p, struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
enum SS4_PACKET_ID pkt_id;
unsigned int no_data_x, no_data_y;
pkt_id = alps_get_pkt_id_ss4_v2(p);
/* Current packet is 1Finger coordinate packet */
switch (pkt_id) {
case SS4_PACKET_ID_ONE:
f->mt[0].x = SS4_1F_X_V2(p);
f->mt[0].y = SS4_1F_Y_V2(p);
f->pressure = ((SS4_1F_Z_V2(p)) * 2) & 0x7f;
/*
* When a button is held the device will give us events
* with x, y, and pressure of 0. This causes annoying jumps
* if a touch is released while the button is held.
* Handle this by claiming zero contacts.
*/
f->fingers = f->pressure > 0 ? 1 : 0;
f->first_mp = 0;
f->is_mp = 0;
break;
case SS4_PACKET_ID_TWO:
if (priv->flags & ALPS_BUTTONPAD) {
if (IS_SS4PLUS_DEV(priv->dev_id)) {
f->mt[0].x = SS4_PLUS_BTL_MF_X_V2(p, 0);
f->mt[1].x = SS4_PLUS_BTL_MF_X_V2(p, 1);
} else {
f->mt[0].x = SS4_BTL_MF_X_V2(p, 0);
f->mt[1].x = SS4_BTL_MF_X_V2(p, 1);
}
f->mt[0].y = SS4_BTL_MF_Y_V2(p, 0);
f->mt[1].y = SS4_BTL_MF_Y_V2(p, 1);
} else {
if (IS_SS4PLUS_DEV(priv->dev_id)) {
f->mt[0].x = SS4_PLUS_STD_MF_X_V2(p, 0);
f->mt[1].x = SS4_PLUS_STD_MF_X_V2(p, 1);
} else {
f->mt[0].x = SS4_STD_MF_X_V2(p, 0);
f->mt[1].x = SS4_STD_MF_X_V2(p, 1);
}
f->mt[0].y = SS4_STD_MF_Y_V2(p, 0);
f->mt[1].y = SS4_STD_MF_Y_V2(p, 1);
}
f->pressure = SS4_MF_Z_V2(p, 0) ? 0x30 : 0;
if (SS4_IS_MF_CONTINUE(p)) {
f->first_mp = 1;
} else {
f->fingers = 2;
f->first_mp = 0;
}
f->is_mp = 0;
break;
case SS4_PACKET_ID_MULTI:
if (priv->flags & ALPS_BUTTONPAD) {
if (IS_SS4PLUS_DEV(priv->dev_id)) {
f->mt[2].x = SS4_PLUS_BTL_MF_X_V2(p, 0);
f->mt[3].x = SS4_PLUS_BTL_MF_X_V2(p, 1);
no_data_x = SS4_PLUS_MFPACKET_NO_AX_BL;
} else {
f->mt[2].x = SS4_BTL_MF_X_V2(p, 0);
f->mt[3].x = SS4_BTL_MF_X_V2(p, 1);
no_data_x = SS4_MFPACKET_NO_AX_BL;
}
no_data_y = SS4_MFPACKET_NO_AY_BL;
f->mt[2].y = SS4_BTL_MF_Y_V2(p, 0);
f->mt[3].y = SS4_BTL_MF_Y_V2(p, 1);
} else {
if (IS_SS4PLUS_DEV(priv->dev_id)) {
f->mt[2].x = SS4_PLUS_STD_MF_X_V2(p, 0);
f->mt[3].x = SS4_PLUS_STD_MF_X_V2(p, 1);
no_data_x = SS4_PLUS_MFPACKET_NO_AX;
} else {
f->mt[2].x = SS4_STD_MF_X_V2(p, 0);
f->mt[3].x = SS4_STD_MF_X_V2(p, 1);
no_data_x = SS4_MFPACKET_NO_AX;
}
no_data_y = SS4_MFPACKET_NO_AY;
f->mt[2].y = SS4_STD_MF_Y_V2(p, 0);
f->mt[3].y = SS4_STD_MF_Y_V2(p, 1);
}
f->first_mp = 0;
f->is_mp = 1;
if (SS4_IS_5F_DETECTED(p)) {
f->fingers = 5;
} else if (f->mt[3].x == no_data_x &&
f->mt[3].y == no_data_y) {
f->mt[3].x = 0;
f->mt[3].y = 0;
f->fingers = 3;
} else {
f->fingers = 4;
}
break;
case SS4_PACKET_ID_STICK:
/*
* x, y, and pressure are decoded in
* alps_process_packet_ss4_v2()
*/
f->first_mp = 0;
f->is_mp = 0;
break;
case SS4_PACKET_ID_IDLE:
default:
memset(f, 0, sizeof(struct alps_fields));
break;
}
/* handle buttons */
if (pkt_id == SS4_PACKET_ID_STICK) {
f->ts_left = !!(SS4_BTN_V2(p) & 0x01);
f->ts_right = !!(SS4_BTN_V2(p) & 0x02);
f->ts_middle = !!(SS4_BTN_V2(p) & 0x04);
} else {
f->left = !!(SS4_BTN_V2(p) & 0x01);
if (!(priv->flags & ALPS_BUTTONPAD)) {
f->right = !!(SS4_BTN_V2(p) & 0x02);
f->middle = !!(SS4_BTN_V2(p) & 0x04);
}
}
return 0;
}
static void alps_process_packet_ss4_v2(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char *packet = psmouse->packet;
struct input_dev *dev = psmouse->dev;
struct input_dev *dev2 = priv->dev2;
struct alps_fields *f = &priv->f;
memset(f, 0, sizeof(struct alps_fields));
priv->decode_fields(f, packet, psmouse);
if (priv->multi_packet) {
/*
* Sometimes the first packet will indicate a multi-packet
* sequence, but sometimes the next multi-packet would not
* come. Check for this, and when it happens process the
* position packet as usual.
*/
if (f->is_mp) {
/* Now process the 1st packet */
priv->decode_fields(f, priv->multi_data, psmouse);
} else {
priv->multi_packet = 0;
}
}
/*
* "f.is_mp" would always be '0' after merging the 1st and 2nd packet.
* When it is set, it means 2nd packet comes without 1st packet come.
*/
if (f->is_mp)
return;
/* Save the first packet */
if (!priv->multi_packet && f->first_mp) {
priv->multi_packet = 1;
memcpy(priv->multi_data, packet, sizeof(priv->multi_data));
return;
}
priv->multi_packet = 0;
/* Report trackstick */
if (alps_get_pkt_id_ss4_v2(packet) == SS4_PACKET_ID_STICK) {
if (!(priv->flags & ALPS_DUALPOINT)) {
psmouse_warn(psmouse,
"Rejected trackstick packet from non DualPoint device");
return;
}
input_report_rel(dev2, REL_X, SS4_TS_X_V2(packet));
input_report_rel(dev2, REL_Y, SS4_TS_Y_V2(packet));
input_report_abs(dev2, ABS_PRESSURE, SS4_TS_Z_V2(packet));
input_report_key(dev2, BTN_LEFT, f->ts_left);
input_report_key(dev2, BTN_RIGHT, f->ts_right);
input_report_key(dev2, BTN_MIDDLE, f->ts_middle);
input_sync(dev2);
return;
}
/* Report touchpad */
alps_report_mt_data(psmouse, (f->fingers <= 4) ? f->fingers : 4);
input_mt_report_finger_count(dev, f->fingers);
input_report_key(dev, BTN_LEFT, f->left);
input_report_key(dev, BTN_RIGHT, f->right);
input_report_key(dev, BTN_MIDDLE, f->middle);
input_report_abs(dev, ABS_PRESSURE, f->pressure);
input_sync(dev);
}
static bool alps_is_valid_package_ss4_v2(struct psmouse *psmouse)
{
if (psmouse->pktcnt == 4 && ((psmouse->packet[3] & 0x08) != 0x08))
return false;
if (psmouse->pktcnt == 6 && ((psmouse->packet[5] & 0x10) != 0x0))
return false;
return true;
}
static DEFINE_MUTEX(alps_mutex);
static void alps_register_bare_ps2_mouse(struct work_struct *work)
{
struct alps_data *priv =
container_of(work, struct alps_data, dev3_register_work.work);
struct psmouse *psmouse = priv->psmouse;
struct input_dev *dev3;
int error = 0;
mutex_lock(&alps_mutex);
if (priv->dev3)
goto out;
dev3 = input_allocate_device();
if (!dev3) {
psmouse_err(psmouse, "failed to allocate secondary device\n");
error = -ENOMEM;
goto out;
}
snprintf(priv->phys3, sizeof(priv->phys3), "%s/%s",
psmouse->ps2dev.serio->phys,
(priv->dev2 ? "input2" : "input1"));
dev3->phys = priv->phys3;
/*
* format of input device name is: "protocol vendor name"
* see function psmouse_switch_protocol() in psmouse-base.c
*/
dev3->name = "PS/2 ALPS Mouse";
dev3->id.bustype = BUS_I8042;
dev3->id.vendor = 0x0002;
dev3->id.product = PSMOUSE_PS2;
dev3->id.version = 0x0000;
dev3->dev.parent = &psmouse->ps2dev.serio->dev;
input_set_capability(dev3, EV_REL, REL_X);
input_set_capability(dev3, EV_REL, REL_Y);
input_set_capability(dev3, EV_KEY, BTN_LEFT);
input_set_capability(dev3, EV_KEY, BTN_RIGHT);
input_set_capability(dev3, EV_KEY, BTN_MIDDLE);
__set_bit(INPUT_PROP_POINTER, dev3->propbit);
error = input_register_device(dev3);
if (error) {
psmouse_err(psmouse,
"failed to register secondary device: %d\n",
error);
input_free_device(dev3);
goto out;
}
priv->dev3 = dev3;
out:
/*
* Save the error code so that we can detect that we
* already tried to create the device.
*/
if (error)
priv->dev3 = ERR_PTR(error);
mutex_unlock(&alps_mutex);
}
static void alps_report_bare_ps2_packet(struct psmouse *psmouse,
unsigned char packet[],
bool report_buttons)
{
struct alps_data *priv = psmouse->private;
struct input_dev *dev, *dev2 = NULL;
/* Figure out which device to use to report the bare packet */
if (priv->proto_version == ALPS_PROTO_V2 &&
(priv->flags & ALPS_DUALPOINT)) {
/* On V2 devices the DualPoint Stick reports bare packets */
dev = priv->dev2;
dev2 = psmouse->dev;
} else if (unlikely(IS_ERR_OR_NULL(priv->dev3))) {
/* Register dev3 mouse if we received PS/2 packet first time */
if (!IS_ERR(priv->dev3))
psmouse_queue_work(psmouse, &priv->dev3_register_work,
0);
return;
} else {
dev = priv->dev3;
}
if (report_buttons)
alps_report_buttons(dev, dev2,
packet[0] & 1, packet[0] & 2, packet[0] & 4);
psmouse_report_standard_motion(dev, packet);
input_sync(dev);
}
static psmouse_ret_t alps_handle_interleaved_ps2(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
if (psmouse->pktcnt < 6)
return PSMOUSE_GOOD_DATA;
if (psmouse->pktcnt == 6) {
/*
* Start a timer to flush the packet if it ends up last
* 6-byte packet in the stream. Timer needs to fire
* psmouse core times out itself. 20 ms should be enough
* to decide if we are getting more data or not.
*/
mod_timer(&priv->timer, jiffies + msecs_to_jiffies(20));
return PSMOUSE_GOOD_DATA;
}
del_timer(&priv->timer);
if (psmouse->packet[6] & 0x80) {
/*
* Highest bit is set - that means we either had
* complete ALPS packet and this is start of the
* next packet or we got garbage.
*/
if (((psmouse->packet[3] |
psmouse->packet[4] |
psmouse->packet[5]) & 0x80) ||
(!alps_is_valid_first_byte(priv, psmouse->packet[6]))) {
psmouse_dbg(psmouse,
"refusing packet %4ph (suspected interleaved ps/2)\n",
psmouse->packet + 3);
return PSMOUSE_BAD_DATA;
}
priv->process_packet(psmouse);
/* Continue with the next packet */
psmouse->packet[0] = psmouse->packet[6];
psmouse->pktcnt = 1;
} else {
/*
* High bit is 0 - that means that we indeed got a PS/2
* packet in the middle of ALPS packet.
*
* There is also possibility that we got 6-byte ALPS
* packet followed by 3-byte packet from trackpoint. We
* can not distinguish between these 2 scenarios but
* because the latter is unlikely to happen in course of
* normal operation (user would need to press all
* buttons on the pad and start moving trackpoint
* without touching the pad surface) we assume former.
* Even if we are wrong the wost thing that would happen
* the cursor would jump but we should not get protocol
* de-synchronization.
*/
alps_report_bare_ps2_packet(psmouse, &psmouse->packet[3],
false);
/*
* Continue with the standard ALPS protocol handling,
* but make sure we won't process it as an interleaved
* packet again, which may happen if all buttons are
* pressed. To avoid this let's reset the 4th bit which
* is normally 1.
*/
psmouse->packet[3] = psmouse->packet[6] & 0xf7;
psmouse->pktcnt = 4;
}
return PSMOUSE_GOOD_DATA;
}
static void alps_flush_packet(struct timer_list *t)
{
struct alps_data *priv = from_timer(priv, t, timer);
struct psmouse *psmouse = priv->psmouse;
serio_pause_rx(psmouse->ps2dev.serio);
if (psmouse->pktcnt == psmouse->pktsize) {
/*
* We did not any more data in reasonable amount of time.
* Validate the last 3 bytes and process as a standard
* ALPS packet.
*/
if ((psmouse->packet[3] |
psmouse->packet[4] |
psmouse->packet[5]) & 0x80) {
psmouse_dbg(psmouse,
"refusing packet %3ph (suspected interleaved ps/2)\n",
psmouse->packet + 3);
} else {
priv->process_packet(psmouse);
}
psmouse->pktcnt = 0;
}
serio_continue_rx(psmouse->ps2dev.serio);
}
static psmouse_ret_t alps_process_byte(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
/*
* Check if we are dealing with a bare PS/2 packet, presumably from
* a device connected to the external PS/2 port. Because bare PS/2
* protocol does not have enough constant bits to self-synchronize
* properly we only do this if the device is fully synchronized.
* Can not distinguish V8's first byte from PS/2 packet's
*/
if (priv->proto_version != ALPS_PROTO_V8 &&
!psmouse->out_of_sync_cnt &&
(psmouse->packet[0] & 0xc8) == 0x08) {
if (psmouse->pktcnt == 3) {
alps_report_bare_ps2_packet(psmouse, psmouse->packet,
true);
return PSMOUSE_FULL_PACKET;
}
return PSMOUSE_GOOD_DATA;
}
/* Check for PS/2 packet stuffed in the middle of ALPS packet. */
if ((priv->flags & ALPS_PS2_INTERLEAVED) &&
psmouse->pktcnt >= 4 && (psmouse->packet[3] & 0x0f) == 0x0f) {
return alps_handle_interleaved_ps2(psmouse);
}
if (!alps_is_valid_first_byte(priv, psmouse->packet[0])) {
psmouse_dbg(psmouse,
"refusing packet[0] = %x (mask0 = %x, byte0 = %x)\n",
psmouse->packet[0], priv->mask0, priv->byte0);
return PSMOUSE_BAD_DATA;
}
/* Bytes 2 - pktsize should have 0 in the highest bit */
if (priv->proto_version < ALPS_PROTO_V5 &&
psmouse->pktcnt >= 2 && psmouse->pktcnt <= psmouse->pktsize &&
(psmouse->packet[psmouse->pktcnt - 1] & 0x80)) {
psmouse_dbg(psmouse, "refusing packet[%i] = %x\n",
psmouse->pktcnt - 1,
psmouse->packet[psmouse->pktcnt - 1]);
if (priv->proto_version == ALPS_PROTO_V3_RUSHMORE &&
psmouse->pktcnt == psmouse->pktsize) {
/*
* Some Dell boxes, such as Latitude E6440 or E7440
* with closed lid, quite often smash last byte of
* otherwise valid packet with 0xff. Given that the
* next packet is very likely to be valid let's
* report PSMOUSE_FULL_PACKET but not process data,
* rather than reporting PSMOUSE_BAD_DATA and
* filling the logs.
*/
return PSMOUSE_FULL_PACKET;
}
return PSMOUSE_BAD_DATA;
}
if ((priv->proto_version == ALPS_PROTO_V7 &&
!alps_is_valid_package_v7(psmouse)) ||
(priv->proto_version == ALPS_PROTO_V8 &&
!alps_is_valid_package_ss4_v2(psmouse))) {
psmouse_dbg(psmouse, "refusing packet[%i] = %x\n",
psmouse->pktcnt - 1,
psmouse->packet[psmouse->pktcnt - 1]);
return PSMOUSE_BAD_DATA;
}
if (psmouse->pktcnt == psmouse->pktsize) {
priv->process_packet(psmouse);
return PSMOUSE_FULL_PACKET;
}
return PSMOUSE_GOOD_DATA;
}
static int alps_command_mode_send_nibble(struct psmouse *psmouse, int nibble)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct alps_data *priv = psmouse->private;
int command;
unsigned char *param;
unsigned char dummy[4];
BUG_ON(nibble > 0xf);
command = priv->nibble_commands[nibble].command;
param = (command & 0x0f00) ?
dummy : (unsigned char *)&priv->nibble_commands[nibble].data;
if (ps2_command(ps2dev, param, command))
return -1;
return 0;
}
static int alps_command_mode_set_addr(struct psmouse *psmouse, int addr)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct alps_data *priv = psmouse->private;
int i, nibble;
if (ps2_command(ps2dev, NULL, priv->addr_command))
return -1;
for (i = 12; i >= 0; i -= 4) {
nibble = (addr >> i) & 0xf;
if (alps_command_mode_send_nibble(psmouse, nibble))
return -1;
}
return 0;
}
static int __alps_command_mode_read_reg(struct psmouse *psmouse, int addr)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
if (ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO))
return -1;
/*
* The address being read is returned in the first two bytes
* of the result. Check that this address matches the expected
* address.
*/
if (addr != ((param[0] << 8) | param[1]))
return -1;
return param[2];
}
static int alps_command_mode_read_reg(struct psmouse *psmouse, int addr)
{
if (alps_command_mode_set_addr(psmouse, addr))
return -1;
return __alps_command_mode_read_reg(psmouse, addr);
}
static int __alps_command_mode_write_reg(struct psmouse *psmouse, u8 value)
{
if (alps_command_mode_send_nibble(psmouse, (value >> 4) & 0xf))
return -1;
if (alps_command_mode_send_nibble(psmouse, value & 0xf))
return -1;
return 0;
}
static int alps_command_mode_write_reg(struct psmouse *psmouse, int addr,
u8 value)
{
if (alps_command_mode_set_addr(psmouse, addr))
return -1;
return __alps_command_mode_write_reg(psmouse, value);
}
static int alps_rpt_cmd(struct psmouse *psmouse, int init_command,
int repeated_command, unsigned char *param)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
param[0] = 0;
if (init_command && ps2_command(ps2dev, param, init_command))
return -EIO;
if (ps2_command(ps2dev, NULL, repeated_command) ||
ps2_command(ps2dev, NULL, repeated_command) ||
ps2_command(ps2dev, NULL, repeated_command))
return -EIO;
param[0] = param[1] = param[2] = 0xff;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO))
return -EIO;
psmouse_dbg(psmouse, "%2.2X report: %3ph\n",
repeated_command, param);
return 0;
}
static bool alps_check_valid_firmware_id(unsigned char id[])
{
if (id[0] == 0x73)
return true;
if (id[0] == 0x88 &&
(id[1] == 0x07 ||
id[1] == 0x08 ||
(id[1] & 0xf0) == 0xb0 ||
(id[1] & 0xf0) == 0xc0)) {
return true;
}
return false;
}
static int alps_enter_command_mode(struct psmouse *psmouse)
{
unsigned char param[4];
if (alps_rpt_cmd(psmouse, 0, PSMOUSE_CMD_RESET_WRAP, param)) {
psmouse_err(psmouse, "failed to enter command mode\n");
return -1;
}
if (!alps_check_valid_firmware_id(param)) {
psmouse_dbg(psmouse,
"unknown response while entering command mode\n");
return -1;
}
return 0;
}
static inline int alps_exit_command_mode(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSTREAM))
return -1;
return 0;
}
/*
* For DualPoint devices select the device that should respond to
* subsequent commands. It looks like glidepad is behind stickpointer,
* I'd thought it would be other way around...
*/
static int alps_passthrough_mode_v2(struct psmouse *psmouse, bool enable)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
int cmd = enable ? PSMOUSE_CMD_SETSCALE21 : PSMOUSE_CMD_SETSCALE11;
if (ps2_command(ps2dev, NULL, cmd) ||
ps2_command(ps2dev, NULL, cmd) ||
ps2_command(ps2dev, NULL, cmd) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE))
return -1;
/* we may get 3 more bytes, just ignore them */
ps2_drain(ps2dev, 3, 100);
return 0;
}
static int alps_absolute_mode_v1_v2(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
/* Try ALPS magic knock - 4 disable before enable */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE))
return -1;
/*
* Switch mouse to poll (remote) mode so motion data will not
* get in our way
*/
return ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETPOLL);
}
static int alps_monitor_mode_send_word(struct psmouse *psmouse, u16 word)
{
int i, nibble;
/*
* b0-b11 are valid bits, send sequence is inverse.
* e.g. when word = 0x0123, nibble send sequence is 3, 2, 1
*/
for (i = 0; i <= 8; i += 4) {
nibble = (word >> i) & 0xf;
if (alps_command_mode_send_nibble(psmouse, nibble))
return -1;
}
return 0;
}
static int alps_monitor_mode_write_reg(struct psmouse *psmouse,
u16 addr, u16 value)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
/* 0x0A0 is the command to write the word */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE) ||
alps_monitor_mode_send_word(psmouse, 0x0A0) ||
alps_monitor_mode_send_word(psmouse, addr) ||
alps_monitor_mode_send_word(psmouse, value) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE))
return -1;
return 0;
}
static int alps_monitor_mode(struct psmouse *psmouse, bool enable)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
if (enable) {
/* EC E9 F5 F5 E7 E6 E7 E9 to enter monitor mode */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_RESET_WRAP) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_GETINFO) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_GETINFO))
return -1;
} else {
/* EC to exit monitor mode */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_RESET_WRAP))
return -1;
}
return 0;
}
static int alps_absolute_mode_v6(struct psmouse *psmouse)
{
u16 reg_val = 0x181;
int ret;
/* enter monitor mode, to write the register */
if (alps_monitor_mode(psmouse, true))
return -1;
ret = alps_monitor_mode_write_reg(psmouse, 0x000, reg_val);
if (alps_monitor_mode(psmouse, false))
ret = -1;
return ret;
}
static int alps_get_status(struct psmouse *psmouse, char *param)
{
/* Get status: 0xF5 0xF5 0xF5 0xE9 */
if (alps_rpt_cmd(psmouse, 0, PSMOUSE_CMD_DISABLE, param))
return -1;
return 0;
}
/*
* Turn touchpad tapping on or off. The sequences are:
* 0xE9 0xF5 0xF5 0xF3 0x0A to enable,
* 0xE9 0xF5 0xF5 0xE8 0x00 to disable.
* My guess that 0xE9 (GetInfo) is here as a sync point.
* For models that also have stickpointer (DualPoints) its tapping
* is controlled separately (0xE6 0xE6 0xE6 0xF3 0x14|0x0A) but
* we don't fiddle with it.
*/
static int alps_tap_mode(struct psmouse *psmouse, int enable)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
int cmd = enable ? PSMOUSE_CMD_SETRATE : PSMOUSE_CMD_SETRES;
unsigned char tap_arg = enable ? 0x0A : 0x00;
unsigned char param[4];
if (ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, &tap_arg, cmd))
return -1;
if (alps_get_status(psmouse, param))
return -1;
return 0;
}
/*
* alps_poll() - poll the touchpad for current motion packet.
* Used in resync.
*/
static int alps_poll(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
unsigned char buf[sizeof(psmouse->packet)];
bool poll_failed;
if (priv->flags & ALPS_PASS)
alps_passthrough_mode_v2(psmouse, true);
poll_failed = ps2_command(&psmouse->ps2dev, buf,
PSMOUSE_CMD_POLL | (psmouse->pktsize << 8)) < 0;
if (priv->flags & ALPS_PASS)
alps_passthrough_mode_v2(psmouse, false);
if (poll_failed || (buf[0] & priv->mask0) != priv->byte0)
return -1;
if ((psmouse->badbyte & 0xc8) == 0x08) {
/*
* Poll the track stick ...
*/
if (ps2_command(&psmouse->ps2dev, buf, PSMOUSE_CMD_POLL | (3 << 8)))
return -1;
}
memcpy(psmouse->packet, buf, sizeof(buf));
return 0;
}
static int alps_hw_init_v1_v2(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
if ((priv->flags & ALPS_PASS) &&
alps_passthrough_mode_v2(psmouse, true)) {
return -1;
}
if (alps_tap_mode(psmouse, true)) {
psmouse_warn(psmouse, "Failed to enable hardware tapping\n");
return -1;
}
if (alps_absolute_mode_v1_v2(psmouse)) {
psmouse_err(psmouse, "Failed to enable absolute mode\n");
return -1;
}
if ((priv->flags & ALPS_PASS) &&
alps_passthrough_mode_v2(psmouse, false)) {
return -1;
}
/* ALPS needs stream mode, otherwise it won't report any data */
if (ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_SETSTREAM)) {
psmouse_err(psmouse, "Failed to enable stream mode\n");
return -1;
}
return 0;
}
/* Must be in passthrough mode when calling this function */
static int alps_trackstick_enter_extended_mode_v3_v6(struct psmouse *psmouse)
{
unsigned char param[2] = {0xC8, 0x14};
if (ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_SETSCALE11) ||
ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_SETSCALE11) ||
ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_SETSCALE11) ||
ps2_command(&psmouse->ps2dev, ¶m[0], PSMOUSE_CMD_SETRATE) ||
ps2_command(&psmouse->ps2dev, ¶m[1], PSMOUSE_CMD_SETRATE))
return -1;
return 0;
}
static int alps_hw_init_v6(struct psmouse *psmouse)
{
int ret;
/* Enter passthrough mode to let trackpoint enter 6byte raw mode */
if (alps_passthrough_mode_v2(psmouse, true))
return -1;
ret = alps_trackstick_enter_extended_mode_v3_v6(psmouse);
if (alps_passthrough_mode_v2(psmouse, false))
return -1;
if (ret)
return ret;
if (alps_absolute_mode_v6(psmouse)) {
psmouse_err(psmouse, "Failed to enable absolute mode\n");
return -1;
}
return 0;
}
/*
* Enable or disable passthrough mode to the trackstick.
*/
static int alps_passthrough_mode_v3(struct psmouse *psmouse,
int reg_base, bool enable)
{
int reg_val, ret = -1;
if (alps_enter_command_mode(psmouse))
return -1;
reg_val = alps_command_mode_read_reg(psmouse, reg_base + 0x0008);
if (reg_val == -1)
goto error;
if (enable)
reg_val |= 0x01;
else
reg_val &= ~0x01;
ret = __alps_command_mode_write_reg(psmouse, reg_val);
error:
if (alps_exit_command_mode(psmouse))
ret = -1;
return ret;
}
/* Must be in command mode when calling this function */
static int alps_absolute_mode_v3(struct psmouse *psmouse)
{
int reg_val;
reg_val = alps_command_mode_read_reg(psmouse, 0x0004);
if (reg_val == -1)
return -1;
reg_val |= 0x06;
if (__alps_command_mode_write_reg(psmouse, reg_val))
return -1;
return 0;
}
static int alps_probe_trackstick_v3_v7(struct psmouse *psmouse, int reg_base)
{
int ret = -EIO, reg_val;
if (alps_enter_command_mode(psmouse))
goto error;
reg_val = alps_command_mode_read_reg(psmouse, reg_base + 0x08);
if (reg_val == -1)
goto error;
/* bit 7: trackstick is present */
ret = reg_val & 0x80 ? 0 : -ENODEV;
error:
alps_exit_command_mode(psmouse);
return ret;
}
static int alps_setup_trackstick_v3(struct psmouse *psmouse, int reg_base)
{
int ret = 0;
int reg_val;
unsigned char param[4];
/*
* We need to configure trackstick to report data for touchpad in
* extended format. And also we need to tell touchpad to expect data
* from trackstick in extended format. Without this configuration
* trackstick packets sent from touchpad are in basic format which is
* different from what we expect.
*/
if (alps_passthrough_mode_v3(psmouse, reg_base, true))
return -EIO;
/*
* E7 report for the trackstick
*
* There have been reports of failures to seem to trace back
* to the above trackstick check failing. When these occur
* this E7 report fails, so when that happens we continue
* with the assumption that there isn't a trackstick after
* all.
*/
if (alps_rpt_cmd(psmouse, 0, PSMOUSE_CMD_SETSCALE21, param)) {
psmouse_warn(psmouse, "Failed to initialize trackstick (E7 report failed)\n");
ret = -ENODEV;
} else {
psmouse_dbg(psmouse, "trackstick E7 report: %3ph\n", param);
if (alps_trackstick_enter_extended_mode_v3_v6(psmouse)) {
psmouse_err(psmouse, "Failed to enter into trackstick extended mode\n");
ret = -EIO;
}
}
if (alps_passthrough_mode_v3(psmouse, reg_base, false))
return -EIO;
if (ret)
return ret;
if (alps_enter_command_mode(psmouse))
return -EIO;
reg_val = alps_command_mode_read_reg(psmouse, reg_base + 0x08);
if (reg_val == -1) {
ret = -EIO;
} else {
/*
* Tell touchpad that trackstick is now in extended mode.
* If bit 1 isn't set the packet format is different.
*/
reg_val |= BIT(1);
if (__alps_command_mode_write_reg(psmouse, reg_val))
ret = -EIO;
}
if (alps_exit_command_mode(psmouse))
return -EIO;
return ret;
}
static int alps_hw_init_v3(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
struct ps2dev *ps2dev = &psmouse->ps2dev;
int reg_val;
unsigned char param[4];
if ((priv->flags & ALPS_DUALPOINT) &&
alps_setup_trackstick_v3(psmouse, ALPS_REG_BASE_PINNACLE) == -EIO)
goto error;
if (alps_enter_command_mode(psmouse) ||
alps_absolute_mode_v3(psmouse)) {
psmouse_err(psmouse, "Failed to enter absolute mode\n");
goto error;
}
reg_val = alps_command_mode_read_reg(psmouse, 0x0006);
if (reg_val == -1)
goto error;
if (__alps_command_mode_write_reg(psmouse, reg_val | 0x01))
goto error;
reg_val = alps_command_mode_read_reg(psmouse, 0x0007);
if (reg_val == -1)
goto error;
if (__alps_command_mode_write_reg(psmouse, reg_val | 0x01))
goto error;
if (alps_command_mode_read_reg(psmouse, 0x0144) == -1)
goto error;
if (__alps_command_mode_write_reg(psmouse, 0x04))
goto error;
if (alps_command_mode_read_reg(psmouse, 0x0159) == -1)
goto error;
if (__alps_command_mode_write_reg(psmouse, 0x03))
goto error;
if (alps_command_mode_read_reg(psmouse, 0x0163) == -1)
goto error;
if (alps_command_mode_write_reg(psmouse, 0x0163, 0x03))
goto error;
if (alps_command_mode_read_reg(psmouse, 0x0162) == -1)
goto error;
if (alps_command_mode_write_reg(psmouse, 0x0162, 0x04))
goto error;
alps_exit_command_mode(psmouse);
/* Set rate and enable data reporting */
param[0] = 0x64;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE)) {
psmouse_err(psmouse, "Failed to enable data reporting\n");
return -1;
}
return 0;
error:
/*
* Leaving the touchpad in command mode will essentially render
* it unusable until the machine reboots, so exit it here just
* to be safe
*/
alps_exit_command_mode(psmouse);
return -1;
}
static int alps_get_v3_v7_resolution(struct psmouse *psmouse, int reg_pitch)
{
int reg, x_pitch, y_pitch, x_electrode, y_electrode, x_phys, y_phys;
struct alps_data *priv = psmouse->private;
reg = alps_command_mode_read_reg(psmouse, reg_pitch);
if (reg < 0)
return reg;
x_pitch = (s8)(reg << 4) >> 4; /* sign extend lower 4 bits */
x_pitch = 50 + 2 * x_pitch; /* In 0.1 mm units */
y_pitch = (s8)reg >> 4; /* sign extend upper 4 bits */
y_pitch = 36 + 2 * y_pitch; /* In 0.1 mm units */
reg = alps_command_mode_read_reg(psmouse, reg_pitch + 1);
if (reg < 0)
return reg;
x_electrode = (s8)(reg << 4) >> 4; /* sign extend lower 4 bits */
x_electrode = 17 + x_electrode;
y_electrode = (s8)reg >> 4; /* sign extend upper 4 bits */
y_electrode = 13 + y_electrode;
x_phys = x_pitch * (x_electrode - 1); /* In 0.1 mm units */
y_phys = y_pitch * (y_electrode - 1); /* In 0.1 mm units */
priv->x_res = priv->x_max * 10 / x_phys; /* units / mm */
priv->y_res = priv->y_max * 10 / y_phys; /* units / mm */
psmouse_dbg(psmouse,
"pitch %dx%d num-electrodes %dx%d physical size %dx%d mm res %dx%d\n",
x_pitch, y_pitch, x_electrode, y_electrode,
x_phys / 10, y_phys / 10, priv->x_res, priv->y_res);
return 0;
}
static int alps_hw_init_rushmore_v3(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
struct ps2dev *ps2dev = &psmouse->ps2dev;
int reg_val, ret = -1;
if (priv->flags & ALPS_DUALPOINT) {
reg_val = alps_setup_trackstick_v3(psmouse,
ALPS_REG_BASE_RUSHMORE);
if (reg_val == -EIO)
goto error;
}
if (alps_enter_command_mode(psmouse) ||
alps_command_mode_read_reg(psmouse, 0xc2d9) == -1 ||
alps_command_mode_write_reg(psmouse, 0xc2cb, 0x00))
goto error;
if (alps_get_v3_v7_resolution(psmouse, 0xc2da))
goto error;
reg_val = alps_command_mode_read_reg(psmouse, 0xc2c6);
if (reg_val == -1)
goto error;
if (__alps_command_mode_write_reg(psmouse, reg_val & 0xfd))
goto error;
if (alps_command_mode_write_reg(psmouse, 0xc2c9, 0x64))
goto error;
/* enter absolute mode */
reg_val = alps_command_mode_read_reg(psmouse, 0xc2c4);
if (reg_val == -1)
goto error;
if (__alps_command_mode_write_reg(psmouse, reg_val | 0x02))
goto error;
alps_exit_command_mode(psmouse);
return ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE);
error:
alps_exit_command_mode(psmouse);
return ret;
}
/* Must be in command mode when calling this function */
static int alps_absolute_mode_v4(struct psmouse *psmouse)
{
int reg_val;
reg_val = alps_command_mode_read_reg(psmouse, 0x0004);
if (reg_val == -1)
return -1;
reg_val |= 0x02;
if (__alps_command_mode_write_reg(psmouse, reg_val))
return -1;
return 0;
}
static int alps_hw_init_v4(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
if (alps_enter_command_mode(psmouse))
goto error;
if (alps_absolute_mode_v4(psmouse)) {
psmouse_err(psmouse, "Failed to enter absolute mode\n");
goto error;
}
if (alps_command_mode_write_reg(psmouse, 0x0007, 0x8c))
goto error;
if (alps_command_mode_write_reg(psmouse, 0x0149, 0x03))
goto error;
if (alps_command_mode_write_reg(psmouse, 0x0160, 0x03))
goto error;
if (alps_command_mode_write_reg(psmouse, 0x017f, 0x15))
goto error;
if (alps_command_mode_write_reg(psmouse, 0x0151, 0x01))
goto error;
if (alps_command_mode_write_reg(psmouse, 0x0168, 0x03))
goto error;
if (alps_command_mode_write_reg(psmouse, 0x014a, 0x03))
goto error;
if (alps_command_mode_write_reg(psmouse, 0x0161, 0x03))
goto error;
alps_exit_command_mode(psmouse);
/*
* This sequence changes the output from a 9-byte to an
* 8-byte format. All the same data seems to be present,
* just in a more compact format.
*/
param[0] = 0xc8;
param[1] = 0x64;
param[2] = 0x50;
if (ps2_command(ps2dev, ¶m[0], PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, ¶m[1], PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, ¶m[2], PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, param, PSMOUSE_CMD_GETID))
return -1;
/* Set rate and enable data reporting */
param[0] = 0x64;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE)) {
psmouse_err(psmouse, "Failed to enable data reporting\n");
return -1;
}
return 0;
error:
/*
* Leaving the touchpad in command mode will essentially render
* it unusable until the machine reboots, so exit it here just
* to be safe
*/
alps_exit_command_mode(psmouse);
return -1;
}
static int alps_get_otp_values_ss4_v2(struct psmouse *psmouse,
unsigned char index, unsigned char otp[])
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
switch (index) {
case 0:
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSTREAM) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSTREAM) ||
ps2_command(ps2dev, otp, PSMOUSE_CMD_GETINFO))
return -1;
break;
case 1:
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETPOLL) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETPOLL) ||
ps2_command(ps2dev, otp, PSMOUSE_CMD_GETINFO))
return -1;
break;
}
return 0;
}
static int alps_update_device_area_ss4_v2(unsigned char otp[][4],
struct alps_data *priv)
{
int num_x_electrode;
int num_y_electrode;
int x_pitch, y_pitch, x_phys, y_phys;
if (IS_SS4PLUS_DEV(priv->dev_id)) {
num_x_electrode =
SS4PLUS_NUMSENSOR_XOFFSET + (otp[0][2] & 0x0F);
num_y_electrode =
SS4PLUS_NUMSENSOR_YOFFSET + ((otp[0][2] >> 4) & 0x0F);
priv->x_max =
(num_x_electrode - 1) * SS4PLUS_COUNT_PER_ELECTRODE;
priv->y_max =
(num_y_electrode - 1) * SS4PLUS_COUNT_PER_ELECTRODE;
x_pitch = (otp[0][1] & 0x0F) + SS4PLUS_MIN_PITCH_MM;
y_pitch = ((otp[0][1] >> 4) & 0x0F) + SS4PLUS_MIN_PITCH_MM;
} else {
num_x_electrode =
SS4_NUMSENSOR_XOFFSET + (otp[1][0] & 0x0F);
num_y_electrode =
SS4_NUMSENSOR_YOFFSET + ((otp[1][0] >> 4) & 0x0F);
priv->x_max =
(num_x_electrode - 1) * SS4_COUNT_PER_ELECTRODE;
priv->y_max =
(num_y_electrode - 1) * SS4_COUNT_PER_ELECTRODE;
x_pitch = ((otp[1][2] >> 2) & 0x07) + SS4_MIN_PITCH_MM;
y_pitch = ((otp[1][2] >> 5) & 0x07) + SS4_MIN_PITCH_MM;
}
x_phys = x_pitch * (num_x_electrode - 1); /* In 0.1 mm units */
y_phys = y_pitch * (num_y_electrode - 1); /* In 0.1 mm units */
priv->x_res = priv->x_max * 10 / x_phys; /* units / mm */
priv->y_res = priv->y_max * 10 / y_phys; /* units / mm */
return 0;
}
static int alps_update_btn_info_ss4_v2(unsigned char otp[][4],
struct alps_data *priv)
{
unsigned char is_btnless;
if (IS_SS4PLUS_DEV(priv->dev_id))
is_btnless = (otp[1][0] >> 1) & 0x01;
else
is_btnless = (otp[1][1] >> 3) & 0x01;
if (is_btnless)
priv->flags |= ALPS_BUTTONPAD;
return 0;
}
static int alps_update_dual_info_ss4_v2(unsigned char otp[][4],
struct alps_data *priv,
struct psmouse *psmouse)
{
bool is_dual = false;
int reg_val = 0;
struct ps2dev *ps2dev = &psmouse->ps2dev;
if (IS_SS4PLUS_DEV(priv->dev_id)) {
is_dual = (otp[0][0] >> 4) & 0x01;
if (!is_dual) {
/* For support TrackStick of Thinkpad L/E series */
if (alps_exit_command_mode(psmouse) == 0 &&
alps_enter_command_mode(psmouse) == 0) {
reg_val = alps_command_mode_read_reg(psmouse,
0xD7);
}
alps_exit_command_mode(psmouse);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE);
if (reg_val == 0x0C || reg_val == 0x1D)
is_dual = true;
}
}
if (is_dual)
priv->flags |= ALPS_DUALPOINT |
ALPS_DUALPOINT_WITH_PRESSURE;
return 0;
}
static int alps_set_defaults_ss4_v2(struct psmouse *psmouse,
struct alps_data *priv)
{
unsigned char otp[2][4];
memset(otp, 0, sizeof(otp));
if (alps_get_otp_values_ss4_v2(psmouse, 1, &otp[1][0]) ||
alps_get_otp_values_ss4_v2(psmouse, 0, &otp[0][0]))
return -1;
alps_update_device_area_ss4_v2(otp, priv);
alps_update_btn_info_ss4_v2(otp, priv);
alps_update_dual_info_ss4_v2(otp, priv, psmouse);
return 0;
}
static int alps_dolphin_get_device_area(struct psmouse *psmouse,
struct alps_data *priv)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4] = {0};
int num_x_electrode, num_y_electrode;
if (alps_enter_command_mode(psmouse))
return -1;
param[0] = 0x0a;
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_RESET_WRAP) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETPOLL) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETPOLL) ||
ps2_command(ps2dev, ¶m[0], PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, ¶m[0], PSMOUSE_CMD_SETRATE))
return -1;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO))
return -1;
/*
* Dolphin's sensor line number is not fixed. It can be calculated
* by adding the device's register value with DOLPHIN_PROFILE_X/YOFFSET.
* Further more, we can get device's x_max and y_max by multiplying
* sensor line number with DOLPHIN_COUNT_PER_ELECTRODE.
*
* e.g. When we get register's sensor_x = 11 & sensor_y = 8,
* real sensor line number X = 11 + 8 = 19, and
* real sensor line number Y = 8 + 1 = 9.
* So, x_max = (19 - 1) * 64 = 1152, and
* y_max = (9 - 1) * 64 = 512.
*/
num_x_electrode = DOLPHIN_PROFILE_XOFFSET + (param[2] & 0x0F);
num_y_electrode = DOLPHIN_PROFILE_YOFFSET + ((param[2] >> 4) & 0x0F);
priv->x_bits = num_x_electrode;
priv->y_bits = num_y_electrode;
priv->x_max = (num_x_electrode - 1) * DOLPHIN_COUNT_PER_ELECTRODE;
priv->y_max = (num_y_electrode - 1) * DOLPHIN_COUNT_PER_ELECTRODE;
if (alps_exit_command_mode(psmouse))
return -1;
return 0;
}
static int alps_hw_init_dolphin_v1(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[2];
/* This is dolphin "v1" as empirically defined by florin9doi */
param[0] = 0x64;
param[1] = 0x28;
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSTREAM) ||
ps2_command(ps2dev, ¶m[0], PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, ¶m[1], PSMOUSE_CMD_SETRATE))
return -1;
return 0;
}
static int alps_hw_init_v7(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
int reg_val, ret = -1;
if (alps_enter_command_mode(psmouse) ||
alps_command_mode_read_reg(psmouse, 0xc2d9) == -1)
goto error;
if (alps_get_v3_v7_resolution(psmouse, 0xc397))
goto error;
if (alps_command_mode_write_reg(psmouse, 0xc2c9, 0x64))
goto error;
reg_val = alps_command_mode_read_reg(psmouse, 0xc2c4);
if (reg_val == -1)
goto error;
if (__alps_command_mode_write_reg(psmouse, reg_val | 0x02))
goto error;
alps_exit_command_mode(psmouse);
return ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE);
error:
alps_exit_command_mode(psmouse);
return ret;
}
static int alps_hw_init_ss4_v2(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
char param[2] = {0x64, 0x28};
int ret = -1;
/* enter absolute mode */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSTREAM) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSTREAM) ||
ps2_command(ps2dev, ¶m[0], PSMOUSE_CMD_SETRATE) ||
ps2_command(ps2dev, ¶m[1], PSMOUSE_CMD_SETRATE)) {
goto error;
}
/* T.B.D. Decread noise packet number, delete in the future */
if (alps_exit_command_mode(psmouse) ||
alps_enter_command_mode(psmouse) ||
alps_command_mode_write_reg(psmouse, 0x001D, 0x20)) {
goto error;
}
alps_exit_command_mode(psmouse);
return ps2_command(ps2dev, NULL, PSMOUSE_CMD_ENABLE);
error:
alps_exit_command_mode(psmouse);
return ret;
}
static int alps_set_protocol(struct psmouse *psmouse,
struct alps_data *priv,
const struct alps_protocol_info *protocol)
{
psmouse->private = priv;
timer_setup(&priv->timer, alps_flush_packet, 0);
priv->proto_version = protocol->version;
priv->byte0 = protocol->byte0;
priv->mask0 = protocol->mask0;
priv->flags = protocol->flags;
priv->x_max = 2000;
priv->y_max = 1400;
priv->x_bits = 15;
priv->y_bits = 11;
switch (priv->proto_version) {
case ALPS_PROTO_V1:
case ALPS_PROTO_V2:
priv->hw_init = alps_hw_init_v1_v2;
priv->process_packet = alps_process_packet_v1_v2;
priv->set_abs_params = alps_set_abs_params_st;
priv->x_max = 1023;
priv->y_max = 767;
if (dmi_check_system(alps_dmi_has_separate_stick_buttons))
priv->flags |= ALPS_STICK_BITS;
break;
case ALPS_PROTO_V3:
priv->hw_init = alps_hw_init_v3;
priv->process_packet = alps_process_packet_v3;
priv->set_abs_params = alps_set_abs_params_semi_mt;
priv->decode_fields = alps_decode_pinnacle;
priv->nibble_commands = alps_v3_nibble_commands;
priv->addr_command = PSMOUSE_CMD_RESET_WRAP;
if (alps_probe_trackstick_v3_v7(psmouse,
ALPS_REG_BASE_PINNACLE) < 0)
priv->flags &= ~ALPS_DUALPOINT;
break;
case ALPS_PROTO_V3_RUSHMORE:
priv->hw_init = alps_hw_init_rushmore_v3;
priv->process_packet = alps_process_packet_v3;
priv->set_abs_params = alps_set_abs_params_semi_mt;
priv->decode_fields = alps_decode_rushmore;
priv->nibble_commands = alps_v3_nibble_commands;
priv->addr_command = PSMOUSE_CMD_RESET_WRAP;
priv->x_bits = 16;
priv->y_bits = 12;
if (alps_probe_trackstick_v3_v7(psmouse,
ALPS_REG_BASE_RUSHMORE) < 0)
priv->flags &= ~ALPS_DUALPOINT;
break;
case ALPS_PROTO_V4:
priv->hw_init = alps_hw_init_v4;
priv->process_packet = alps_process_packet_v4;
priv->set_abs_params = alps_set_abs_params_semi_mt;
priv->nibble_commands = alps_v4_nibble_commands;
priv->addr_command = PSMOUSE_CMD_DISABLE;
break;
case ALPS_PROTO_V5:
priv->hw_init = alps_hw_init_dolphin_v1;
priv->process_packet = alps_process_touchpad_packet_v3_v5;
priv->decode_fields = alps_decode_dolphin;
priv->set_abs_params = alps_set_abs_params_semi_mt;
priv->nibble_commands = alps_v3_nibble_commands;
priv->addr_command = PSMOUSE_CMD_RESET_WRAP;
priv->x_bits = 23;
priv->y_bits = 12;
if (alps_dolphin_get_device_area(psmouse, priv))
return -EIO;
break;
case ALPS_PROTO_V6:
priv->hw_init = alps_hw_init_v6;
priv->process_packet = alps_process_packet_v6;
priv->set_abs_params = alps_set_abs_params_st;
priv->nibble_commands = alps_v6_nibble_commands;
priv->x_max = 2047;
priv->y_max = 1535;
break;
case ALPS_PROTO_V7:
priv->hw_init = alps_hw_init_v7;
priv->process_packet = alps_process_packet_v7;
priv->decode_fields = alps_decode_packet_v7;
priv->set_abs_params = alps_set_abs_params_v7;
priv->nibble_commands = alps_v3_nibble_commands;
priv->addr_command = PSMOUSE_CMD_RESET_WRAP;
priv->x_max = 0xfff;
priv->y_max = 0x7ff;
if (priv->fw_ver[1] != 0xba)
priv->flags |= ALPS_BUTTONPAD;
if (alps_probe_trackstick_v3_v7(psmouse, ALPS_REG_BASE_V7) < 0)
priv->flags &= ~ALPS_DUALPOINT;
break;
case ALPS_PROTO_V8:
priv->hw_init = alps_hw_init_ss4_v2;
priv->process_packet = alps_process_packet_ss4_v2;
priv->decode_fields = alps_decode_ss4_v2;
priv->set_abs_params = alps_set_abs_params_ss4_v2;
priv->nibble_commands = alps_v3_nibble_commands;
priv->addr_command = PSMOUSE_CMD_RESET_WRAP;
if (alps_set_defaults_ss4_v2(psmouse, priv))
return -EIO;
break;
}
return 0;
}
static const struct alps_protocol_info *alps_match_table(unsigned char *e7,
unsigned char *ec)
{
const struct alps_model_info *model;
int i;
for (i = 0; i < ARRAY_SIZE(alps_model_data); i++) {
model = &alps_model_data[i];
if (!memcmp(e7, model->signature, sizeof(model->signature)))
return &model->protocol_info;
}
return NULL;
}
static bool alps_is_cs19_trackpoint(struct psmouse *psmouse)
{
u8 param[2] = { 0 };
if (ps2_command(&psmouse->ps2dev,
param, MAKE_PS2_CMD(0, 2, TP_READ_ID)))
return false;
/*
* param[0] contains the trackpoint device variant_id while
* param[1] contains the firmware_id. So far all alps
* trackpoint-only devices have their variant_ids equal
* TP_VARIANT_ALPS and their firmware_ids are in 0x20~0x2f range.
*/
return param[0] == TP_VARIANT_ALPS && ((param[1] & 0xf0) == 0x20);
}
static int alps_identify(struct psmouse *psmouse, struct alps_data *priv)
{
const struct alps_protocol_info *protocol;
unsigned char e6[4], e7[4], ec[4];
int error;
/*
* First try "E6 report".
* ALPS should return 0,0,10 or 0,0,100 if no buttons are pressed.
* The bits 0-2 of the first byte will be 1s if some buttons are
* pressed.
*/
if (alps_rpt_cmd(psmouse, PSMOUSE_CMD_SETRES,
PSMOUSE_CMD_SETSCALE11, e6))
return -EIO;
if ((e6[0] & 0xf8) != 0 || e6[1] != 0 || (e6[2] != 10 && e6[2] != 100))
return -EINVAL;
/*
* Now get the "E7" and "EC" reports. These will uniquely identify
* most ALPS touchpads.
*/
if (alps_rpt_cmd(psmouse, PSMOUSE_CMD_SETRES,
PSMOUSE_CMD_SETSCALE21, e7) ||
alps_rpt_cmd(psmouse, PSMOUSE_CMD_SETRES,
PSMOUSE_CMD_RESET_WRAP, ec) ||
alps_exit_command_mode(psmouse))
return -EIO;
protocol = alps_match_table(e7, ec);
if (!protocol) {
if (e7[0] == 0x73 && e7[1] == 0x02 && e7[2] == 0x64 &&
ec[2] == 0x8a) {
protocol = &alps_v4_protocol_data;
} else if (e7[0] == 0x73 && e7[1] == 0x03 && e7[2] == 0x50 &&
ec[0] == 0x73 && (ec[1] == 0x01 || ec[1] == 0x02)) {
protocol = &alps_v5_protocol_data;
} else if (ec[0] == 0x88 &&
((ec[1] & 0xf0) == 0xb0 || (ec[1] & 0xf0) == 0xc0)) {
protocol = &alps_v7_protocol_data;
} else if (ec[0] == 0x88 && ec[1] == 0x08) {
protocol = &alps_v3_rushmore_data;
} else if (ec[0] == 0x88 && ec[1] == 0x07 &&
ec[2] >= 0x90 && ec[2] <= 0x9d) {
protocol = &alps_v3_protocol_data;
} else if (e7[0] == 0x73 && e7[1] == 0x03 &&
(e7[2] == 0x14 || e7[2] == 0x28)) {
protocol = &alps_v8_protocol_data;
} else if (e7[0] == 0x73 && e7[1] == 0x03 && e7[2] == 0xc8) {
protocol = &alps_v9_protocol_data;
psmouse_warn(psmouse,
"Unsupported ALPS V9 touchpad: E7=%3ph, EC=%3ph\n",
e7, ec);
return -EINVAL;
} else {
psmouse_dbg(psmouse,
"Likely not an ALPS touchpad: E7=%3ph, EC=%3ph\n", e7, ec);
return -EINVAL;
}
}
if (priv) {
/* Save Device ID and Firmware version */
memcpy(priv->dev_id, e7, 3);
memcpy(priv->fw_ver, ec, 3);
error = alps_set_protocol(psmouse, priv, protocol);
if (error)
return error;
}
return 0;
}
static int alps_reconnect(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
psmouse_reset(psmouse);
if (alps_identify(psmouse, priv) < 0)
return -1;
return priv->hw_init(psmouse);
}
static void alps_disconnect(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
psmouse_reset(psmouse);
timer_shutdown_sync(&priv->timer);
if (priv->dev2)
input_unregister_device(priv->dev2);
if (!IS_ERR_OR_NULL(priv->dev3))
input_unregister_device(priv->dev3);
kfree(priv);
}
static void alps_set_abs_params_st(struct alps_data *priv,
struct input_dev *dev1)
{
input_set_abs_params(dev1, ABS_X, 0, priv->x_max, 0, 0);
input_set_abs_params(dev1, ABS_Y, 0, priv->y_max, 0, 0);
input_set_abs_params(dev1, ABS_PRESSURE, 0, 127, 0, 0);
}
static void alps_set_abs_params_mt_common(struct alps_data *priv,
struct input_dev *dev1)
{
input_set_abs_params(dev1, ABS_MT_POSITION_X, 0, priv->x_max, 0, 0);
input_set_abs_params(dev1, ABS_MT_POSITION_Y, 0, priv->y_max, 0, 0);
input_abs_set_res(dev1, ABS_MT_POSITION_X, priv->x_res);
input_abs_set_res(dev1, ABS_MT_POSITION_Y, priv->y_res);
set_bit(BTN_TOOL_TRIPLETAP, dev1->keybit);
set_bit(BTN_TOOL_QUADTAP, dev1->keybit);
}
static void alps_set_abs_params_semi_mt(struct alps_data *priv,
struct input_dev *dev1)
{
alps_set_abs_params_mt_common(priv, dev1);
input_set_abs_params(dev1, ABS_PRESSURE, 0, 127, 0, 0);
input_mt_init_slots(dev1, MAX_TOUCHES,
INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED |
INPUT_MT_SEMI_MT);
}
static void alps_set_abs_params_v7(struct alps_data *priv,
struct input_dev *dev1)
{
alps_set_abs_params_mt_common(priv, dev1);
set_bit(BTN_TOOL_QUINTTAP, dev1->keybit);
input_mt_init_slots(dev1, MAX_TOUCHES,
INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED |
INPUT_MT_TRACK);
set_bit(BTN_TOOL_QUINTTAP, dev1->keybit);
}
static void alps_set_abs_params_ss4_v2(struct alps_data *priv,
struct input_dev *dev1)
{
alps_set_abs_params_mt_common(priv, dev1);
input_set_abs_params(dev1, ABS_PRESSURE, 0, 127, 0, 0);
set_bit(BTN_TOOL_QUINTTAP, dev1->keybit);
input_mt_init_slots(dev1, MAX_TOUCHES,
INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED |
INPUT_MT_TRACK);
}
int alps_init(struct psmouse *psmouse)
{
struct alps_data *priv = psmouse->private;
struct input_dev *dev1 = psmouse->dev;
int error;
error = priv->hw_init(psmouse);
if (error)
goto init_fail;
/*
* Undo part of setup done for us by psmouse core since touchpad
* is not a relative device.
*/
__clear_bit(EV_REL, dev1->evbit);
__clear_bit(REL_X, dev1->relbit);
__clear_bit(REL_Y, dev1->relbit);
/*
* Now set up our capabilities.
*/
dev1->evbit[BIT_WORD(EV_KEY)] |= BIT_MASK(EV_KEY);
dev1->keybit[BIT_WORD(BTN_TOUCH)] |= BIT_MASK(BTN_TOUCH);
dev1->keybit[BIT_WORD(BTN_TOOL_FINGER)] |= BIT_MASK(BTN_TOOL_FINGER);
dev1->keybit[BIT_WORD(BTN_LEFT)] |=
BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT);
dev1->evbit[BIT_WORD(EV_ABS)] |= BIT_MASK(EV_ABS);
priv->set_abs_params(priv, dev1);
if (priv->flags & ALPS_WHEEL) {
dev1->evbit[BIT_WORD(EV_REL)] |= BIT_MASK(EV_REL);
dev1->relbit[BIT_WORD(REL_WHEEL)] |= BIT_MASK(REL_WHEEL);
}
if (priv->flags & (ALPS_FW_BK_1 | ALPS_FW_BK_2)) {
dev1->keybit[BIT_WORD(BTN_FORWARD)] |= BIT_MASK(BTN_FORWARD);
dev1->keybit[BIT_WORD(BTN_BACK)] |= BIT_MASK(BTN_BACK);
}
if (priv->flags & ALPS_FOUR_BUTTONS) {
dev1->keybit[BIT_WORD(BTN_0)] |= BIT_MASK(BTN_0);
dev1->keybit[BIT_WORD(BTN_1)] |= BIT_MASK(BTN_1);
dev1->keybit[BIT_WORD(BTN_2)] |= BIT_MASK(BTN_2);
dev1->keybit[BIT_WORD(BTN_3)] |= BIT_MASK(BTN_3);
} else if (priv->flags & ALPS_BUTTONPAD) {
set_bit(INPUT_PROP_BUTTONPAD, dev1->propbit);
clear_bit(BTN_RIGHT, dev1->keybit);
} else {
dev1->keybit[BIT_WORD(BTN_MIDDLE)] |= BIT_MASK(BTN_MIDDLE);
}
if (priv->flags & ALPS_DUALPOINT) {
struct input_dev *dev2;
dev2 = input_allocate_device();
if (!dev2) {
psmouse_err(psmouse,
"failed to allocate trackstick device\n");
error = -ENOMEM;
goto init_fail;
}
snprintf(priv->phys2, sizeof(priv->phys2), "%s/input1",
psmouse->ps2dev.serio->phys);
dev2->phys = priv->phys2;
/*
* format of input device name is: "protocol vendor name"
* see function psmouse_switch_protocol() in psmouse-base.c
*/
dev2->name = "AlpsPS/2 ALPS DualPoint Stick";
dev2->id.bustype = BUS_I8042;
dev2->id.vendor = 0x0002;
dev2->id.product = PSMOUSE_ALPS;
dev2->id.version = priv->proto_version;
dev2->dev.parent = &psmouse->ps2dev.serio->dev;
input_set_capability(dev2, EV_REL, REL_X);
input_set_capability(dev2, EV_REL, REL_Y);
if (priv->flags & ALPS_DUALPOINT_WITH_PRESSURE) {
input_set_capability(dev2, EV_ABS, ABS_PRESSURE);
input_set_abs_params(dev2, ABS_PRESSURE, 0, 127, 0, 0);
}
input_set_capability(dev2, EV_KEY, BTN_LEFT);
input_set_capability(dev2, EV_KEY, BTN_RIGHT);
input_set_capability(dev2, EV_KEY, BTN_MIDDLE);
__set_bit(INPUT_PROP_POINTER, dev2->propbit);
__set_bit(INPUT_PROP_POINTING_STICK, dev2->propbit);
error = input_register_device(dev2);
if (error) {
psmouse_err(psmouse,
"failed to register trackstick device: %d\n",
error);
input_free_device(dev2);
goto init_fail;
}
priv->dev2 = dev2;
}
priv->psmouse = psmouse;
INIT_DELAYED_WORK(&priv->dev3_register_work,
alps_register_bare_ps2_mouse);
psmouse->protocol_handler = alps_process_byte;
psmouse->poll = alps_poll;
psmouse->disconnect = alps_disconnect;
psmouse->reconnect = alps_reconnect;
psmouse->pktsize = priv->proto_version == ALPS_PROTO_V4 ? 8 : 6;
/* We are having trouble resyncing ALPS touchpads so disable it for now */
psmouse->resync_time = 0;
/* Allow 2 invalid packets without resetting device */
psmouse->resetafter = psmouse->pktsize * 2;
return 0;
init_fail:
psmouse_reset(psmouse);
/*
* Even though we did not allocate psmouse->private we do free
* it here.
*/
kfree(psmouse->private);
psmouse->private = NULL;
return error;
}
int alps_detect(struct psmouse *psmouse, bool set_properties)
{
struct alps_data *priv;
int error;
error = alps_identify(psmouse, NULL);
if (error)
return error;
/*
* ALPS cs19 is a trackpoint-only device, and uses different
* protocol than DualPoint ones, so we return -EINVAL here and let
* trackpoint.c drive this device. If the trackpoint driver is not
* enabled, the device will fall back to a bare PS/2 mouse.
* If ps2_command() fails here, we depend on the immediately
* followed psmouse_reset() to reset the device to normal state.
*/
if (alps_is_cs19_trackpoint(psmouse)) {
psmouse_dbg(psmouse,
"ALPS CS19 trackpoint-only device detected, ignoring\n");
return -EINVAL;
}
/*
* Reset the device to make sure it is fully operational:
* on some laptops, like certain Dell Latitudes, we may
* fail to properly detect presence of trackstick if device
* has not been reset.
*/
psmouse_reset(psmouse);
priv = kzalloc(sizeof(struct alps_data), GFP_KERNEL);
if (!priv)
return -ENOMEM;
error = alps_identify(psmouse, priv);
if (error) {
kfree(priv);
return error;
}
if (set_properties) {
psmouse->vendor = "ALPS";
psmouse->name = priv->flags & ALPS_DUALPOINT ?
"DualPoint TouchPad" : "GlidePoint";
psmouse->model = priv->proto_version;
} else {
/*
* Destroy alps_data structure we allocated earlier since
* this was just a "trial run". Otherwise we'll keep it
* to be used by alps_init() which has to be called if
* we succeed and set_properties is true.
*/
kfree(priv);
psmouse->private = NULL;
}
return 0;
}
|
linux-master
|
drivers/input/mouse/alps.c
|
/*
* Cypress APA trackpad with I2C interface
*
* Author: Dudley Du <[email protected]>
*
* Copyright (C) 2015 Cypress Semiconductor, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/mutex.h>
#include <linux/completion.h>
#include <linux/slab.h>
#include <asm/unaligned.h>
#include <linux/crc-itu-t.h>
#include "cyapa.h"
#define GEN6_ENABLE_CMD_IRQ 0x41
#define GEN6_DISABLE_CMD_IRQ 0x42
#define GEN6_ENABLE_DEV_IRQ 0x43
#define GEN6_DISABLE_DEV_IRQ 0x44
#define GEN6_POWER_MODE_ACTIVE 0x01
#define GEN6_POWER_MODE_LP_MODE1 0x02
#define GEN6_POWER_MODE_LP_MODE2 0x03
#define GEN6_POWER_MODE_BTN_ONLY 0x04
#define GEN6_SET_POWER_MODE_INTERVAL 0x47
#define GEN6_GET_POWER_MODE_INTERVAL 0x48
#define GEN6_MAX_RX_NUM 14
#define GEN6_RETRIEVE_DATA_ID_RX_ATTENURATOR_IDAC 0x00
#define GEN6_RETRIEVE_DATA_ID_ATTENURATOR_TRIM 0x12
struct pip_app_cmd_head {
__le16 addr;
__le16 length;
u8 report_id;
u8 resv; /* Reserved, must be 0 */
u8 cmd_code; /* bit7: resv, set to 0; bit6~0: command code.*/
} __packed;
struct pip_app_resp_head {
__le16 length;
u8 report_id;
u8 resv; /* Reserved, must be 0 */
u8 cmd_code; /* bit7: TGL; bit6~0: command code.*/
/*
* The value of data_status can be the first byte of data or
* the command status or the unsupported command code depending on the
* requested command code.
*/
u8 data_status;
} __packed;
struct pip_fixed_info {
u8 silicon_id_high;
u8 silicon_id_low;
u8 family_id;
};
static u8 pip_get_bl_info[] = {
0x04, 0x00, 0x0B, 0x00, 0x40, 0x00, 0x01, 0x38,
0x00, 0x00, 0x70, 0x9E, 0x17
};
static bool cyapa_sort_pip_hid_descriptor_data(struct cyapa *cyapa,
u8 *buf, int len)
{
if (len != PIP_HID_DESCRIPTOR_SIZE)
return false;
if (buf[PIP_RESP_REPORT_ID_OFFSET] == PIP_HID_APP_REPORT_ID ||
buf[PIP_RESP_REPORT_ID_OFFSET] == PIP_HID_BL_REPORT_ID)
return true;
return false;
}
static int cyapa_get_pip_fixed_info(struct cyapa *cyapa,
struct pip_fixed_info *pip_info, bool is_bootloader)
{
u8 resp_data[PIP_READ_SYS_INFO_RESP_LENGTH];
int resp_len;
u16 product_family;
int error;
if (is_bootloader) {
/* Read Bootloader Information to determine Gen5 or Gen6. */
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
pip_get_bl_info, sizeof(pip_get_bl_info),
resp_data, &resp_len,
2000, cyapa_sort_tsg_pip_bl_resp_data,
false);
if (error || resp_len < PIP_BL_GET_INFO_RESP_LENGTH)
return error ? error : -EIO;
pip_info->family_id = resp_data[8];
pip_info->silicon_id_low = resp_data[10];
pip_info->silicon_id_high = resp_data[11];
return 0;
}
/* Get App System Information to determine Gen5 or Gen6. */
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
pip_read_sys_info, PIP_READ_SYS_INFO_CMD_LENGTH,
resp_data, &resp_len,
2000, cyapa_pip_sort_system_info_data, false);
if (error || resp_len < PIP_READ_SYS_INFO_RESP_LENGTH)
return error ? error : -EIO;
product_family = get_unaligned_le16(&resp_data[7]);
if ((product_family & PIP_PRODUCT_FAMILY_MASK) !=
PIP_PRODUCT_FAMILY_TRACKPAD)
return -EINVAL;
pip_info->family_id = resp_data[19];
pip_info->silicon_id_low = resp_data[21];
pip_info->silicon_id_high = resp_data[22];
return 0;
}
int cyapa_pip_state_parse(struct cyapa *cyapa, u8 *reg_data, int len)
{
u8 cmd[] = { 0x01, 0x00};
struct pip_fixed_info pip_info;
u8 resp_data[PIP_HID_DESCRIPTOR_SIZE];
int resp_len;
bool is_bootloader;
int error;
cyapa->state = CYAPA_STATE_NO_DEVICE;
/* Try to wake from it deep sleep state if it is. */
cyapa_pip_deep_sleep(cyapa, PIP_DEEP_SLEEP_STATE_ON);
/* Empty the buffer queue to get fresh data with later commands. */
cyapa_empty_pip_output_data(cyapa, NULL, NULL, NULL);
/*
* Read description info from trackpad device to determine running in
* APP mode or Bootloader mode.
*/
resp_len = PIP_HID_DESCRIPTOR_SIZE;
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
cmd, sizeof(cmd),
resp_data, &resp_len,
300,
cyapa_sort_pip_hid_descriptor_data,
false);
if (error)
return error;
if (resp_data[PIP_RESP_REPORT_ID_OFFSET] == PIP_HID_BL_REPORT_ID)
is_bootloader = true;
else if (resp_data[PIP_RESP_REPORT_ID_OFFSET] == PIP_HID_APP_REPORT_ID)
is_bootloader = false;
else
return -EAGAIN;
/* Get PIP fixed information to determine Gen5 or Gen6. */
memset(&pip_info, 0, sizeof(struct pip_fixed_info));
error = cyapa_get_pip_fixed_info(cyapa, &pip_info, is_bootloader);
if (error)
return error;
if (pip_info.family_id == 0x9B && pip_info.silicon_id_high == 0x0B) {
cyapa->gen = CYAPA_GEN6;
cyapa->state = is_bootloader ? CYAPA_STATE_GEN6_BL
: CYAPA_STATE_GEN6_APP;
} else if (pip_info.family_id == 0x91 &&
pip_info.silicon_id_high == 0x02) {
cyapa->gen = CYAPA_GEN5;
cyapa->state = is_bootloader ? CYAPA_STATE_GEN5_BL
: CYAPA_STATE_GEN5_APP;
}
return 0;
}
static int cyapa_gen6_read_sys_info(struct cyapa *cyapa)
{
u8 resp_data[PIP_READ_SYS_INFO_RESP_LENGTH];
int resp_len;
u16 product_family;
u8 rotat_align;
int error;
/* Get App System Information to determine Gen5 or Gen6. */
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
pip_read_sys_info, PIP_READ_SYS_INFO_CMD_LENGTH,
resp_data, &resp_len,
2000, cyapa_pip_sort_system_info_data, false);
if (error || resp_len < sizeof(resp_data))
return error ? error : -EIO;
product_family = get_unaligned_le16(&resp_data[7]);
if ((product_family & PIP_PRODUCT_FAMILY_MASK) !=
PIP_PRODUCT_FAMILY_TRACKPAD)
return -EINVAL;
cyapa->platform_ver = (resp_data[67] >> PIP_BL_PLATFORM_VER_SHIFT) &
PIP_BL_PLATFORM_VER_MASK;
cyapa->fw_maj_ver = resp_data[9];
cyapa->fw_min_ver = resp_data[10];
cyapa->electrodes_x = resp_data[33];
cyapa->electrodes_y = resp_data[34];
cyapa->physical_size_x = get_unaligned_le16(&resp_data[35]) / 100;
cyapa->physical_size_y = get_unaligned_le16(&resp_data[37]) / 100;
cyapa->max_abs_x = get_unaligned_le16(&resp_data[39]);
cyapa->max_abs_y = get_unaligned_le16(&resp_data[41]);
cyapa->max_z = get_unaligned_le16(&resp_data[43]);
cyapa->x_origin = resp_data[45] & 0x01;
cyapa->y_origin = resp_data[46] & 0x01;
cyapa->btn_capability = (resp_data[70] << 3) & CAPABILITY_BTN_MASK;
memcpy(&cyapa->product_id[0], &resp_data[51], 5);
cyapa->product_id[5] = '-';
memcpy(&cyapa->product_id[6], &resp_data[56], 6);
cyapa->product_id[12] = '-';
memcpy(&cyapa->product_id[13], &resp_data[62], 2);
cyapa->product_id[15] = '\0';
/* Get the number of Rx electrodes. */
rotat_align = resp_data[68];
cyapa->electrodes_rx =
rotat_align ? cyapa->electrodes_y : cyapa->electrodes_x;
cyapa->aligned_electrodes_rx = (cyapa->electrodes_rx + 3) & ~3u;
if (!cyapa->electrodes_x || !cyapa->electrodes_y ||
!cyapa->physical_size_x || !cyapa->physical_size_y ||
!cyapa->max_abs_x || !cyapa->max_abs_y || !cyapa->max_z)
return -EINVAL;
return 0;
}
static int cyapa_gen6_bl_read_app_info(struct cyapa *cyapa)
{
u8 resp_data[PIP_BL_APP_INFO_RESP_LENGTH];
int resp_len;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
pip_bl_read_app_info, PIP_BL_READ_APP_INFO_CMD_LENGTH,
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_bl_resp_data, false);
if (error || resp_len < PIP_BL_APP_INFO_RESP_LENGTH ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data))
return error ? error : -EIO;
cyapa->fw_maj_ver = resp_data[8];
cyapa->fw_min_ver = resp_data[9];
cyapa->platform_ver = (resp_data[12] >> PIP_BL_PLATFORM_VER_SHIFT) &
PIP_BL_PLATFORM_VER_MASK;
memcpy(&cyapa->product_id[0], &resp_data[13], 5);
cyapa->product_id[5] = '-';
memcpy(&cyapa->product_id[6], &resp_data[18], 6);
cyapa->product_id[12] = '-';
memcpy(&cyapa->product_id[13], &resp_data[24], 2);
cyapa->product_id[15] = '\0';
return 0;
}
static int cyapa_gen6_config_dev_irq(struct cyapa *cyapa, u8 cmd_code)
{
u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, cmd_code };
u8 resp_data[6];
int resp_len;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error || !VALID_CMD_RESP_HEADER(resp_data, cmd_code) ||
!PIP_CMD_COMPLETE_SUCCESS(resp_data)
)
return error < 0 ? error : -EINVAL;
return 0;
}
static int cyapa_gen6_set_proximity(struct cyapa *cyapa, bool enable)
{
int error;
cyapa_gen6_config_dev_irq(cyapa, GEN6_DISABLE_CMD_IRQ);
error = cyapa_pip_set_proximity(cyapa, enable);
cyapa_gen6_config_dev_irq(cyapa, GEN6_ENABLE_CMD_IRQ);
return error;
}
static int cyapa_gen6_change_power_state(struct cyapa *cyapa, u8 power_mode)
{
u8 cmd[] = { 0x04, 0x00, 0x06, 0x00, 0x2f, 0x00, 0x46, power_mode };
u8 resp_data[6];
int resp_len;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error || !VALID_CMD_RESP_HEADER(resp_data, 0x46))
return error < 0 ? error : -EINVAL;
/* New power state applied in device not match the set power state. */
if (resp_data[5] != power_mode)
return -EAGAIN;
return 0;
}
static int cyapa_gen6_set_interval_setting(struct cyapa *cyapa,
struct gen6_interval_setting *interval_setting)
{
struct gen6_set_interval_cmd {
__le16 addr;
__le16 length;
u8 report_id;
u8 rsvd; /* Reserved, must be 0 */
u8 cmd_code;
__le16 active_interval;
__le16 lp1_interval;
__le16 lp2_interval;
} __packed set_interval_cmd;
u8 resp_data[11];
int resp_len;
int error;
memset(&set_interval_cmd, 0, sizeof(set_interval_cmd));
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &set_interval_cmd.addr);
put_unaligned_le16(sizeof(set_interval_cmd) - 2,
&set_interval_cmd.length);
set_interval_cmd.report_id = PIP_APP_CMD_REPORT_ID;
set_interval_cmd.cmd_code = GEN6_SET_POWER_MODE_INTERVAL;
put_unaligned_le16(interval_setting->active_interval,
&set_interval_cmd.active_interval);
put_unaligned_le16(interval_setting->lp1_interval,
&set_interval_cmd.lp1_interval);
put_unaligned_le16(interval_setting->lp2_interval,
&set_interval_cmd.lp2_interval);
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
(u8 *)&set_interval_cmd, sizeof(set_interval_cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error ||
!VALID_CMD_RESP_HEADER(resp_data, GEN6_SET_POWER_MODE_INTERVAL))
return error < 0 ? error : -EINVAL;
/* Get the real set intervals from response. */
interval_setting->active_interval = get_unaligned_le16(&resp_data[5]);
interval_setting->lp1_interval = get_unaligned_le16(&resp_data[7]);
interval_setting->lp2_interval = get_unaligned_le16(&resp_data[9]);
return 0;
}
static int cyapa_gen6_get_interval_setting(struct cyapa *cyapa,
struct gen6_interval_setting *interval_setting)
{
u8 cmd[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00,
GEN6_GET_POWER_MODE_INTERVAL };
u8 resp_data[11];
int resp_len;
int error;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa, cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data, false);
if (error ||
!VALID_CMD_RESP_HEADER(resp_data, GEN6_GET_POWER_MODE_INTERVAL))
return error < 0 ? error : -EINVAL;
interval_setting->active_interval = get_unaligned_le16(&resp_data[5]);
interval_setting->lp1_interval = get_unaligned_le16(&resp_data[7]);
interval_setting->lp2_interval = get_unaligned_le16(&resp_data[9]);
return 0;
}
static int cyapa_gen6_deep_sleep(struct cyapa *cyapa, u8 state)
{
u8 ping[] = { 0x04, 0x00, 0x05, 0x00, 0x2f, 0x00, 0x00 };
if (state == PIP_DEEP_SLEEP_STATE_ON)
/*
* Send ping command to notify device prepare for wake up
* when it's in deep sleep mode. At this time, device will
* response nothing except an I2C NAK.
*/
cyapa_i2c_pip_write(cyapa, ping, sizeof(ping));
return cyapa_pip_deep_sleep(cyapa, state);
}
static int cyapa_gen6_set_power_mode(struct cyapa *cyapa,
u8 power_mode, u16 sleep_time, enum cyapa_pm_stage pm_stage)
{
struct device *dev = &cyapa->client->dev;
struct gen6_interval_setting *interval_setting =
&cyapa->gen6_interval_setting;
u8 lp_mode;
int error;
if (cyapa->state != CYAPA_STATE_GEN6_APP)
return 0;
if (PIP_DEV_GET_PWR_STATE(cyapa) == UNINIT_PWR_MODE) {
/*
* Assume TP in deep sleep mode when driver is loaded,
* avoid driver unload and reload command IO issue caused by TP
* has been set into deep sleep mode when unloading.
*/
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_OFF);
}
if (PIP_DEV_UNINIT_SLEEP_TIME(cyapa) &&
PIP_DEV_GET_PWR_STATE(cyapa) != PWR_MODE_OFF)
PIP_DEV_SET_SLEEP_TIME(cyapa, UNINIT_SLEEP_TIME);
if (PIP_DEV_GET_PWR_STATE(cyapa) == power_mode) {
if (power_mode == PWR_MODE_OFF ||
power_mode == PWR_MODE_FULL_ACTIVE ||
power_mode == PWR_MODE_BTN_ONLY ||
PIP_DEV_GET_SLEEP_TIME(cyapa) == sleep_time) {
/* Has in correct power mode state, early return. */
return 0;
}
}
if (power_mode == PWR_MODE_OFF) {
cyapa_gen6_config_dev_irq(cyapa, GEN6_DISABLE_CMD_IRQ);
error = cyapa_gen6_deep_sleep(cyapa, PIP_DEEP_SLEEP_STATE_OFF);
if (error) {
dev_err(dev, "enter deep sleep fail: %d\n", error);
return error;
}
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_OFF);
return 0;
}
/*
* When trackpad in power off mode, it cannot change to other power
* state directly, must be wake up from sleep firstly, then
* continue to do next power sate change.
*/
if (PIP_DEV_GET_PWR_STATE(cyapa) == PWR_MODE_OFF) {
error = cyapa_gen6_deep_sleep(cyapa, PIP_DEEP_SLEEP_STATE_ON);
if (error) {
dev_err(dev, "deep sleep wake fail: %d\n", error);
return error;
}
}
/*
* Disable device assert interrupts for command response to avoid
* disturbing system suspending or hibernating process.
*/
cyapa_gen6_config_dev_irq(cyapa, GEN6_DISABLE_CMD_IRQ);
if (power_mode == PWR_MODE_FULL_ACTIVE) {
error = cyapa_gen6_change_power_state(cyapa,
GEN6_POWER_MODE_ACTIVE);
if (error) {
dev_err(dev, "change to active fail: %d\n", error);
goto out;
}
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_FULL_ACTIVE);
/* Sync the interval setting from device. */
cyapa_gen6_get_interval_setting(cyapa, interval_setting);
} else if (power_mode == PWR_MODE_BTN_ONLY) {
error = cyapa_gen6_change_power_state(cyapa,
GEN6_POWER_MODE_BTN_ONLY);
if (error) {
dev_err(dev, "fail to button only mode: %d\n", error);
goto out;
}
PIP_DEV_SET_PWR_STATE(cyapa, PWR_MODE_BTN_ONLY);
} else {
/*
* Gen6 internally supports to 2 low power scan interval time,
* so can help to switch power mode quickly.
* such as runtime suspend and system suspend.
*/
if (interval_setting->lp1_interval == sleep_time) {
lp_mode = GEN6_POWER_MODE_LP_MODE1;
} else if (interval_setting->lp2_interval == sleep_time) {
lp_mode = GEN6_POWER_MODE_LP_MODE2;
} else {
if (interval_setting->lp1_interval == 0) {
interval_setting->lp1_interval = sleep_time;
lp_mode = GEN6_POWER_MODE_LP_MODE1;
} else {
interval_setting->lp2_interval = sleep_time;
lp_mode = GEN6_POWER_MODE_LP_MODE2;
}
cyapa_gen6_set_interval_setting(cyapa,
interval_setting);
}
error = cyapa_gen6_change_power_state(cyapa, lp_mode);
if (error) {
dev_err(dev, "set power state to 0x%02x failed: %d\n",
lp_mode, error);
goto out;
}
PIP_DEV_SET_SLEEP_TIME(cyapa, sleep_time);
PIP_DEV_SET_PWR_STATE(cyapa,
cyapa_sleep_time_to_pwr_cmd(sleep_time));
}
out:
cyapa_gen6_config_dev_irq(cyapa, GEN6_ENABLE_CMD_IRQ);
return error;
}
static int cyapa_gen6_initialize(struct cyapa *cyapa)
{
return 0;
}
static int cyapa_pip_retrieve_data_structure(struct cyapa *cyapa,
u16 read_offset, u16 read_len, u8 data_id,
u8 *data, int *data_buf_lens)
{
struct retrieve_data_struct_cmd {
struct pip_app_cmd_head head;
__le16 read_offset;
__le16 read_length;
u8 data_id;
} __packed cmd;
u8 resp_data[GEN6_MAX_RX_NUM + 10];
int resp_len;
int error;
memset(&cmd, 0, sizeof(cmd));
put_unaligned_le16(PIP_OUTPUT_REPORT_ADDR, &cmd.head.addr);
put_unaligned_le16(sizeof(cmd) - 2, &cmd.head.length);
cmd.head.report_id = PIP_APP_CMD_REPORT_ID;
cmd.head.cmd_code = PIP_RETRIEVE_DATA_STRUCTURE;
put_unaligned_le16(read_offset, &cmd.read_offset);
put_unaligned_le16(read_len, &cmd.read_length);
cmd.data_id = data_id;
resp_len = sizeof(resp_data);
error = cyapa_i2c_pip_cmd_irq_sync(cyapa,
(u8 *)&cmd, sizeof(cmd),
resp_data, &resp_len,
500, cyapa_sort_tsg_pip_app_resp_data,
true);
if (error || !PIP_CMD_COMPLETE_SUCCESS(resp_data) ||
resp_data[6] != data_id ||
!VALID_CMD_RESP_HEADER(resp_data, PIP_RETRIEVE_DATA_STRUCTURE))
return (error < 0) ? error : -EAGAIN;
read_len = get_unaligned_le16(&resp_data[7]);
if (*data_buf_lens < read_len) {
*data_buf_lens = read_len;
return -ENOBUFS;
}
memcpy(data, &resp_data[10], read_len);
*data_buf_lens = read_len;
return 0;
}
static ssize_t cyapa_gen6_show_baseline(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
u8 data[GEN6_MAX_RX_NUM];
int data_len;
int size = 0;
int i;
int error;
int resume_error;
if (!cyapa_is_pip_app_mode(cyapa))
return -EBUSY;
/* 1. Suspend Scanning*/
error = cyapa_pip_suspend_scanning(cyapa);
if (error)
return error;
/* 2. IDAC and RX Attenuator Calibration Data (Center Frequency). */
data_len = sizeof(data);
error = cyapa_pip_retrieve_data_structure(cyapa, 0, data_len,
GEN6_RETRIEVE_DATA_ID_RX_ATTENURATOR_IDAC,
data, &data_len);
if (error)
goto resume_scanning;
size = scnprintf(buf, PAGE_SIZE, "%d %d %d %d %d %d ",
data[0], /* RX Attenuator Mutual */
data[1], /* IDAC Mutual */
data[2], /* RX Attenuator Self RX */
data[3], /* IDAC Self RX */
data[4], /* RX Attenuator Self TX */
data[5] /* IDAC Self TX */
);
/* 3. Read Attenuator Trim. */
data_len = sizeof(data);
error = cyapa_pip_retrieve_data_structure(cyapa, 0, data_len,
GEN6_RETRIEVE_DATA_ID_ATTENURATOR_TRIM,
data, &data_len);
if (error)
goto resume_scanning;
/* set attenuator trim values. */
for (i = 0; i < data_len; i++)
size += scnprintf(buf + size, PAGE_SIZE - size, "%d ", data[i]);
size += scnprintf(buf + size, PAGE_SIZE - size, "\n");
resume_scanning:
/* 4. Resume Scanning*/
resume_error = cyapa_pip_resume_scanning(cyapa);
if (resume_error || error) {
memset(buf, 0, PAGE_SIZE);
return resume_error ? resume_error : error;
}
return size;
}
static int cyapa_gen6_operational_check(struct cyapa *cyapa)
{
struct device *dev = &cyapa->client->dev;
int error;
if (cyapa->gen != CYAPA_GEN6)
return -ENODEV;
switch (cyapa->state) {
case CYAPA_STATE_GEN6_BL:
error = cyapa_pip_bl_exit(cyapa);
if (error) {
/* Try to update trackpad product information. */
cyapa_gen6_bl_read_app_info(cyapa);
goto out;
}
cyapa->state = CYAPA_STATE_GEN6_APP;
fallthrough;
case CYAPA_STATE_GEN6_APP:
/*
* If trackpad device in deep sleep mode,
* the app command will fail.
* So always try to reset trackpad device to full active when
* the device state is required.
*/
error = cyapa_gen6_set_power_mode(cyapa,
PWR_MODE_FULL_ACTIVE, 0, CYAPA_PM_ACTIVE);
if (error)
dev_warn(dev, "%s: failed to set power active mode.\n",
__func__);
/* By default, the trackpad proximity function is enabled. */
error = cyapa_pip_set_proximity(cyapa, true);
if (error)
dev_warn(dev, "%s: failed to enable proximity.\n",
__func__);
/* Get trackpad product information. */
error = cyapa_gen6_read_sys_info(cyapa);
if (error)
goto out;
/* Only support product ID starting with CYTRA */
if (memcmp(cyapa->product_id, product_id,
strlen(product_id)) != 0) {
dev_err(dev, "%s: unknown product ID (%s)\n",
__func__, cyapa->product_id);
error = -EINVAL;
}
break;
default:
error = -EINVAL;
}
out:
return error;
}
const struct cyapa_dev_ops cyapa_gen6_ops = {
.check_fw = cyapa_pip_check_fw,
.bl_enter = cyapa_pip_bl_enter,
.bl_initiate = cyapa_pip_bl_initiate,
.update_fw = cyapa_pip_do_fw_update,
.bl_activate = cyapa_pip_bl_activate,
.bl_deactivate = cyapa_pip_bl_deactivate,
.show_baseline = cyapa_gen6_show_baseline,
.calibrate_store = cyapa_pip_do_calibrate,
.initialize = cyapa_gen6_initialize,
.state_parse = cyapa_pip_state_parse,
.operational_check = cyapa_gen6_operational_check,
.irq_handler = cyapa_pip_irq_handler,
.irq_cmd_handler = cyapa_pip_irq_cmd_handler,
.sort_empty_output_data = cyapa_empty_pip_output_data,
.set_power_mode = cyapa_gen6_set_power_mode,
.set_proximity = cyapa_gen6_set_proximity,
};
|
linux-master
|
drivers/input/mouse/cyapa_gen6.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Elantech Touchpad driver (v6)
*
* Copyright (C) 2007-2009 Arjan Opmeer <[email protected]>
*
* Trademarks are the property of their respective owners.
*/
#include <linux/delay.h>
#include <linux/dmi.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/platform_device.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include <asm/unaligned.h>
#include "psmouse.h"
#include "elantech.h"
#include "elan_i2c.h"
#define elantech_debug(fmt, ...) \
do { \
if (etd->info.debug) \
psmouse_printk(KERN_DEBUG, psmouse, \
fmt, ##__VA_ARGS__); \
} while (0)
/*
* Send a Synaptics style sliced query command
*/
static int synaptics_send_cmd(struct psmouse *psmouse, unsigned char c,
unsigned char *param)
{
if (ps2_sliced_command(&psmouse->ps2dev, c) ||
ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_GETINFO)) {
psmouse_err(psmouse, "%s query 0x%02x failed.\n", __func__, c);
return -1;
}
return 0;
}
/*
* V3 and later support this fast command
*/
static int elantech_send_cmd(struct psmouse *psmouse, unsigned char c,
unsigned char *param)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
if (ps2_command(ps2dev, NULL, ETP_PS2_CUSTOM_COMMAND) ||
ps2_command(ps2dev, NULL, c) ||
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO)) {
psmouse_err(psmouse, "%s query 0x%02x failed.\n", __func__, c);
return -1;
}
return 0;
}
/*
* A retrying version of ps2_command
*/
static int elantech_ps2_command(struct psmouse *psmouse,
unsigned char *param, int command)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct elantech_data *etd = psmouse->private;
int rc;
int tries = ETP_PS2_COMMAND_TRIES;
do {
rc = ps2_command(ps2dev, param, command);
if (rc == 0)
break;
tries--;
elantech_debug("retrying ps2 command 0x%02x (%d).\n",
command, tries);
msleep(ETP_PS2_COMMAND_DELAY);
} while (tries > 0);
if (rc)
psmouse_err(psmouse, "ps2 command 0x%02x failed.\n", command);
return rc;
}
/*
* Send an Elantech style special command to read 3 bytes from a register
*/
static int elantech_read_reg_params(struct psmouse *psmouse, u8 reg, u8 *param)
{
if (elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_READWRITE) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, reg) ||
elantech_ps2_command(psmouse, param, PSMOUSE_CMD_GETINFO)) {
psmouse_err(psmouse,
"failed to read register %#02x\n", reg);
return -EIO;
}
return 0;
}
/*
* Send an Elantech style special command to write a register with a parameter
*/
static int elantech_write_reg_params(struct psmouse *psmouse, u8 reg, u8 *param)
{
if (elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_READWRITE) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, reg) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, param[0]) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, param[1]) ||
elantech_ps2_command(psmouse, NULL, PSMOUSE_CMD_SETSCALE11)) {
psmouse_err(psmouse,
"failed to write register %#02x with value %#02x%#02x\n",
reg, param[0], param[1]);
return -EIO;
}
return 0;
}
/*
* Send an Elantech style special command to read a value from a register
*/
static int elantech_read_reg(struct psmouse *psmouse, unsigned char reg,
unsigned char *val)
{
struct elantech_data *etd = psmouse->private;
unsigned char param[3];
int rc = 0;
if (reg < 0x07 || reg > 0x26)
return -1;
if (reg > 0x11 && reg < 0x20)
return -1;
switch (etd->info.hw_version) {
case 1:
if (ps2_sliced_command(&psmouse->ps2dev, ETP_REGISTER_READ) ||
ps2_sliced_command(&psmouse->ps2dev, reg) ||
ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_GETINFO)) {
rc = -1;
}
break;
case 2:
if (elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_READ) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, reg) ||
elantech_ps2_command(psmouse, param, PSMOUSE_CMD_GETINFO)) {
rc = -1;
}
break;
case 3 ... 4:
if (elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_READWRITE) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, reg) ||
elantech_ps2_command(psmouse, param, PSMOUSE_CMD_GETINFO)) {
rc = -1;
}
break;
}
if (rc)
psmouse_err(psmouse, "failed to read register 0x%02x.\n", reg);
else if (etd->info.hw_version != 4)
*val = param[0];
else
*val = param[1];
return rc;
}
/*
* Send an Elantech style special command to write a register with a value
*/
static int elantech_write_reg(struct psmouse *psmouse, unsigned char reg,
unsigned char val)
{
struct elantech_data *etd = psmouse->private;
int rc = 0;
if (reg < 0x07 || reg > 0x26)
return -1;
if (reg > 0x11 && reg < 0x20)
return -1;
switch (etd->info.hw_version) {
case 1:
if (ps2_sliced_command(&psmouse->ps2dev, ETP_REGISTER_WRITE) ||
ps2_sliced_command(&psmouse->ps2dev, reg) ||
ps2_sliced_command(&psmouse->ps2dev, val) ||
ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_SETSCALE11)) {
rc = -1;
}
break;
case 2:
if (elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_WRITE) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, reg) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, val) ||
elantech_ps2_command(psmouse, NULL, PSMOUSE_CMD_SETSCALE11)) {
rc = -1;
}
break;
case 3:
if (elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_READWRITE) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, reg) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, val) ||
elantech_ps2_command(psmouse, NULL, PSMOUSE_CMD_SETSCALE11)) {
rc = -1;
}
break;
case 4:
if (elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_READWRITE) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, reg) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, ETP_REGISTER_READWRITE) ||
elantech_ps2_command(psmouse, NULL, ETP_PS2_CUSTOM_COMMAND) ||
elantech_ps2_command(psmouse, NULL, val) ||
elantech_ps2_command(psmouse, NULL, PSMOUSE_CMD_SETSCALE11)) {
rc = -1;
}
break;
}
if (rc)
psmouse_err(psmouse,
"failed to write register 0x%02x with value 0x%02x.\n",
reg, val);
return rc;
}
/*
* Dump a complete mouse movement packet to the syslog
*/
static void elantech_packet_dump(struct psmouse *psmouse)
{
psmouse_printk(KERN_DEBUG, psmouse, "PS/2 packet [%*ph]\n",
psmouse->pktsize, psmouse->packet);
}
/*
* Advertise INPUT_PROP_BUTTONPAD for clickpads. The testing of bit 12 in
* fw_version for this is based on the following fw_version & caps table:
*
* Laptop-model: fw_version: caps: buttons:
* Acer S3 0x461f00 10, 13, 0e clickpad
* Acer S7-392 0x581f01 50, 17, 0d clickpad
* Acer V5-131 0x461f02 01, 16, 0c clickpad
* Acer V5-551 0x461f00 ? clickpad
* Asus K53SV 0x450f01 78, 15, 0c 2 hw buttons
* Asus G46VW 0x460f02 00, 18, 0c 2 hw buttons
* Asus G750JX 0x360f00 00, 16, 0c 2 hw buttons
* Asus TP500LN 0x381f17 10, 14, 0e clickpad
* Asus X750JN 0x381f17 10, 14, 0e clickpad
* Asus UX31 0x361f00 20, 15, 0e clickpad
* Asus UX32VD 0x361f02 00, 15, 0e clickpad
* Avatar AVIU-145A2 0x361f00 ? clickpad
* Fujitsu CELSIUS H760 0x570f02 40, 14, 0c 3 hw buttons (**)
* Fujitsu CELSIUS H780 0x5d0f02 41, 16, 0d 3 hw buttons (**)
* Fujitsu LIFEBOOK E544 0x470f00 d0, 12, 09 2 hw buttons
* Fujitsu LIFEBOOK E546 0x470f00 50, 12, 09 2 hw buttons
* Fujitsu LIFEBOOK E547 0x470f00 50, 12, 09 2 hw buttons
* Fujitsu LIFEBOOK E554 0x570f01 40, 14, 0c 2 hw buttons
* Fujitsu LIFEBOOK E557 0x570f01 40, 14, 0c 2 hw buttons
* Fujitsu T725 0x470f01 05, 12, 09 2 hw buttons
* Fujitsu H730 0x570f00 c0, 14, 0c 3 hw buttons (**)
* Gigabyte U2442 0x450f01 58, 17, 0c 2 hw buttons
* Lenovo L430 0x350f02 b9, 15, 0c 2 hw buttons (*)
* Lenovo L530 0x350f02 b9, 15, 0c 2 hw buttons (*)
* Samsung NF210 0x150b00 78, 14, 0a 2 hw buttons
* Samsung NP770Z5E 0x575f01 10, 15, 0f clickpad
* Samsung NP700Z5B 0x361f06 21, 15, 0f clickpad
* Samsung NP900X3E-A02 0x575f03 ? clickpad
* Samsung NP-QX410 0x851b00 19, 14, 0c clickpad
* Samsung RC512 0x450f00 08, 15, 0c 2 hw buttons
* Samsung RF710 0x450f00 ? 2 hw buttons
* System76 Pangolin 0x250f01 ? 2 hw buttons
* (*) + 3 trackpoint buttons
* (**) + 0 trackpoint buttons
* Note: Lenovo L430 and Lenovo L530 have the same fw_version/caps
*/
static inline int elantech_is_buttonpad(struct elantech_device_info *info)
{
return info->fw_version & 0x001000;
}
/*
* Interpret complete data packets and report absolute mode input events for
* hardware version 1. (4 byte packets)
*/
static void elantech_report_absolute_v1(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
int fingers;
if (etd->info.fw_version < 0x020000) {
/*
* byte 0: D U p1 p2 1 p3 R L
* byte 1: f 0 th tw x9 x8 y9 y8
*/
fingers = ((packet[1] & 0x80) >> 7) +
((packet[1] & 0x30) >> 4);
} else {
/*
* byte 0: n1 n0 p2 p1 1 p3 R L
* byte 1: 0 0 0 0 x9 x8 y9 y8
*/
fingers = (packet[0] & 0xc0) >> 6;
}
if (etd->info.jumpy_cursor) {
if (fingers != 1) {
etd->single_finger_reports = 0;
} else if (etd->single_finger_reports < 2) {
/* Discard first 2 reports of one finger, bogus */
etd->single_finger_reports++;
elantech_debug("discarding packet\n");
return;
}
}
input_report_key(dev, BTN_TOUCH, fingers != 0);
/*
* byte 2: x7 x6 x5 x4 x3 x2 x1 x0
* byte 3: y7 y6 y5 y4 y3 y2 y1 y0
*/
if (fingers) {
input_report_abs(dev, ABS_X,
((packet[1] & 0x0c) << 6) | packet[2]);
input_report_abs(dev, ABS_Y,
etd->y_max - (((packet[1] & 0x03) << 8) | packet[3]));
}
input_report_key(dev, BTN_TOOL_FINGER, fingers == 1);
input_report_key(dev, BTN_TOOL_DOUBLETAP, fingers == 2);
input_report_key(dev, BTN_TOOL_TRIPLETAP, fingers == 3);
psmouse_report_standard_buttons(dev, packet[0]);
if (etd->info.fw_version < 0x020000 &&
(etd->info.capabilities[0] & ETP_CAP_HAS_ROCKER)) {
/* rocker up */
input_report_key(dev, BTN_FORWARD, packet[0] & 0x40);
/* rocker down */
input_report_key(dev, BTN_BACK, packet[0] & 0x80);
}
input_sync(dev);
}
static void elantech_set_slot(struct input_dev *dev, int slot, bool active,
unsigned int x, unsigned int y)
{
input_mt_slot(dev, slot);
input_mt_report_slot_state(dev, MT_TOOL_FINGER, active);
if (active) {
input_report_abs(dev, ABS_MT_POSITION_X, x);
input_report_abs(dev, ABS_MT_POSITION_Y, y);
}
}
/* x1 < x2 and y1 < y2 when two fingers, x = y = 0 when not pressed */
static void elantech_report_semi_mt_data(struct input_dev *dev,
unsigned int num_fingers,
unsigned int x1, unsigned int y1,
unsigned int x2, unsigned int y2)
{
elantech_set_slot(dev, 0, num_fingers != 0, x1, y1);
elantech_set_slot(dev, 1, num_fingers >= 2, x2, y2);
}
/*
* Interpret complete data packets and report absolute mode input events for
* hardware version 2. (6 byte packets)
*/
static void elantech_report_absolute_v2(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
unsigned int fingers, x1 = 0, y1 = 0, x2 = 0, y2 = 0;
unsigned int width = 0, pres = 0;
/* byte 0: n1 n0 . . . . R L */
fingers = (packet[0] & 0xc0) >> 6;
switch (fingers) {
case 3:
/*
* Same as one finger, except report of more than 3 fingers:
* byte 3: n4 . w1 w0 . . . .
*/
if (packet[3] & 0x80)
fingers = 4;
fallthrough;
case 1:
/*
* byte 1: . . . . x11 x10 x9 x8
* byte 2: x7 x6 x5 x4 x4 x2 x1 x0
*/
x1 = ((packet[1] & 0x0f) << 8) | packet[2];
/*
* byte 4: . . . . y11 y10 y9 y8
* byte 5: y7 y6 y5 y4 y3 y2 y1 y0
*/
y1 = etd->y_max - (((packet[4] & 0x0f) << 8) | packet[5]);
pres = (packet[1] & 0xf0) | ((packet[4] & 0xf0) >> 4);
width = ((packet[0] & 0x30) >> 2) | ((packet[3] & 0x30) >> 4);
break;
case 2:
/*
* The coordinate of each finger is reported separately
* with a lower resolution for two finger touches:
* byte 0: . . ay8 ax8 . . . .
* byte 1: ax7 ax6 ax5 ax4 ax3 ax2 ax1 ax0
*/
x1 = (((packet[0] & 0x10) << 4) | packet[1]) << 2;
/* byte 2: ay7 ay6 ay5 ay4 ay3 ay2 ay1 ay0 */
y1 = etd->y_max -
((((packet[0] & 0x20) << 3) | packet[2]) << 2);
/*
* byte 3: . . by8 bx8 . . . .
* byte 4: bx7 bx6 bx5 bx4 bx3 bx2 bx1 bx0
*/
x2 = (((packet[3] & 0x10) << 4) | packet[4]) << 2;
/* byte 5: by7 by8 by5 by4 by3 by2 by1 by0 */
y2 = etd->y_max -
((((packet[3] & 0x20) << 3) | packet[5]) << 2);
/* Unknown so just report sensible values */
pres = 127;
width = 7;
break;
}
input_report_key(dev, BTN_TOUCH, fingers != 0);
if (fingers != 0) {
input_report_abs(dev, ABS_X, x1);
input_report_abs(dev, ABS_Y, y1);
}
elantech_report_semi_mt_data(dev, fingers, x1, y1, x2, y2);
input_report_key(dev, BTN_TOOL_FINGER, fingers == 1);
input_report_key(dev, BTN_TOOL_DOUBLETAP, fingers == 2);
input_report_key(dev, BTN_TOOL_TRIPLETAP, fingers == 3);
input_report_key(dev, BTN_TOOL_QUADTAP, fingers == 4);
psmouse_report_standard_buttons(dev, packet[0]);
if (etd->info.reports_pressure) {
input_report_abs(dev, ABS_PRESSURE, pres);
input_report_abs(dev, ABS_TOOL_WIDTH, width);
}
input_sync(dev);
}
static void elantech_report_trackpoint(struct psmouse *psmouse,
int packet_type)
{
/*
* byte 0: 0 0 sx sy 0 M R L
* byte 1:~sx 0 0 0 0 0 0 0
* byte 2:~sy 0 0 0 0 0 0 0
* byte 3: 0 0 ~sy ~sx 0 1 1 0
* byte 4: x7 x6 x5 x4 x3 x2 x1 x0
* byte 5: y7 y6 y5 y4 y3 y2 y1 y0
*
* x and y are written in two's complement spread
* over 9 bits with sx/sy the relative top bit and
* x7..x0 and y7..y0 the lower bits.
* The sign of y is opposite to what the input driver
* expects for a relative movement
*/
struct elantech_data *etd = psmouse->private;
struct input_dev *tp_dev = etd->tp_dev;
unsigned char *packet = psmouse->packet;
int x, y;
u32 t;
t = get_unaligned_le32(&packet[0]);
switch (t & ~7U) {
case 0x06000030U:
case 0x16008020U:
case 0x26800010U:
case 0x36808000U:
/*
* This firmware misreport coordinates for trackpoint
* occasionally. Discard packets outside of [-127, 127] range
* to prevent cursor jumps.
*/
if (packet[4] == 0x80 || packet[5] == 0x80 ||
packet[1] >> 7 == packet[4] >> 7 ||
packet[2] >> 7 == packet[5] >> 7) {
elantech_debug("discarding packet [%6ph]\n", packet);
break;
}
x = packet[4] - (int)((packet[1]^0x80) << 1);
y = (int)((packet[2]^0x80) << 1) - packet[5];
psmouse_report_standard_buttons(tp_dev, packet[0]);
input_report_rel(tp_dev, REL_X, x);
input_report_rel(tp_dev, REL_Y, y);
input_sync(tp_dev);
break;
default:
/* Dump unexpected packet sequences if debug=1 (default) */
if (etd->info.debug == 1)
elantech_packet_dump(psmouse);
break;
}
}
/*
* Interpret complete data packets and report absolute mode input events for
* hardware version 3. (12 byte packets for two fingers)
*/
static void elantech_report_absolute_v3(struct psmouse *psmouse,
int packet_type)
{
struct input_dev *dev = psmouse->dev;
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
unsigned int fingers = 0, x1 = 0, y1 = 0, x2 = 0, y2 = 0;
unsigned int width = 0, pres = 0;
/* byte 0: n1 n0 . . . . R L */
fingers = (packet[0] & 0xc0) >> 6;
switch (fingers) {
case 3:
case 1:
/*
* byte 1: . . . . x11 x10 x9 x8
* byte 2: x7 x6 x5 x4 x4 x2 x1 x0
*/
x1 = ((packet[1] & 0x0f) << 8) | packet[2];
/*
* byte 4: . . . . y11 y10 y9 y8
* byte 5: y7 y6 y5 y4 y3 y2 y1 y0
*/
y1 = etd->y_max - (((packet[4] & 0x0f) << 8) | packet[5]);
break;
case 2:
if (packet_type == PACKET_V3_HEAD) {
/*
* byte 1: . . . . ax11 ax10 ax9 ax8
* byte 2: ax7 ax6 ax5 ax4 ax3 ax2 ax1 ax0
*/
etd->mt[0].x = ((packet[1] & 0x0f) << 8) | packet[2];
/*
* byte 4: . . . . ay11 ay10 ay9 ay8
* byte 5: ay7 ay6 ay5 ay4 ay3 ay2 ay1 ay0
*/
etd->mt[0].y = etd->y_max -
(((packet[4] & 0x0f) << 8) | packet[5]);
/*
* wait for next packet
*/
return;
}
/* packet_type == PACKET_V3_TAIL */
x1 = etd->mt[0].x;
y1 = etd->mt[0].y;
x2 = ((packet[1] & 0x0f) << 8) | packet[2];
y2 = etd->y_max - (((packet[4] & 0x0f) << 8) | packet[5]);
break;
}
pres = (packet[1] & 0xf0) | ((packet[4] & 0xf0) >> 4);
width = ((packet[0] & 0x30) >> 2) | ((packet[3] & 0x30) >> 4);
input_report_key(dev, BTN_TOUCH, fingers != 0);
if (fingers != 0) {
input_report_abs(dev, ABS_X, x1);
input_report_abs(dev, ABS_Y, y1);
}
elantech_report_semi_mt_data(dev, fingers, x1, y1, x2, y2);
input_report_key(dev, BTN_TOOL_FINGER, fingers == 1);
input_report_key(dev, BTN_TOOL_DOUBLETAP, fingers == 2);
input_report_key(dev, BTN_TOOL_TRIPLETAP, fingers == 3);
/* For clickpads map both buttons to BTN_LEFT */
if (elantech_is_buttonpad(&etd->info))
input_report_key(dev, BTN_LEFT, packet[0] & 0x03);
else
psmouse_report_standard_buttons(dev, packet[0]);
input_report_abs(dev, ABS_PRESSURE, pres);
input_report_abs(dev, ABS_TOOL_WIDTH, width);
input_sync(dev);
}
static void elantech_input_sync_v4(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
/* For clickpads map both buttons to BTN_LEFT */
if (elantech_is_buttonpad(&etd->info))
input_report_key(dev, BTN_LEFT, packet[0] & 0x03);
else
psmouse_report_standard_buttons(dev, packet[0]);
input_mt_report_pointer_emulation(dev, true);
input_sync(dev);
}
static void process_packet_status_v4(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
unsigned fingers;
int i;
/* notify finger state change */
fingers = packet[1] & 0x1f;
for (i = 0; i < ETP_MAX_FINGERS; i++) {
if ((fingers & (1 << i)) == 0) {
input_mt_slot(dev, i);
input_mt_report_slot_state(dev, MT_TOOL_FINGER, false);
}
}
elantech_input_sync_v4(psmouse);
}
static void process_packet_head_v4(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
int id;
int pres, traces;
id = ((packet[3] & 0xe0) >> 5) - 1;
if (id < 0 || id >= ETP_MAX_FINGERS)
return;
etd->mt[id].x = ((packet[1] & 0x0f) << 8) | packet[2];
etd->mt[id].y = etd->y_max - (((packet[4] & 0x0f) << 8) | packet[5]);
pres = (packet[1] & 0xf0) | ((packet[4] & 0xf0) >> 4);
traces = (packet[0] & 0xf0) >> 4;
input_mt_slot(dev, id);
input_mt_report_slot_state(dev, MT_TOOL_FINGER, true);
input_report_abs(dev, ABS_MT_POSITION_X, etd->mt[id].x);
input_report_abs(dev, ABS_MT_POSITION_Y, etd->mt[id].y);
input_report_abs(dev, ABS_MT_PRESSURE, pres);
input_report_abs(dev, ABS_MT_TOUCH_MAJOR, traces * etd->width);
/* report this for backwards compatibility */
input_report_abs(dev, ABS_TOOL_WIDTH, traces);
elantech_input_sync_v4(psmouse);
}
static void process_packet_motion_v4(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
int weight, delta_x1 = 0, delta_y1 = 0, delta_x2 = 0, delta_y2 = 0;
int id, sid;
id = ((packet[0] & 0xe0) >> 5) - 1;
if (id < 0 || id >= ETP_MAX_FINGERS)
return;
sid = ((packet[3] & 0xe0) >> 5) - 1;
weight = (packet[0] & 0x10) ? ETP_WEIGHT_VALUE : 1;
/*
* Motion packets give us the delta of x, y values of specific fingers,
* but in two's complement. Let the compiler do the conversion for us.
* Also _enlarge_ the numbers to int, in case of overflow.
*/
delta_x1 = (signed char)packet[1];
delta_y1 = (signed char)packet[2];
delta_x2 = (signed char)packet[4];
delta_y2 = (signed char)packet[5];
etd->mt[id].x += delta_x1 * weight;
etd->mt[id].y -= delta_y1 * weight;
input_mt_slot(dev, id);
input_report_abs(dev, ABS_MT_POSITION_X, etd->mt[id].x);
input_report_abs(dev, ABS_MT_POSITION_Y, etd->mt[id].y);
if (sid >= 0 && sid < ETP_MAX_FINGERS) {
etd->mt[sid].x += delta_x2 * weight;
etd->mt[sid].y -= delta_y2 * weight;
input_mt_slot(dev, sid);
input_report_abs(dev, ABS_MT_POSITION_X, etd->mt[sid].x);
input_report_abs(dev, ABS_MT_POSITION_Y, etd->mt[sid].y);
}
elantech_input_sync_v4(psmouse);
}
static void elantech_report_absolute_v4(struct psmouse *psmouse,
int packet_type)
{
switch (packet_type) {
case PACKET_V4_STATUS:
process_packet_status_v4(psmouse);
break;
case PACKET_V4_HEAD:
process_packet_head_v4(psmouse);
break;
case PACKET_V4_MOTION:
process_packet_motion_v4(psmouse);
break;
case PACKET_UNKNOWN:
default:
/* impossible to get here */
break;
}
}
static int elantech_packet_check_v1(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
unsigned char p1, p2, p3;
/* Parity bits are placed differently */
if (etd->info.fw_version < 0x020000) {
/* byte 0: D U p1 p2 1 p3 R L */
p1 = (packet[0] & 0x20) >> 5;
p2 = (packet[0] & 0x10) >> 4;
} else {
/* byte 0: n1 n0 p2 p1 1 p3 R L */
p1 = (packet[0] & 0x10) >> 4;
p2 = (packet[0] & 0x20) >> 5;
}
p3 = (packet[0] & 0x04) >> 2;
return etd->parity[packet[1]] == p1 &&
etd->parity[packet[2]] == p2 &&
etd->parity[packet[3]] == p3;
}
static int elantech_debounce_check_v2(struct psmouse *psmouse)
{
/*
* When we encounter packet that matches this exactly, it means the
* hardware is in debounce status. Just ignore the whole packet.
*/
static const u8 debounce_packet[] = {
0x84, 0xff, 0xff, 0x02, 0xff, 0xff
};
unsigned char *packet = psmouse->packet;
return !memcmp(packet, debounce_packet, sizeof(debounce_packet));
}
static int elantech_packet_check_v2(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
/*
* V2 hardware has two flavors. Older ones that do not report pressure,
* and newer ones that reports pressure and width. With newer ones, all
* packets (1, 2, 3 finger touch) have the same constant bits. With
* older ones, 1/3 finger touch packets and 2 finger touch packets
* have different constant bits.
* With all three cases, if the constant bits are not exactly what I
* expected, I consider them invalid.
*/
if (etd->info.reports_pressure)
return (packet[0] & 0x0c) == 0x04 &&
(packet[3] & 0x0f) == 0x02;
if ((packet[0] & 0xc0) == 0x80)
return (packet[0] & 0x0c) == 0x0c &&
(packet[3] & 0x0e) == 0x08;
return (packet[0] & 0x3c) == 0x3c &&
(packet[1] & 0xf0) == 0x00 &&
(packet[3] & 0x3e) == 0x38 &&
(packet[4] & 0xf0) == 0x00;
}
/*
* We check the constant bits to determine what packet type we get,
* so packet checking is mandatory for v3 and later hardware.
*/
static int elantech_packet_check_v3(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
static const u8 debounce_packet[] = {
0xc4, 0xff, 0xff, 0x02, 0xff, 0xff
};
unsigned char *packet = psmouse->packet;
/*
* check debounce first, it has the same signature in byte 0
* and byte 3 as PACKET_V3_HEAD.
*/
if (!memcmp(packet, debounce_packet, sizeof(debounce_packet)))
return PACKET_DEBOUNCE;
/*
* If the hardware flag 'crc_enabled' is set the packets have
* different signatures.
*/
if (etd->info.crc_enabled) {
if ((packet[3] & 0x09) == 0x08)
return PACKET_V3_HEAD;
if ((packet[3] & 0x09) == 0x09)
return PACKET_V3_TAIL;
} else {
if ((packet[0] & 0x0c) == 0x04 && (packet[3] & 0xcf) == 0x02)
return PACKET_V3_HEAD;
if ((packet[0] & 0x0c) == 0x0c && (packet[3] & 0xce) == 0x0c)
return PACKET_V3_TAIL;
if ((packet[3] & 0x0f) == 0x06)
return PACKET_TRACKPOINT;
}
return PACKET_UNKNOWN;
}
static int elantech_packet_check_v4(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
unsigned char *packet = psmouse->packet;
unsigned char packet_type = packet[3] & 0x03;
unsigned int ic_version;
bool sanity_check;
if (etd->tp_dev && (packet[3] & 0x0f) == 0x06)
return PACKET_TRACKPOINT;
/* This represents the version of IC body. */
ic_version = (etd->info.fw_version & 0x0f0000) >> 16;
/*
* Sanity check based on the constant bits of a packet.
* The constant bits change depending on the value of
* the hardware flag 'crc_enabled' and the version of
* the IC body, but are the same for every packet,
* regardless of the type.
*/
if (etd->info.crc_enabled)
sanity_check = ((packet[3] & 0x08) == 0x00);
else if (ic_version == 7 && etd->info.samples[1] == 0x2A)
sanity_check = ((packet[3] & 0x1c) == 0x10);
else
sanity_check = ((packet[0] & 0x08) == 0x00 &&
(packet[3] & 0x1c) == 0x10);
if (!sanity_check)
return PACKET_UNKNOWN;
switch (packet_type) {
case 0:
return PACKET_V4_STATUS;
case 1:
return PACKET_V4_HEAD;
case 2:
return PACKET_V4_MOTION;
}
return PACKET_UNKNOWN;
}
/*
* Process byte stream from mouse and handle complete packets
*/
static psmouse_ret_t elantech_process_byte(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
int packet_type;
if (psmouse->pktcnt < psmouse->pktsize)
return PSMOUSE_GOOD_DATA;
if (etd->info.debug > 1)
elantech_packet_dump(psmouse);
switch (etd->info.hw_version) {
case 1:
if (etd->info.paritycheck && !elantech_packet_check_v1(psmouse))
return PSMOUSE_BAD_DATA;
elantech_report_absolute_v1(psmouse);
break;
case 2:
/* ignore debounce */
if (elantech_debounce_check_v2(psmouse))
return PSMOUSE_FULL_PACKET;
if (etd->info.paritycheck && !elantech_packet_check_v2(psmouse))
return PSMOUSE_BAD_DATA;
elantech_report_absolute_v2(psmouse);
break;
case 3:
packet_type = elantech_packet_check_v3(psmouse);
switch (packet_type) {
case PACKET_UNKNOWN:
return PSMOUSE_BAD_DATA;
case PACKET_DEBOUNCE:
/* ignore debounce */
break;
case PACKET_TRACKPOINT:
elantech_report_trackpoint(psmouse, packet_type);
break;
default:
elantech_report_absolute_v3(psmouse, packet_type);
break;
}
break;
case 4:
packet_type = elantech_packet_check_v4(psmouse);
switch (packet_type) {
case PACKET_UNKNOWN:
return PSMOUSE_BAD_DATA;
case PACKET_TRACKPOINT:
elantech_report_trackpoint(psmouse, packet_type);
break;
default:
elantech_report_absolute_v4(psmouse, packet_type);
break;
}
break;
}
return PSMOUSE_FULL_PACKET;
}
/*
* This writes the reg_07 value again to the hardware at the end of every
* set_rate call because the register loses its value. reg_07 allows setting
* absolute mode on v4 hardware
*/
static void elantech_set_rate_restore_reg_07(struct psmouse *psmouse,
unsigned int rate)
{
struct elantech_data *etd = psmouse->private;
etd->original_set_rate(psmouse, rate);
if (elantech_write_reg(psmouse, 0x07, etd->reg_07))
psmouse_err(psmouse, "restoring reg_07 failed\n");
}
/*
* Put the touchpad into absolute mode
*/
static int elantech_set_absolute_mode(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
unsigned char val;
int tries = ETP_READ_BACK_TRIES;
int rc = 0;
switch (etd->info.hw_version) {
case 1:
etd->reg_10 = 0x16;
etd->reg_11 = 0x8f;
if (elantech_write_reg(psmouse, 0x10, etd->reg_10) ||
elantech_write_reg(psmouse, 0x11, etd->reg_11)) {
rc = -1;
}
break;
case 2:
/* Windows driver values */
etd->reg_10 = 0x54;
etd->reg_11 = 0x88; /* 0x8a */
etd->reg_21 = 0x60; /* 0x00 */
if (elantech_write_reg(psmouse, 0x10, etd->reg_10) ||
elantech_write_reg(psmouse, 0x11, etd->reg_11) ||
elantech_write_reg(psmouse, 0x21, etd->reg_21)) {
rc = -1;
}
break;
case 3:
if (etd->info.set_hw_resolution)
etd->reg_10 = 0x0b;
else
etd->reg_10 = 0x01;
if (elantech_write_reg(psmouse, 0x10, etd->reg_10))
rc = -1;
break;
case 4:
etd->reg_07 = 0x01;
if (elantech_write_reg(psmouse, 0x07, etd->reg_07))
rc = -1;
goto skip_readback_reg_10; /* v4 has no reg 0x10 to read */
}
if (rc == 0) {
/*
* Read back reg 0x10. For hardware version 1 we must make
* sure the absolute mode bit is set. For hardware version 2
* the touchpad is probably initializing and not ready until
* we read back the value we just wrote.
*/
do {
rc = elantech_read_reg(psmouse, 0x10, &val);
if (rc == 0)
break;
tries--;
elantech_debug("retrying read (%d).\n", tries);
msleep(ETP_READ_BACK_DELAY);
} while (tries > 0);
if (rc) {
psmouse_err(psmouse,
"failed to read back register 0x10.\n");
} else if (etd->info.hw_version == 1 &&
!(val & ETP_R10_ABSOLUTE_MODE)) {
psmouse_err(psmouse,
"touchpad refuses to switch to absolute mode.\n");
rc = -1;
}
}
skip_readback_reg_10:
if (rc)
psmouse_err(psmouse, "failed to initialise registers.\n");
return rc;
}
/*
* (value from firmware) * 10 + 790 = dpi
* we also have to convert dpi to dots/mm (*10/254 to avoid floating point)
*/
static unsigned int elantech_convert_res(unsigned int val)
{
return (val * 10 + 790) * 10 / 254;
}
static int elantech_get_resolution_v4(struct psmouse *psmouse,
unsigned int *x_res,
unsigned int *y_res,
unsigned int *bus)
{
unsigned char param[3];
if (elantech_send_cmd(psmouse, ETP_RESOLUTION_QUERY, param))
return -1;
*x_res = elantech_convert_res(param[1] & 0x0f);
*y_res = elantech_convert_res((param[1] & 0xf0) >> 4);
*bus = param[2];
return 0;
}
static void elantech_set_buttonpad_prop(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct elantech_data *etd = psmouse->private;
if (elantech_is_buttonpad(&etd->info)) {
__set_bit(INPUT_PROP_BUTTONPAD, dev->propbit);
__clear_bit(BTN_RIGHT, dev->keybit);
}
}
/*
* Some hw_version 4 models do have a middle button
*/
static const struct dmi_system_id elantech_dmi_has_middle_button[] = {
#if defined(CONFIG_DMI) && defined(CONFIG_X86)
{
/* Fujitsu H730 has a middle button */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "CELSIUS H730"),
},
},
{
/* Fujitsu H760 also has a middle button */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "CELSIUS H760"),
},
},
{
/* Fujitsu H780 also has a middle button */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "CELSIUS H780"),
},
},
#endif
{ }
};
/*
* Set the appropriate event bits for the input subsystem
*/
static int elantech_set_input_params(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct elantech_data *etd = psmouse->private;
struct elantech_device_info *info = &etd->info;
unsigned int x_min = info->x_min, y_min = info->y_min,
x_max = info->x_max, y_max = info->y_max,
width = info->width;
__set_bit(INPUT_PROP_POINTER, dev->propbit);
__set_bit(EV_KEY, dev->evbit);
__set_bit(EV_ABS, dev->evbit);
__clear_bit(EV_REL, dev->evbit);
__set_bit(BTN_LEFT, dev->keybit);
if (info->has_middle_button)
__set_bit(BTN_MIDDLE, dev->keybit);
__set_bit(BTN_RIGHT, dev->keybit);
__set_bit(BTN_TOUCH, dev->keybit);
__set_bit(BTN_TOOL_FINGER, dev->keybit);
__set_bit(BTN_TOOL_DOUBLETAP, dev->keybit);
__set_bit(BTN_TOOL_TRIPLETAP, dev->keybit);
switch (info->hw_version) {
case 1:
/* Rocker button */
if (info->fw_version < 0x020000 &&
(info->capabilities[0] & ETP_CAP_HAS_ROCKER)) {
__set_bit(BTN_FORWARD, dev->keybit);
__set_bit(BTN_BACK, dev->keybit);
}
input_set_abs_params(dev, ABS_X, x_min, x_max, 0, 0);
input_set_abs_params(dev, ABS_Y, y_min, y_max, 0, 0);
break;
case 2:
__set_bit(BTN_TOOL_QUADTAP, dev->keybit);
__set_bit(INPUT_PROP_SEMI_MT, dev->propbit);
fallthrough;
case 3:
if (info->hw_version == 3)
elantech_set_buttonpad_prop(psmouse);
input_set_abs_params(dev, ABS_X, x_min, x_max, 0, 0);
input_set_abs_params(dev, ABS_Y, y_min, y_max, 0, 0);
if (info->reports_pressure) {
input_set_abs_params(dev, ABS_PRESSURE, ETP_PMIN_V2,
ETP_PMAX_V2, 0, 0);
input_set_abs_params(dev, ABS_TOOL_WIDTH, ETP_WMIN_V2,
ETP_WMAX_V2, 0, 0);
}
input_mt_init_slots(dev, 2, INPUT_MT_SEMI_MT);
input_set_abs_params(dev, ABS_MT_POSITION_X, x_min, x_max, 0, 0);
input_set_abs_params(dev, ABS_MT_POSITION_Y, y_min, y_max, 0, 0);
break;
case 4:
elantech_set_buttonpad_prop(psmouse);
__set_bit(BTN_TOOL_QUADTAP, dev->keybit);
/* For X to recognize me as touchpad. */
input_set_abs_params(dev, ABS_X, x_min, x_max, 0, 0);
input_set_abs_params(dev, ABS_Y, y_min, y_max, 0, 0);
/*
* range of pressure and width is the same as v2,
* report ABS_PRESSURE, ABS_TOOL_WIDTH for compatibility.
*/
input_set_abs_params(dev, ABS_PRESSURE, ETP_PMIN_V2,
ETP_PMAX_V2, 0, 0);
input_set_abs_params(dev, ABS_TOOL_WIDTH, ETP_WMIN_V2,
ETP_WMAX_V2, 0, 0);
/* Multitouch capable pad, up to 5 fingers. */
input_mt_init_slots(dev, ETP_MAX_FINGERS, 0);
input_set_abs_params(dev, ABS_MT_POSITION_X, x_min, x_max, 0, 0);
input_set_abs_params(dev, ABS_MT_POSITION_Y, y_min, y_max, 0, 0);
input_set_abs_params(dev, ABS_MT_PRESSURE, ETP_PMIN_V2,
ETP_PMAX_V2, 0, 0);
/*
* The firmware reports how many trace lines the finger spans,
* convert to surface unit as Protocol-B requires.
*/
input_set_abs_params(dev, ABS_MT_TOUCH_MAJOR, 0,
ETP_WMAX_V2 * width, 0, 0);
break;
}
input_abs_set_res(dev, ABS_X, info->x_res);
input_abs_set_res(dev, ABS_Y, info->y_res);
if (info->hw_version > 1) {
input_abs_set_res(dev, ABS_MT_POSITION_X, info->x_res);
input_abs_set_res(dev, ABS_MT_POSITION_Y, info->y_res);
}
etd->y_max = y_max;
etd->width = width;
return 0;
}
struct elantech_attr_data {
size_t field_offset;
unsigned char reg;
};
/*
* Display a register value by reading a sysfs entry
*/
static ssize_t elantech_show_int_attr(struct psmouse *psmouse, void *data,
char *buf)
{
struct elantech_data *etd = psmouse->private;
struct elantech_attr_data *attr = data;
unsigned char *reg = (unsigned char *) etd + attr->field_offset;
int rc = 0;
if (attr->reg)
rc = elantech_read_reg(psmouse, attr->reg, reg);
return sprintf(buf, "0x%02x\n", (attr->reg && rc) ? -1 : *reg);
}
/*
* Write a register value by writing a sysfs entry
*/
static ssize_t elantech_set_int_attr(struct psmouse *psmouse,
void *data, const char *buf, size_t count)
{
struct elantech_data *etd = psmouse->private;
struct elantech_attr_data *attr = data;
unsigned char *reg = (unsigned char *) etd + attr->field_offset;
unsigned char value;
int err;
err = kstrtou8(buf, 16, &value);
if (err)
return err;
/* Do we need to preserve some bits for version 2 hardware too? */
if (etd->info.hw_version == 1) {
if (attr->reg == 0x10)
/* Force absolute mode always on */
value |= ETP_R10_ABSOLUTE_MODE;
else if (attr->reg == 0x11)
/* Force 4 byte mode always on */
value |= ETP_R11_4_BYTE_MODE;
}
if (!attr->reg || elantech_write_reg(psmouse, attr->reg, value) == 0)
*reg = value;
return count;
}
#define ELANTECH_INT_ATTR(_name, _register) \
static struct elantech_attr_data elantech_attr_##_name = { \
.field_offset = offsetof(struct elantech_data, _name), \
.reg = _register, \
}; \
PSMOUSE_DEFINE_ATTR(_name, 0644, \
&elantech_attr_##_name, \
elantech_show_int_attr, \
elantech_set_int_attr)
#define ELANTECH_INFO_ATTR(_name) \
static struct elantech_attr_data elantech_attr_##_name = { \
.field_offset = offsetof(struct elantech_data, info) + \
offsetof(struct elantech_device_info, _name), \
.reg = 0, \
}; \
PSMOUSE_DEFINE_ATTR(_name, 0644, \
&elantech_attr_##_name, \
elantech_show_int_attr, \
elantech_set_int_attr)
ELANTECH_INT_ATTR(reg_07, 0x07);
ELANTECH_INT_ATTR(reg_10, 0x10);
ELANTECH_INT_ATTR(reg_11, 0x11);
ELANTECH_INT_ATTR(reg_20, 0x20);
ELANTECH_INT_ATTR(reg_21, 0x21);
ELANTECH_INT_ATTR(reg_22, 0x22);
ELANTECH_INT_ATTR(reg_23, 0x23);
ELANTECH_INT_ATTR(reg_24, 0x24);
ELANTECH_INT_ATTR(reg_25, 0x25);
ELANTECH_INT_ATTR(reg_26, 0x26);
ELANTECH_INFO_ATTR(debug);
ELANTECH_INFO_ATTR(paritycheck);
ELANTECH_INFO_ATTR(crc_enabled);
static struct attribute *elantech_attrs[] = {
&psmouse_attr_reg_07.dattr.attr,
&psmouse_attr_reg_10.dattr.attr,
&psmouse_attr_reg_11.dattr.attr,
&psmouse_attr_reg_20.dattr.attr,
&psmouse_attr_reg_21.dattr.attr,
&psmouse_attr_reg_22.dattr.attr,
&psmouse_attr_reg_23.dattr.attr,
&psmouse_attr_reg_24.dattr.attr,
&psmouse_attr_reg_25.dattr.attr,
&psmouse_attr_reg_26.dattr.attr,
&psmouse_attr_debug.dattr.attr,
&psmouse_attr_paritycheck.dattr.attr,
&psmouse_attr_crc_enabled.dattr.attr,
NULL
};
static const struct attribute_group elantech_attr_group = {
.attrs = elantech_attrs,
};
static bool elantech_is_signature_valid(const unsigned char *param)
{
static const unsigned char rates[] = { 200, 100, 80, 60, 40, 20, 10 };
int i;
if (param[0] == 0)
return false;
if (param[1] == 0)
return true;
/*
* Some hw_version >= 4 models have a revision higher then 20. Meaning
* that param[2] may be 10 or 20, skip the rates check for these.
*/
if ((param[0] & 0x0f) >= 0x06 && (param[1] & 0xaf) == 0x0f &&
param[2] < 40)
return true;
for (i = 0; i < ARRAY_SIZE(rates); i++)
if (param[2] == rates[i])
return false;
return true;
}
/*
* Use magic knock to detect Elantech touchpad
*/
int elantech_detect(struct psmouse *psmouse, bool set_properties)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[3];
ps2_command(ps2dev, NULL, PSMOUSE_CMD_RESET_DIS);
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_DISABLE) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11) ||
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO)) {
psmouse_dbg(psmouse, "sending Elantech magic knock failed.\n");
return -1;
}
/*
* Report this in case there are Elantech models that use a different
* set of magic numbers
*/
if (param[0] != 0x3c || param[1] != 0x03 ||
(param[2] != 0xc8 && param[2] != 0x00)) {
psmouse_dbg(psmouse,
"unexpected magic knock result 0x%02x, 0x%02x, 0x%02x.\n",
param[0], param[1], param[2]);
return -1;
}
/*
* Query touchpad's firmware version and see if it reports known
* value to avoid mis-detection. Logitech mice are known to respond
* to Elantech magic knock and there might be more.
*/
if (synaptics_send_cmd(psmouse, ETP_FW_VERSION_QUERY, param)) {
psmouse_dbg(psmouse, "failed to query firmware version.\n");
return -1;
}
psmouse_dbg(psmouse,
"Elantech version query result 0x%02x, 0x%02x, 0x%02x.\n",
param[0], param[1], param[2]);
if (!elantech_is_signature_valid(param)) {
psmouse_dbg(psmouse,
"Probably not a real Elantech touchpad. Aborting.\n");
return -1;
}
if (set_properties) {
psmouse->vendor = "Elantech";
psmouse->name = "Touchpad";
}
return 0;
}
/*
* Clean up sysfs entries when disconnecting
*/
static void elantech_disconnect(struct psmouse *psmouse)
{
struct elantech_data *etd = psmouse->private;
/*
* We might have left a breadcrumb when trying to
* set up SMbus companion.
*/
psmouse_smbus_cleanup(psmouse);
if (etd->tp_dev)
input_unregister_device(etd->tp_dev);
sysfs_remove_group(&psmouse->ps2dev.serio->dev.kobj,
&elantech_attr_group);
kfree(psmouse->private);
psmouse->private = NULL;
}
/*
* Put the touchpad back into absolute mode when reconnecting
*/
static int elantech_reconnect(struct psmouse *psmouse)
{
psmouse_reset(psmouse);
if (elantech_detect(psmouse, 0))
return -1;
if (elantech_set_absolute_mode(psmouse)) {
psmouse_err(psmouse,
"failed to put touchpad back into absolute mode.\n");
return -1;
}
return 0;
}
/*
* Some hw_version 4 models do not work with crc_disabled
*/
static const struct dmi_system_id elantech_dmi_force_crc_enabled[] = {
#if defined(CONFIG_DMI) && defined(CONFIG_X86)
{
/* Fujitsu H730 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "CELSIUS H730"),
},
},
{
/* Fujitsu H760 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "CELSIUS H760"),
},
},
{
/* Fujitsu LIFEBOOK E544 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK E544"),
},
},
{
/* Fujitsu LIFEBOOK E546 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK E546"),
},
},
{
/* Fujitsu LIFEBOOK E547 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK E547"),
},
},
{
/* Fujitsu LIFEBOOK E554 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK E554"),
},
},
{
/* Fujitsu LIFEBOOK E556 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK E556"),
},
},
{
/* Fujitsu LIFEBOOK E557 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK E557"),
},
},
{
/* Fujitsu LIFEBOOK U745 does not work with crc_enabled == 0 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU"),
DMI_MATCH(DMI_PRODUCT_NAME, "LIFEBOOK U745"),
},
},
#endif
{ }
};
/*
* Some hw_version 3 models go into error state when we try to set
* bit 3 and/or bit 1 of r10.
*/
static const struct dmi_system_id no_hw_res_dmi_table[] = {
#if defined(CONFIG_DMI) && defined(CONFIG_X86)
{
/* Gigabyte U2442 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "GIGABYTE"),
DMI_MATCH(DMI_PRODUCT_NAME, "U2442"),
},
},
#endif
{ }
};
/*
* Change Report id 0x5E to 0x5F.
*/
static int elantech_change_report_id(struct psmouse *psmouse)
{
/*
* NOTE: the code is expecting to receive param[] as an array of 3
* items (see __ps2_command()), even if in this case only 2 are
* actually needed. Make sure the array size is 3 to avoid potential
* stack out-of-bound accesses.
*/
unsigned char param[3] = { 0x10, 0x03 };
if (elantech_write_reg_params(psmouse, 0x7, param) ||
elantech_read_reg_params(psmouse, 0x7, param) ||
param[0] != 0x10 || param[1] != 0x03) {
psmouse_err(psmouse, "Unable to change report ID to 0x5f.\n");
return -EIO;
}
return 0;
}
/*
* determine hardware version and set some properties according to it.
*/
static int elantech_set_properties(struct elantech_device_info *info)
{
/* This represents the version of IC body. */
info->ic_version = (info->fw_version & 0x0f0000) >> 16;
/* Early version of Elan touchpads doesn't obey the rule. */
if (info->fw_version < 0x020030 || info->fw_version == 0x020600)
info->hw_version = 1;
else {
switch (info->ic_version) {
case 2:
case 4:
info->hw_version = 2;
break;
case 5:
info->hw_version = 3;
break;
case 6 ... 15:
info->hw_version = 4;
break;
default:
return -1;
}
}
/* Get information pattern for hw_version 4 */
info->pattern = 0x00;
if (info->ic_version == 0x0f && (info->fw_version & 0xff) <= 0x02)
info->pattern = info->fw_version & 0xff;
/* decide which send_cmd we're gonna use early */
info->send_cmd = info->hw_version >= 3 ? elantech_send_cmd :
synaptics_send_cmd;
/* Turn on packet checking by default */
info->paritycheck = 1;
/*
* This firmware suffers from misreporting coordinates when
* a touch action starts causing the mouse cursor or scrolled page
* to jump. Enable a workaround.
*/
info->jumpy_cursor =
(info->fw_version == 0x020022 || info->fw_version == 0x020600);
if (info->hw_version > 1) {
/* For now show extra debug information */
info->debug = 1;
if (info->fw_version >= 0x020800)
info->reports_pressure = true;
}
/*
* The signatures of v3 and v4 packets change depending on the
* value of this hardware flag.
*/
info->crc_enabled = (info->fw_version & 0x4000) == 0x4000 ||
dmi_check_system(elantech_dmi_force_crc_enabled);
/* Enable real hardware resolution on hw_version 3 ? */
info->set_hw_resolution = !dmi_check_system(no_hw_res_dmi_table);
return 0;
}
static int elantech_query_info(struct psmouse *psmouse,
struct elantech_device_info *info)
{
unsigned char param[3];
unsigned char traces;
unsigned char ic_body[3];
memset(info, 0, sizeof(*info));
/*
* Do the version query again so we can store the result
*/
if (synaptics_send_cmd(psmouse, ETP_FW_VERSION_QUERY, param)) {
psmouse_err(psmouse, "failed to query firmware version.\n");
return -EINVAL;
}
info->fw_version = (param[0] << 16) | (param[1] << 8) | param[2];
if (elantech_set_properties(info)) {
psmouse_err(psmouse, "unknown hardware version, aborting...\n");
return -EINVAL;
}
psmouse_info(psmouse,
"assuming hardware version %d (with firmware version 0x%02x%02x%02x)\n",
info->hw_version, param[0], param[1], param[2]);
if (info->send_cmd(psmouse, ETP_CAPABILITIES_QUERY,
info->capabilities)) {
psmouse_err(psmouse, "failed to query capabilities.\n");
return -EINVAL;
}
psmouse_info(psmouse,
"Synaptics capabilities query result 0x%02x, 0x%02x, 0x%02x.\n",
info->capabilities[0], info->capabilities[1],
info->capabilities[2]);
if (info->hw_version != 1) {
if (info->send_cmd(psmouse, ETP_SAMPLE_QUERY, info->samples)) {
psmouse_err(psmouse, "failed to query sample data\n");
return -EINVAL;
}
psmouse_info(psmouse,
"Elan sample query result %02x, %02x, %02x\n",
info->samples[0],
info->samples[1],
info->samples[2]);
}
if (info->pattern > 0x00 && info->ic_version == 0xf) {
if (info->send_cmd(psmouse, ETP_ICBODY_QUERY, ic_body)) {
psmouse_err(psmouse, "failed to query ic body\n");
return -EINVAL;
}
info->ic_version = be16_to_cpup((__be16 *)ic_body);
psmouse_info(psmouse,
"Elan ic body: %#04x, current fw version: %#02x\n",
info->ic_version, ic_body[2]);
}
info->product_id = be16_to_cpup((__be16 *)info->samples);
if (info->pattern == 0x00)
info->product_id &= 0xff;
if (info->samples[1] == 0x74 && info->hw_version == 0x03) {
/*
* This module has a bug which makes absolute mode
* unusable, so let's abort so we'll be using standard
* PS/2 protocol.
*/
psmouse_info(psmouse,
"absolute mode broken, forcing standard PS/2 protocol\n");
return -ENODEV;
}
/* The MSB indicates the presence of the trackpoint */
info->has_trackpoint = (info->capabilities[0] & 0x80) == 0x80;
if (info->has_trackpoint && info->ic_version == 0x0011 &&
(info->product_id == 0x08 || info->product_id == 0x09 ||
info->product_id == 0x0d || info->product_id == 0x0e)) {
/*
* This module has a bug which makes trackpoint in SMBus
* mode return invalid data unless trackpoint is switched
* from using 0x5e reports to 0x5f. If we are not able to
* make the switch, let's abort initialization so we'll be
* using standard PS/2 protocol.
*/
if (elantech_change_report_id(psmouse)) {
psmouse_info(psmouse,
"Trackpoint report is broken, forcing standard PS/2 protocol\n");
return -ENODEV;
}
}
info->x_res = 31;
info->y_res = 31;
if (info->hw_version == 4) {
if (elantech_get_resolution_v4(psmouse,
&info->x_res,
&info->y_res,
&info->bus)) {
psmouse_warn(psmouse,
"failed to query resolution data.\n");
}
}
/* query range information */
switch (info->hw_version) {
case 1:
info->x_min = ETP_XMIN_V1;
info->y_min = ETP_YMIN_V1;
info->x_max = ETP_XMAX_V1;
info->y_max = ETP_YMAX_V1;
break;
case 2:
if (info->fw_version == 0x020800 ||
info->fw_version == 0x020b00 ||
info->fw_version == 0x020030) {
info->x_min = ETP_XMIN_V2;
info->y_min = ETP_YMIN_V2;
info->x_max = ETP_XMAX_V2;
info->y_max = ETP_YMAX_V2;
} else {
int i;
int fixed_dpi;
i = (info->fw_version > 0x020800 &&
info->fw_version < 0x020900) ? 1 : 2;
if (info->send_cmd(psmouse, ETP_FW_ID_QUERY, param))
return -EINVAL;
fixed_dpi = param[1] & 0x10;
if (((info->fw_version >> 16) == 0x14) && fixed_dpi) {
if (info->send_cmd(psmouse, ETP_SAMPLE_QUERY, param))
return -EINVAL;
info->x_max = (info->capabilities[1] - i) * param[1] / 2;
info->y_max = (info->capabilities[2] - i) * param[2] / 2;
} else if (info->fw_version == 0x040216) {
info->x_max = 819;
info->y_max = 405;
} else if (info->fw_version == 0x040219 || info->fw_version == 0x040215) {
info->x_max = 900;
info->y_max = 500;
} else {
info->x_max = (info->capabilities[1] - i) * 64;
info->y_max = (info->capabilities[2] - i) * 64;
}
}
break;
case 3:
if (info->send_cmd(psmouse, ETP_FW_ID_QUERY, param))
return -EINVAL;
info->x_max = (0x0f & param[0]) << 8 | param[1];
info->y_max = (0xf0 & param[0]) << 4 | param[2];
break;
case 4:
if (info->send_cmd(psmouse, ETP_FW_ID_QUERY, param))
return -EINVAL;
info->x_max = (0x0f & param[0]) << 8 | param[1];
info->y_max = (0xf0 & param[0]) << 4 | param[2];
traces = info->capabilities[1];
if ((traces < 2) || (traces > info->x_max))
return -EINVAL;
info->width = info->x_max / (traces - 1);
/* column number of traces */
info->x_traces = traces;
/* row number of traces */
traces = info->capabilities[2];
if ((traces >= 2) && (traces <= info->y_max))
info->y_traces = traces;
break;
}
/* check for the middle button: DMI matching or new v4 firmwares */
info->has_middle_button = dmi_check_system(elantech_dmi_has_middle_button) ||
(ETP_NEW_IC_SMBUS_HOST_NOTIFY(info->fw_version) &&
!elantech_is_buttonpad(info));
return 0;
}
#if defined(CONFIG_MOUSE_PS2_ELANTECH_SMBUS)
/*
* The newest Elantech device can use a secondary bus (over SMBus) which
* provides a better bandwidth and allow a better control of the touchpads.
* This is used to decide if we need to use this bus or not.
*/
enum {
ELANTECH_SMBUS_NOT_SET = -1,
ELANTECH_SMBUS_OFF,
ELANTECH_SMBUS_ON,
};
static int elantech_smbus = IS_ENABLED(CONFIG_MOUSE_ELAN_I2C_SMBUS) ?
ELANTECH_SMBUS_NOT_SET : ELANTECH_SMBUS_OFF;
module_param_named(elantech_smbus, elantech_smbus, int, 0644);
MODULE_PARM_DESC(elantech_smbus, "Use a secondary bus for the Elantech device.");
static const char * const i2c_blacklist_pnp_ids[] = {
/*
* These are known to not be working properly as bits are missing
* in elan_i2c.
*/
NULL
};
static int elantech_create_smbus(struct psmouse *psmouse,
struct elantech_device_info *info,
bool leave_breadcrumbs)
{
struct property_entry i2c_props[11] = {};
struct i2c_board_info smbus_board = {
I2C_BOARD_INFO("elan_i2c", 0x15),
.flags = I2C_CLIENT_HOST_NOTIFY,
};
unsigned int idx = 0;
i2c_props[idx++] = PROPERTY_ENTRY_U32("touchscreen-size-x",
info->x_max + 1);
i2c_props[idx++] = PROPERTY_ENTRY_U32("touchscreen-size-y",
info->y_max + 1);
i2c_props[idx++] = PROPERTY_ENTRY_U32("touchscreen-min-x",
info->x_min);
i2c_props[idx++] = PROPERTY_ENTRY_U32("touchscreen-min-y",
info->y_min);
if (info->x_res)
i2c_props[idx++] = PROPERTY_ENTRY_U32("touchscreen-x-mm",
(info->x_max + 1) / info->x_res);
if (info->y_res)
i2c_props[idx++] = PROPERTY_ENTRY_U32("touchscreen-y-mm",
(info->y_max + 1) / info->y_res);
if (info->has_trackpoint)
i2c_props[idx++] = PROPERTY_ENTRY_BOOL("elan,trackpoint");
if (info->has_middle_button)
i2c_props[idx++] = PROPERTY_ENTRY_BOOL("elan,middle-button");
if (info->x_traces)
i2c_props[idx++] = PROPERTY_ENTRY_U32("elan,x_traces",
info->x_traces);
if (info->y_traces)
i2c_props[idx++] = PROPERTY_ENTRY_U32("elan,y_traces",
info->y_traces);
if (elantech_is_buttonpad(info))
i2c_props[idx++] = PROPERTY_ENTRY_BOOL("elan,clickpad");
smbus_board.fwnode = fwnode_create_software_node(i2c_props, NULL);
if (IS_ERR(smbus_board.fwnode))
return PTR_ERR(smbus_board.fwnode);
return psmouse_smbus_init(psmouse, &smbus_board, NULL, 0, false,
leave_breadcrumbs);
}
/*
* elantech_setup_smbus - called once the PS/2 devices are enumerated
* and decides to instantiate a SMBus InterTouch device.
*/
static int elantech_setup_smbus(struct psmouse *psmouse,
struct elantech_device_info *info,
bool leave_breadcrumbs)
{
int error;
if (elantech_smbus == ELANTECH_SMBUS_OFF)
return -ENXIO;
if (elantech_smbus == ELANTECH_SMBUS_NOT_SET) {
/*
* New ICs are enabled by default, unless mentioned in
* i2c_blacklist_pnp_ids.
* Old ICs are up to the user to decide.
*/
if (!ETP_NEW_IC_SMBUS_HOST_NOTIFY(info->fw_version) ||
psmouse_matches_pnp_id(psmouse, i2c_blacklist_pnp_ids))
return -ENXIO;
}
psmouse_info(psmouse, "Trying to set up SMBus access\n");
error = elantech_create_smbus(psmouse, info, leave_breadcrumbs);
if (error) {
if (error == -EAGAIN)
psmouse_info(psmouse, "SMbus companion is not ready yet\n");
else
psmouse_err(psmouse, "unable to create intertouch device\n");
return error;
}
return 0;
}
static bool elantech_use_host_notify(struct psmouse *psmouse,
struct elantech_device_info *info)
{
if (ETP_NEW_IC_SMBUS_HOST_NOTIFY(info->fw_version))
return true;
switch (info->bus) {
case ETP_BUS_PS2_ONLY:
/* expected case */
break;
case ETP_BUS_SMB_ALERT_ONLY:
case ETP_BUS_PS2_SMB_ALERT:
psmouse_dbg(psmouse, "Ignoring SMBus provider through alert protocol.\n");
break;
case ETP_BUS_SMB_HST_NTFY_ONLY:
case ETP_BUS_PS2_SMB_HST_NTFY:
return true;
default:
psmouse_dbg(psmouse,
"Ignoring SMBus bus provider %d.\n",
info->bus);
}
return false;
}
int elantech_init_smbus(struct psmouse *psmouse)
{
struct elantech_device_info info;
int error;
psmouse_reset(psmouse);
error = elantech_query_info(psmouse, &info);
if (error)
goto init_fail;
if (info.hw_version < 4) {
error = -ENXIO;
goto init_fail;
}
return elantech_create_smbus(psmouse, &info, false);
init_fail:
psmouse_reset(psmouse);
return error;
}
#endif /* CONFIG_MOUSE_PS2_ELANTECH_SMBUS */
/*
* Initialize the touchpad and create sysfs entries
*/
static int elantech_setup_ps2(struct psmouse *psmouse,
struct elantech_device_info *info)
{
struct elantech_data *etd;
int i;
int error = -EINVAL;
struct input_dev *tp_dev;
psmouse->private = etd = kzalloc(sizeof(*etd), GFP_KERNEL);
if (!etd)
return -ENOMEM;
etd->info = *info;
etd->parity[0] = 1;
for (i = 1; i < 256; i++)
etd->parity[i] = etd->parity[i & (i - 1)] ^ 1;
if (elantech_set_absolute_mode(psmouse)) {
psmouse_err(psmouse,
"failed to put touchpad into absolute mode.\n");
goto init_fail;
}
if (info->fw_version == 0x381f17) {
etd->original_set_rate = psmouse->set_rate;
psmouse->set_rate = elantech_set_rate_restore_reg_07;
}
if (elantech_set_input_params(psmouse)) {
psmouse_err(psmouse, "failed to query touchpad range.\n");
goto init_fail;
}
error = sysfs_create_group(&psmouse->ps2dev.serio->dev.kobj,
&elantech_attr_group);
if (error) {
psmouse_err(psmouse,
"failed to create sysfs attributes, error: %d.\n",
error);
goto init_fail;
}
if (info->has_trackpoint) {
tp_dev = input_allocate_device();
if (!tp_dev) {
error = -ENOMEM;
goto init_fail_tp_alloc;
}
etd->tp_dev = tp_dev;
snprintf(etd->tp_phys, sizeof(etd->tp_phys), "%s/input1",
psmouse->ps2dev.serio->phys);
tp_dev->phys = etd->tp_phys;
tp_dev->name = "ETPS/2 Elantech TrackPoint";
tp_dev->id.bustype = BUS_I8042;
tp_dev->id.vendor = 0x0002;
tp_dev->id.product = PSMOUSE_ELANTECH;
tp_dev->id.version = 0x0000;
tp_dev->dev.parent = &psmouse->ps2dev.serio->dev;
tp_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
tp_dev->relbit[BIT_WORD(REL_X)] =
BIT_MASK(REL_X) | BIT_MASK(REL_Y);
tp_dev->keybit[BIT_WORD(BTN_LEFT)] =
BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE) |
BIT_MASK(BTN_RIGHT);
__set_bit(INPUT_PROP_POINTER, tp_dev->propbit);
__set_bit(INPUT_PROP_POINTING_STICK, tp_dev->propbit);
error = input_register_device(etd->tp_dev);
if (error < 0)
goto init_fail_tp_reg;
}
psmouse->protocol_handler = elantech_process_byte;
psmouse->disconnect = elantech_disconnect;
psmouse->reconnect = elantech_reconnect;
psmouse->pktsize = info->hw_version > 1 ? 6 : 4;
return 0;
init_fail_tp_reg:
input_free_device(tp_dev);
init_fail_tp_alloc:
sysfs_remove_group(&psmouse->ps2dev.serio->dev.kobj,
&elantech_attr_group);
init_fail:
kfree(etd);
return error;
}
int elantech_init_ps2(struct psmouse *psmouse)
{
struct elantech_device_info info;
int error;
psmouse_reset(psmouse);
error = elantech_query_info(psmouse, &info);
if (error)
goto init_fail;
error = elantech_setup_ps2(psmouse, &info);
if (error)
goto init_fail;
return 0;
init_fail:
psmouse_reset(psmouse);
return error;
}
int elantech_init(struct psmouse *psmouse)
{
struct elantech_device_info info;
int error;
psmouse_reset(psmouse);
error = elantech_query_info(psmouse, &info);
if (error)
goto init_fail;
#if defined(CONFIG_MOUSE_PS2_ELANTECH_SMBUS)
if (elantech_use_host_notify(psmouse, &info)) {
if (!IS_ENABLED(CONFIG_MOUSE_ELAN_I2C_SMBUS) ||
!IS_ENABLED(CONFIG_MOUSE_PS2_ELANTECH_SMBUS)) {
psmouse_warn(psmouse,
"The touchpad can support a better bus than the too old PS/2 protocol. "
"Make sure MOUSE_PS2_ELANTECH_SMBUS and MOUSE_ELAN_I2C_SMBUS are enabled to get a better touchpad experience.\n");
}
error = elantech_setup_smbus(psmouse, &info, true);
if (!error)
return PSMOUSE_ELANTECH_SMBUS;
}
#endif /* CONFIG_MOUSE_PS2_ELANTECH_SMBUS */
error = elantech_setup_ps2(psmouse, &info);
if (error < 0) {
/*
* Not using any flavor of Elantech support, so clean up
* SMbus breadcrumbs, if any.
*/
psmouse_smbus_cleanup(psmouse);
goto init_fail;
}
return PSMOUSE_ELANTECH;
init_fail:
psmouse_reset(psmouse);
return error;
}
|
linux-master
|
drivers/input/mouse/elantech.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* SEGA Dreamcast mouse driver
* Based on drivers/usb/usbmouse.c
*
* Copyright (c) Yaegashi Takeshi, 2001
* Copyright (c) Adrian McMenamin, 2008 - 2009
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/maple.h>
MODULE_AUTHOR("Adrian McMenamin <[email protected]>");
MODULE_DESCRIPTION("SEGA Dreamcast mouse driver");
MODULE_LICENSE("GPL");
struct dc_mouse {
struct input_dev *dev;
struct maple_device *mdev;
};
static void dc_mouse_callback(struct mapleq *mq)
{
int buttons, relx, rely, relz;
struct maple_device *mapledev = mq->dev;
struct dc_mouse *mse = maple_get_drvdata(mapledev);
struct input_dev *dev = mse->dev;
unsigned char *res = mq->recvbuf->buf;
buttons = ~res[8];
relx = *(unsigned short *)(res + 12) - 512;
rely = *(unsigned short *)(res + 14) - 512;
relz = *(unsigned short *)(res + 16) - 512;
input_report_key(dev, BTN_LEFT, buttons & 4);
input_report_key(dev, BTN_MIDDLE, buttons & 9);
input_report_key(dev, BTN_RIGHT, buttons & 2);
input_report_rel(dev, REL_X, relx);
input_report_rel(dev, REL_Y, rely);
input_report_rel(dev, REL_WHEEL, relz);
input_sync(dev);
}
static int dc_mouse_open(struct input_dev *dev)
{
struct dc_mouse *mse = maple_get_drvdata(to_maple_dev(&dev->dev));
maple_getcond_callback(mse->mdev, dc_mouse_callback, HZ/50,
MAPLE_FUNC_MOUSE);
return 0;
}
static void dc_mouse_close(struct input_dev *dev)
{
struct dc_mouse *mse = maple_get_drvdata(to_maple_dev(&dev->dev));
maple_getcond_callback(mse->mdev, dc_mouse_callback, 0,
MAPLE_FUNC_MOUSE);
}
/* allow the mouse to be used */
static int probe_maple_mouse(struct device *dev)
{
struct maple_device *mdev = to_maple_dev(dev);
struct maple_driver *mdrv = to_maple_driver(dev->driver);
int error;
struct input_dev *input_dev;
struct dc_mouse *mse;
mse = kzalloc(sizeof(struct dc_mouse), GFP_KERNEL);
if (!mse) {
error = -ENOMEM;
goto fail;
}
input_dev = input_allocate_device();
if (!input_dev) {
error = -ENOMEM;
goto fail_nomem;
}
mse->dev = input_dev;
mse->mdev = mdev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE);
input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y) |
BIT_MASK(REL_WHEEL);
input_dev->open = dc_mouse_open;
input_dev->close = dc_mouse_close;
input_dev->name = mdev->product_name;
input_dev->id.bustype = BUS_HOST;
error = input_register_device(input_dev);
if (error)
goto fail_register;
mdev->driver = mdrv;
maple_set_drvdata(mdev, mse);
return error;
fail_register:
input_free_device(input_dev);
fail_nomem:
kfree(mse);
fail:
return error;
}
static int remove_maple_mouse(struct device *dev)
{
struct maple_device *mdev = to_maple_dev(dev);
struct dc_mouse *mse = maple_get_drvdata(mdev);
mdev->callback = NULL;
input_unregister_device(mse->dev);
maple_set_drvdata(mdev, NULL);
kfree(mse);
return 0;
}
static struct maple_driver dc_mouse_driver = {
.function = MAPLE_FUNC_MOUSE,
.drv = {
.name = "Dreamcast_mouse",
.probe = probe_maple_mouse,
.remove = remove_maple_mouse,
},
};
static int __init dc_mouse_init(void)
{
return maple_driver_register(&dc_mouse_driver);
}
static void __exit dc_mouse_exit(void)
{
maple_driver_unregister(&dc_mouse_driver);
}
module_init(dc_mouse_init);
module_exit(dc_mouse_exit);
|
linux-master
|
drivers/input/mouse/maplemouse.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Atari mouse driver for Linux/m68k
*
* Copyright (c) 2005 Michael Schmitz
*
* Based on:
* Amiga mouse driver for Linux/m68k
*
* Copyright (c) 2000-2002 Vojtech Pavlik
*/
/*
* The low level init and interrupt stuff is handled in arch/mm68k/atari/atakeyb.c
* (the keyboard ACIA also handles the mouse and joystick data, and the keyboard
* interrupt is shared with the MIDI ACIA so MIDI data also get handled there).
* This driver only deals with handing key events off to the input layer.
*
* Largely based on the old:
*
* Atari Mouse Driver for Linux
* by Robert de Vries ([email protected]) 19Jul93
*
* 16 Nov 1994 Andreas Schwab
* Compatibility with busmouse
* Support for three button mouse (shamelessly stolen from MiNT)
* third button wired to one of the joystick directions on joystick 1
*
* 1996/02/11 Andreas Schwab
* Module support
* Allow multiple open's
*
* Converted to use new generic busmouse code. 5 Apr 1998
* Russell King <[email protected]>
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <asm/irq.h>
#include <asm/setup.h>
#include <linux/uaccess.h>
#include <asm/atarihw.h>
#include <asm/atarikb.h>
#include <asm/atariints.h>
MODULE_AUTHOR("Michael Schmitz <[email protected]>");
MODULE_DESCRIPTION("Atari mouse driver");
MODULE_LICENSE("GPL");
static int mouse_threshold[2] = {2, 2};
module_param_array(mouse_threshold, int, NULL, 0);
#ifdef FIXED_ATARI_JOYSTICK
extern int atari_mouse_buttons;
#endif
static struct input_dev *atamouse_dev;
static void atamouse_interrupt(char *buf)
{
int buttons, dx, dy;
buttons = (buf[0] & 1) | ((buf[0] & 2) << 1);
#ifdef FIXED_ATARI_JOYSTICK
buttons |= atari_mouse_buttons & 2;
atari_mouse_buttons = buttons;
#endif
/* only relative events get here */
dx = buf[1];
dy = buf[2];
input_report_rel(atamouse_dev, REL_X, dx);
input_report_rel(atamouse_dev, REL_Y, dy);
input_report_key(atamouse_dev, BTN_LEFT, buttons & 0x4);
input_report_key(atamouse_dev, BTN_MIDDLE, buttons & 0x2);
input_report_key(atamouse_dev, BTN_RIGHT, buttons & 0x1);
input_sync(atamouse_dev);
return;
}
static int atamouse_open(struct input_dev *dev)
{
#ifdef FIXED_ATARI_JOYSTICK
atari_mouse_buttons = 0;
#endif
ikbd_mouse_y0_top();
ikbd_mouse_thresh(mouse_threshold[0], mouse_threshold[1]);
ikbd_mouse_rel_pos();
atari_input_mouse_interrupt_hook = atamouse_interrupt;
return 0;
}
static void atamouse_close(struct input_dev *dev)
{
ikbd_mouse_disable();
atari_input_mouse_interrupt_hook = NULL;
}
static int __init atamouse_init(void)
{
int error;
if (!MACH_IS_ATARI || !ATARIHW_PRESENT(ST_MFP))
return -ENODEV;
error = atari_keyb_init();
if (error)
return error;
atamouse_dev = input_allocate_device();
if (!atamouse_dev)
return -ENOMEM;
atamouse_dev->name = "Atari mouse";
atamouse_dev->phys = "atamouse/input0";
atamouse_dev->id.bustype = BUS_HOST;
atamouse_dev->id.vendor = 0x0001;
atamouse_dev->id.product = 0x0002;
atamouse_dev->id.version = 0x0100;
atamouse_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
atamouse_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
atamouse_dev->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT);
atamouse_dev->open = atamouse_open;
atamouse_dev->close = atamouse_close;
error = input_register_device(atamouse_dev);
if (error) {
input_free_device(atamouse_dev);
return error;
}
return 0;
}
static void __exit atamouse_exit(void)
{
input_unregister_device(atamouse_dev);
}
module_init(atamouse_init);
module_exit(atamouse_exit);
|
linux-master
|
drivers/input/mouse/atarimouse.c
|
/*
* Cypress APA trackpad with I2C interface
*
* Author: Dudley Du <[email protected]>
* Further cleanup and restructuring by:
* Daniel Kurtz <[email protected]>
* Benson Leung <[email protected]>
*
* Copyright (C) 2011-2015 Cypress Semiconductor, Inc.
* Copyright (C) 2011-2012 Google, Inc.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/mt.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/pm_runtime.h>
#include <linux/acpi.h>
#include <linux/of.h>
#include "cyapa.h"
#define CYAPA_ADAPTER_FUNC_NONE 0
#define CYAPA_ADAPTER_FUNC_I2C 1
#define CYAPA_ADAPTER_FUNC_SMBUS 2
#define CYAPA_ADAPTER_FUNC_BOTH 3
#define CYAPA_FW_NAME "cyapa.bin"
const char product_id[] = "CYTRA";
static int cyapa_reinitialize(struct cyapa *cyapa);
bool cyapa_is_pip_bl_mode(struct cyapa *cyapa)
{
if (cyapa->gen == CYAPA_GEN6 && cyapa->state == CYAPA_STATE_GEN6_BL)
return true;
if (cyapa->gen == CYAPA_GEN5 && cyapa->state == CYAPA_STATE_GEN5_BL)
return true;
return false;
}
bool cyapa_is_pip_app_mode(struct cyapa *cyapa)
{
if (cyapa->gen == CYAPA_GEN6 && cyapa->state == CYAPA_STATE_GEN6_APP)
return true;
if (cyapa->gen == CYAPA_GEN5 && cyapa->state == CYAPA_STATE_GEN5_APP)
return true;
return false;
}
static bool cyapa_is_bootloader_mode(struct cyapa *cyapa)
{
if (cyapa_is_pip_bl_mode(cyapa))
return true;
if (cyapa->gen == CYAPA_GEN3 &&
cyapa->state >= CYAPA_STATE_BL_BUSY &&
cyapa->state <= CYAPA_STATE_BL_ACTIVE)
return true;
return false;
}
static inline bool cyapa_is_operational_mode(struct cyapa *cyapa)
{
if (cyapa_is_pip_app_mode(cyapa))
return true;
if (cyapa->gen == CYAPA_GEN3 && cyapa->state == CYAPA_STATE_OP)
return true;
return false;
}
/* Returns 0 on success, else negative errno on failure. */
static ssize_t cyapa_i2c_read(struct cyapa *cyapa, u8 reg, size_t len,
u8 *values)
{
struct i2c_client *client = cyapa->client;
struct i2c_msg msgs[] = {
{
.addr = client->addr,
.flags = 0,
.len = 1,
.buf = ®,
},
{
.addr = client->addr,
.flags = I2C_M_RD,
.len = len,
.buf = values,
},
};
int ret;
ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
if (ret != ARRAY_SIZE(msgs))
return ret < 0 ? ret : -EIO;
return 0;
}
/**
* cyapa_i2c_write - Execute i2c block data write operation
* @cyapa: Handle to this driver
* @reg: Offset of the data to written in the register map
* @len: number of bytes to write
* @values: Data to be written
*
* Return negative errno code on error; return zero when success.
*/
static int cyapa_i2c_write(struct cyapa *cyapa, u8 reg,
size_t len, const void *values)
{
struct i2c_client *client = cyapa->client;
char buf[32];
int ret;
if (len > sizeof(buf) - 1)
return -ENOMEM;
buf[0] = reg;
memcpy(&buf[1], values, len);
ret = i2c_master_send(client, buf, len + 1);
if (ret != len + 1)
return ret < 0 ? ret : -EIO;
return 0;
}
static u8 cyapa_check_adapter_functionality(struct i2c_client *client)
{
u8 ret = CYAPA_ADAPTER_FUNC_NONE;
if (i2c_check_functionality(client->adapter, I2C_FUNC_I2C))
ret |= CYAPA_ADAPTER_FUNC_I2C;
if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA |
I2C_FUNC_SMBUS_BLOCK_DATA |
I2C_FUNC_SMBUS_I2C_BLOCK))
ret |= CYAPA_ADAPTER_FUNC_SMBUS;
return ret;
}
/*
* Query device for its current operating state.
*/
static int cyapa_get_state(struct cyapa *cyapa)
{
u8 status[BL_STATUS_SIZE];
u8 cmd[32];
/* The i2c address of gen4 and gen5 trackpad device must be even. */
bool even_addr = ((cyapa->client->addr & 0x0001) == 0);
bool smbus = false;
int retries = 2;
int error;
cyapa->state = CYAPA_STATE_NO_DEVICE;
/*
* Get trackpad status by reading 3 registers starting from 0.
* If the device is in the bootloader, this will be BL_HEAD.
* If the device is in operation mode, this will be the DATA regs.
*
*/
error = cyapa_i2c_reg_read_block(cyapa, BL_HEAD_OFFSET, BL_STATUS_SIZE,
status);
/*
* On smbus systems in OP mode, the i2c_reg_read will fail with
* -ETIMEDOUT. In this case, try again using the smbus equivalent
* command. This should return a BL_HEAD indicating CYAPA_STATE_OP.
*/
if (cyapa->smbus && (error == -ETIMEDOUT || error == -ENXIO)) {
if (!even_addr)
error = cyapa_read_block(cyapa,
CYAPA_CMD_BL_STATUS, status);
smbus = true;
}
if (error != BL_STATUS_SIZE)
goto error;
/*
* Detect trackpad protocol based on characteristic registers and bits.
*/
do {
cyapa->status[REG_OP_STATUS] = status[REG_OP_STATUS];
cyapa->status[REG_BL_STATUS] = status[REG_BL_STATUS];
cyapa->status[REG_BL_ERROR] = status[REG_BL_ERROR];
if (cyapa->gen == CYAPA_GEN_UNKNOWN ||
cyapa->gen == CYAPA_GEN3) {
error = cyapa_gen3_ops.state_parse(cyapa,
status, BL_STATUS_SIZE);
if (!error)
goto out_detected;
}
if (cyapa->gen == CYAPA_GEN_UNKNOWN ||
cyapa->gen == CYAPA_GEN6 ||
cyapa->gen == CYAPA_GEN5) {
error = cyapa_pip_state_parse(cyapa,
status, BL_STATUS_SIZE);
if (!error)
goto out_detected;
}
/* For old Gen5 trackpads detecting. */
if ((cyapa->gen == CYAPA_GEN_UNKNOWN ||
cyapa->gen == CYAPA_GEN5) &&
!smbus && even_addr) {
error = cyapa_gen5_ops.state_parse(cyapa,
status, BL_STATUS_SIZE);
if (!error)
goto out_detected;
}
/*
* Write 0x00 0x00 to trackpad device to force update its
* status, then redo the detection again.
*/
if (!smbus) {
cmd[0] = 0x00;
cmd[1] = 0x00;
error = cyapa_i2c_write(cyapa, 0, 2, cmd);
if (error)
goto error;
msleep(50);
error = cyapa_i2c_read(cyapa, BL_HEAD_OFFSET,
BL_STATUS_SIZE, status);
if (error)
goto error;
}
} while (--retries > 0 && !smbus);
goto error;
out_detected:
if (cyapa->state <= CYAPA_STATE_BL_BUSY)
return -EAGAIN;
return 0;
error:
return (error < 0) ? error : -EAGAIN;
}
/*
* Poll device for its status in a loop, waiting up to timeout for a response.
*
* When the device switches state, it usually takes ~300 ms.
* However, when running a new firmware image, the device must calibrate its
* sensors, which can take as long as 2 seconds.
*
* Note: The timeout has granularity of the polling rate, which is 100 ms.
*
* Returns:
* 0 when the device eventually responds with a valid non-busy state.
* -ETIMEDOUT if device never responds (too many -EAGAIN)
* -EAGAIN if bootload is busy, or unknown state.
* < 0 other errors
*/
int cyapa_poll_state(struct cyapa *cyapa, unsigned int timeout)
{
int error;
int tries = timeout / 100;
do {
error = cyapa_get_state(cyapa);
if (!error && cyapa->state > CYAPA_STATE_BL_BUSY)
return 0;
msleep(100);
} while (tries--);
return (error == -EAGAIN || error == -ETIMEDOUT) ? -ETIMEDOUT : error;
}
/*
* Check if device is operational.
*
* An operational device is responding, has exited bootloader, and has
* firmware supported by this driver.
*
* Returns:
* -ENODEV no device
* -EBUSY no device or in bootloader
* -EIO failure while reading from device
* -ETIMEDOUT timeout failure for bus idle or bus no response
* -EAGAIN device is still in bootloader
* if ->state = CYAPA_STATE_BL_IDLE, device has invalid firmware
* -EINVAL device is in operational mode, but not supported by this driver
* 0 device is supported
*/
static int cyapa_check_is_operational(struct cyapa *cyapa)
{
int error;
error = cyapa_poll_state(cyapa, 4000);
if (error)
return error;
switch (cyapa->gen) {
case CYAPA_GEN6:
cyapa->ops = &cyapa_gen6_ops;
break;
case CYAPA_GEN5:
cyapa->ops = &cyapa_gen5_ops;
break;
case CYAPA_GEN3:
cyapa->ops = &cyapa_gen3_ops;
break;
default:
return -ENODEV;
}
error = cyapa->ops->operational_check(cyapa);
if (!error && cyapa_is_operational_mode(cyapa))
cyapa->operational = true;
else
cyapa->operational = false;
return error;
}
/*
* Returns 0 on device detected, negative errno on no device detected.
* And when the device is detected and operational, it will be reset to
* full power active mode automatically.
*/
static int cyapa_detect(struct cyapa *cyapa)
{
struct device *dev = &cyapa->client->dev;
int error;
error = cyapa_check_is_operational(cyapa);
if (error) {
if (error != -ETIMEDOUT && error != -ENODEV &&
cyapa_is_bootloader_mode(cyapa)) {
dev_warn(dev, "device detected but not operational\n");
return 0;
}
dev_err(dev, "no device detected: %d\n", error);
return error;
}
return 0;
}
static int cyapa_open(struct input_dev *input)
{
struct cyapa *cyapa = input_get_drvdata(input);
struct i2c_client *client = cyapa->client;
struct device *dev = &client->dev;
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
if (cyapa->operational) {
/*
* though failed to set active power mode,
* but still may be able to work in lower scan rate
* when in operational mode.
*/
error = cyapa->ops->set_power_mode(cyapa,
PWR_MODE_FULL_ACTIVE, 0, CYAPA_PM_ACTIVE);
if (error) {
dev_warn(dev, "set active power failed: %d\n", error);
goto out;
}
} else {
error = cyapa_reinitialize(cyapa);
if (error || !cyapa->operational) {
error = error ? error : -EAGAIN;
goto out;
}
}
enable_irq(client->irq);
if (!pm_runtime_enabled(dev)) {
pm_runtime_set_active(dev);
pm_runtime_enable(dev);
}
pm_runtime_get_sync(dev);
pm_runtime_mark_last_busy(dev);
pm_runtime_put_sync_autosuspend(dev);
out:
mutex_unlock(&cyapa->state_sync_lock);
return error;
}
static void cyapa_close(struct input_dev *input)
{
struct cyapa *cyapa = input_get_drvdata(input);
struct i2c_client *client = cyapa->client;
struct device *dev = &cyapa->client->dev;
mutex_lock(&cyapa->state_sync_lock);
disable_irq(client->irq);
if (pm_runtime_enabled(dev))
pm_runtime_disable(dev);
pm_runtime_set_suspended(dev);
if (cyapa->operational)
cyapa->ops->set_power_mode(cyapa,
PWR_MODE_OFF, 0, CYAPA_PM_DEACTIVE);
mutex_unlock(&cyapa->state_sync_lock);
}
static int cyapa_create_input_dev(struct cyapa *cyapa)
{
struct device *dev = &cyapa->client->dev;
struct input_dev *input;
int error;
if (!cyapa->physical_size_x || !cyapa->physical_size_y)
return -EINVAL;
input = devm_input_allocate_device(dev);
if (!input) {
dev_err(dev, "failed to allocate memory for input device.\n");
return -ENOMEM;
}
input->name = CYAPA_NAME;
input->phys = cyapa->phys;
input->id.bustype = BUS_I2C;
input->id.version = 1;
input->id.product = 0; /* Means any product in eventcomm. */
input->dev.parent = &cyapa->client->dev;
input->open = cyapa_open;
input->close = cyapa_close;
input_set_drvdata(input, cyapa);
__set_bit(EV_ABS, input->evbit);
/* Finger position */
input_set_abs_params(input, ABS_MT_POSITION_X, 0, cyapa->max_abs_x, 0,
0);
input_set_abs_params(input, ABS_MT_POSITION_Y, 0, cyapa->max_abs_y, 0,
0);
input_set_abs_params(input, ABS_MT_PRESSURE, 0, cyapa->max_z, 0, 0);
if (cyapa->gen > CYAPA_GEN3) {
input_set_abs_params(input, ABS_MT_TOUCH_MAJOR, 0, 255, 0, 0);
input_set_abs_params(input, ABS_MT_TOUCH_MINOR, 0, 255, 0, 0);
/*
* Orientation is the angle between the vertical axis and
* the major axis of the contact ellipse.
* The range is -127 to 127.
* the positive direction is clockwise form the vertical axis.
* If the ellipse of contact degenerates into a circle,
* orientation is reported as 0.
*
* Also, for Gen5 trackpad the accurate of this orientation
* value is value + (-30 ~ 30).
*/
input_set_abs_params(input, ABS_MT_ORIENTATION,
-127, 127, 0, 0);
}
if (cyapa->gen >= CYAPA_GEN5) {
input_set_abs_params(input, ABS_MT_WIDTH_MAJOR, 0, 255, 0, 0);
input_set_abs_params(input, ABS_MT_WIDTH_MINOR, 0, 255, 0, 0);
input_set_abs_params(input, ABS_DISTANCE, 0, 1, 0, 0);
}
input_abs_set_res(input, ABS_MT_POSITION_X,
cyapa->max_abs_x / cyapa->physical_size_x);
input_abs_set_res(input, ABS_MT_POSITION_Y,
cyapa->max_abs_y / cyapa->physical_size_y);
if (cyapa->btn_capability & CAPABILITY_LEFT_BTN_MASK)
__set_bit(BTN_LEFT, input->keybit);
if (cyapa->btn_capability & CAPABILITY_MIDDLE_BTN_MASK)
__set_bit(BTN_MIDDLE, input->keybit);
if (cyapa->btn_capability & CAPABILITY_RIGHT_BTN_MASK)
__set_bit(BTN_RIGHT, input->keybit);
if (cyapa->btn_capability == CAPABILITY_LEFT_BTN_MASK)
__set_bit(INPUT_PROP_BUTTONPAD, input->propbit);
/* Handle pointer emulation and unused slots in core */
error = input_mt_init_slots(input, CYAPA_MAX_MT_SLOTS,
INPUT_MT_POINTER | INPUT_MT_DROP_UNUSED);
if (error) {
dev_err(dev, "failed to initialize MT slots: %d\n", error);
return error;
}
/* Register the device in input subsystem */
error = input_register_device(input);
if (error) {
dev_err(dev, "failed to register input device: %d\n", error);
return error;
}
cyapa->input = input;
return 0;
}
static void cyapa_enable_irq_for_cmd(struct cyapa *cyapa)
{
struct input_dev *input = cyapa->input;
if (!input || !input_device_enabled(input)) {
/*
* When input is NULL, TP must be in deep sleep mode.
* In this mode, later non-power I2C command will always failed
* if not bring it out of deep sleep mode firstly,
* so must command TP to active mode here.
*/
if (!input || cyapa->operational)
cyapa->ops->set_power_mode(cyapa,
PWR_MODE_FULL_ACTIVE, 0, CYAPA_PM_ACTIVE);
/* Gen3 always using polling mode for command. */
if (cyapa->gen >= CYAPA_GEN5)
enable_irq(cyapa->client->irq);
}
}
static void cyapa_disable_irq_for_cmd(struct cyapa *cyapa)
{
struct input_dev *input = cyapa->input;
if (!input || !input_device_enabled(input)) {
if (cyapa->gen >= CYAPA_GEN5)
disable_irq(cyapa->client->irq);
if (!input || cyapa->operational)
cyapa->ops->set_power_mode(cyapa,
PWR_MODE_OFF, 0, CYAPA_PM_ACTIVE);
}
}
/*
* cyapa_sleep_time_to_pwr_cmd and cyapa_pwr_cmd_to_sleep_time
*
* These are helper functions that convert to and from integer idle
* times and register settings to write to the PowerMode register.
* The trackpad supports between 20ms to 1000ms scan intervals.
* The time will be increased in increments of 10ms from 20ms to 100ms.
* From 100ms to 1000ms, time will be increased in increments of 20ms.
*
* When Idle_Time < 100, the format to convert Idle_Time to Idle_Command is:
* Idle_Command = Idle Time / 10;
* When Idle_Time >= 100, the format to convert Idle_Time to Idle_Command is:
* Idle_Command = Idle Time / 20 + 5;
*/
u8 cyapa_sleep_time_to_pwr_cmd(u16 sleep_time)
{
u16 encoded_time;
sleep_time = clamp_val(sleep_time, 20, 1000);
encoded_time = sleep_time < 100 ? sleep_time / 10 : sleep_time / 20 + 5;
return (encoded_time << 2) & PWR_MODE_MASK;
}
u16 cyapa_pwr_cmd_to_sleep_time(u8 pwr_mode)
{
u8 encoded_time = pwr_mode >> 2;
return (encoded_time < 10) ? encoded_time * 10
: (encoded_time - 5) * 20;
}
/* 0 on driver initialize and detected successfully, negative on failure. */
static int cyapa_initialize(struct cyapa *cyapa)
{
int error = 0;
cyapa->state = CYAPA_STATE_NO_DEVICE;
cyapa->gen = CYAPA_GEN_UNKNOWN;
mutex_init(&cyapa->state_sync_lock);
/*
* Set to hard code default, they will be updated with trackpad set
* default values after probe and initialized.
*/
cyapa->suspend_power_mode = PWR_MODE_SLEEP;
cyapa->suspend_sleep_time =
cyapa_pwr_cmd_to_sleep_time(cyapa->suspend_power_mode);
/* ops.initialize() is aimed to prepare for module communications. */
error = cyapa_gen3_ops.initialize(cyapa);
if (!error)
error = cyapa_gen5_ops.initialize(cyapa);
if (!error)
error = cyapa_gen6_ops.initialize(cyapa);
if (error)
return error;
error = cyapa_detect(cyapa);
if (error)
return error;
/* Power down the device until we need it. */
if (cyapa->operational)
cyapa->ops->set_power_mode(cyapa,
PWR_MODE_OFF, 0, CYAPA_PM_ACTIVE);
return 0;
}
static int cyapa_reinitialize(struct cyapa *cyapa)
{
struct device *dev = &cyapa->client->dev;
struct input_dev *input = cyapa->input;
int error;
if (pm_runtime_enabled(dev))
pm_runtime_disable(dev);
/* Avoid command failures when TP was in OFF state. */
if (cyapa->operational)
cyapa->ops->set_power_mode(cyapa,
PWR_MODE_FULL_ACTIVE, 0, CYAPA_PM_ACTIVE);
error = cyapa_detect(cyapa);
if (error)
goto out;
if (!input && cyapa->operational) {
error = cyapa_create_input_dev(cyapa);
if (error) {
dev_err(dev, "create input_dev instance failed: %d\n",
error);
goto out;
}
}
out:
if (!input || !input_device_enabled(input)) {
/* Reset to power OFF state to save power when no user open. */
if (cyapa->operational)
cyapa->ops->set_power_mode(cyapa,
PWR_MODE_OFF, 0, CYAPA_PM_DEACTIVE);
} else if (!error && cyapa->operational) {
/*
* Make sure only enable runtime PM when device is
* in operational mode and input->users > 0.
*/
pm_runtime_set_active(dev);
pm_runtime_enable(dev);
pm_runtime_get_sync(dev);
pm_runtime_mark_last_busy(dev);
pm_runtime_put_sync_autosuspend(dev);
}
return error;
}
static irqreturn_t cyapa_irq(int irq, void *dev_id)
{
struct cyapa *cyapa = dev_id;
struct device *dev = &cyapa->client->dev;
int error;
if (device_may_wakeup(dev))
pm_wakeup_event(dev, 0);
/* Interrupt event can be caused by host command to trackpad device. */
if (cyapa->ops->irq_cmd_handler(cyapa)) {
/*
* Interrupt event maybe from trackpad device input reporting.
*/
if (!cyapa->input) {
/*
* Still in probing or in firmware image
* updating or reading.
*/
cyapa->ops->sort_empty_output_data(cyapa,
NULL, NULL, NULL);
goto out;
}
if (cyapa->operational) {
error = cyapa->ops->irq_handler(cyapa);
/*
* Apply runtime power management to touch report event
* except the events caused by the command responses.
* Note:
* It will introduce about 20~40 ms additional delay
* time in receiving for first valid touch report data.
* The time is used to execute device runtime resume
* process.
*/
pm_runtime_get_sync(dev);
pm_runtime_mark_last_busy(dev);
pm_runtime_put_sync_autosuspend(dev);
}
if (!cyapa->operational || error) {
if (!mutex_trylock(&cyapa->state_sync_lock)) {
cyapa->ops->sort_empty_output_data(cyapa,
NULL, NULL, NULL);
goto out;
}
cyapa_reinitialize(cyapa);
mutex_unlock(&cyapa->state_sync_lock);
}
}
out:
return IRQ_HANDLED;
}
/*
**************************************************************
* sysfs interface
**************************************************************
*/
#ifdef CONFIG_PM_SLEEP
static ssize_t cyapa_show_suspend_scanrate(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
u8 pwr_cmd;
u16 sleep_time;
int len;
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
pwr_cmd = cyapa->suspend_power_mode;
sleep_time = cyapa->suspend_sleep_time;
mutex_unlock(&cyapa->state_sync_lock);
switch (pwr_cmd) {
case PWR_MODE_BTN_ONLY:
len = scnprintf(buf, PAGE_SIZE, "%s\n", BTN_ONLY_MODE_NAME);
break;
case PWR_MODE_OFF:
len = scnprintf(buf, PAGE_SIZE, "%s\n", OFF_MODE_NAME);
break;
default:
len = scnprintf(buf, PAGE_SIZE, "%u\n",
cyapa->gen == CYAPA_GEN3 ?
cyapa_pwr_cmd_to_sleep_time(pwr_cmd) :
sleep_time);
break;
}
return len;
}
static ssize_t cyapa_update_suspend_scanrate(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
u16 sleep_time;
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
if (sysfs_streq(buf, BTN_ONLY_MODE_NAME)) {
cyapa->suspend_power_mode = PWR_MODE_BTN_ONLY;
} else if (sysfs_streq(buf, OFF_MODE_NAME)) {
cyapa->suspend_power_mode = PWR_MODE_OFF;
} else if (!kstrtou16(buf, 10, &sleep_time)) {
cyapa->suspend_sleep_time = min_t(u16, sleep_time, 1000);
cyapa->suspend_power_mode =
cyapa_sleep_time_to_pwr_cmd(cyapa->suspend_sleep_time);
} else {
count = -EINVAL;
}
mutex_unlock(&cyapa->state_sync_lock);
return count;
}
static DEVICE_ATTR(suspend_scanrate_ms, S_IRUGO|S_IWUSR,
cyapa_show_suspend_scanrate,
cyapa_update_suspend_scanrate);
static struct attribute *cyapa_power_wakeup_entries[] = {
&dev_attr_suspend_scanrate_ms.attr,
NULL,
};
static const struct attribute_group cyapa_power_wakeup_group = {
.name = power_group_name,
.attrs = cyapa_power_wakeup_entries,
};
static void cyapa_remove_power_wakeup_group(void *data)
{
struct cyapa *cyapa = data;
sysfs_unmerge_group(&cyapa->client->dev.kobj,
&cyapa_power_wakeup_group);
}
static int cyapa_prepare_wakeup_controls(struct cyapa *cyapa)
{
struct i2c_client *client = cyapa->client;
struct device *dev = &client->dev;
int error;
if (device_can_wakeup(dev)) {
error = sysfs_merge_group(&dev->kobj,
&cyapa_power_wakeup_group);
if (error) {
dev_err(dev, "failed to add power wakeup group: %d\n",
error);
return error;
}
error = devm_add_action_or_reset(dev,
cyapa_remove_power_wakeup_group, cyapa);
if (error) {
dev_err(dev, "failed to add power cleanup action: %d\n",
error);
return error;
}
}
return 0;
}
#else
static inline int cyapa_prepare_wakeup_controls(struct cyapa *cyapa)
{
return 0;
}
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_PM
static ssize_t cyapa_show_rt_suspend_scanrate(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
u8 pwr_cmd;
u16 sleep_time;
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
pwr_cmd = cyapa->runtime_suspend_power_mode;
sleep_time = cyapa->runtime_suspend_sleep_time;
mutex_unlock(&cyapa->state_sync_lock);
return scnprintf(buf, PAGE_SIZE, "%u\n",
cyapa->gen == CYAPA_GEN3 ?
cyapa_pwr_cmd_to_sleep_time(pwr_cmd) :
sleep_time);
}
static ssize_t cyapa_update_rt_suspend_scanrate(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
u16 time;
int error;
if (buf == NULL || count == 0 || kstrtou16(buf, 10, &time)) {
dev_err(dev, "invalid runtime suspend scanrate ms parameter\n");
return -EINVAL;
}
/*
* When the suspend scanrate is changed, pm_runtime_get to resume
* a potentially suspended device, update to the new pwr_cmd
* and then pm_runtime_put to suspend into the new power mode.
*/
pm_runtime_get_sync(dev);
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
cyapa->runtime_suspend_sleep_time = min_t(u16, time, 1000);
cyapa->runtime_suspend_power_mode =
cyapa_sleep_time_to_pwr_cmd(cyapa->runtime_suspend_sleep_time);
mutex_unlock(&cyapa->state_sync_lock);
pm_runtime_put_sync_autosuspend(dev);
return count;
}
static DEVICE_ATTR(runtime_suspend_scanrate_ms, S_IRUGO|S_IWUSR,
cyapa_show_rt_suspend_scanrate,
cyapa_update_rt_suspend_scanrate);
static struct attribute *cyapa_power_runtime_entries[] = {
&dev_attr_runtime_suspend_scanrate_ms.attr,
NULL,
};
static const struct attribute_group cyapa_power_runtime_group = {
.name = power_group_name,
.attrs = cyapa_power_runtime_entries,
};
static void cyapa_remove_power_runtime_group(void *data)
{
struct cyapa *cyapa = data;
sysfs_unmerge_group(&cyapa->client->dev.kobj,
&cyapa_power_runtime_group);
}
static int cyapa_start_runtime(struct cyapa *cyapa)
{
struct device *dev = &cyapa->client->dev;
int error;
cyapa->runtime_suspend_power_mode = PWR_MODE_IDLE;
cyapa->runtime_suspend_sleep_time =
cyapa_pwr_cmd_to_sleep_time(cyapa->runtime_suspend_power_mode);
error = sysfs_merge_group(&dev->kobj, &cyapa_power_runtime_group);
if (error) {
dev_err(dev,
"failed to create power runtime group: %d\n", error);
return error;
}
error = devm_add_action_or_reset(dev, cyapa_remove_power_runtime_group,
cyapa);
if (error) {
dev_err(dev,
"failed to add power runtime cleanup action: %d\n",
error);
return error;
}
/* runtime is enabled until device is operational and opened. */
pm_runtime_set_suspended(dev);
pm_runtime_use_autosuspend(dev);
pm_runtime_set_autosuspend_delay(dev, AUTOSUSPEND_DELAY);
return 0;
}
#else
static inline int cyapa_start_runtime(struct cyapa *cyapa)
{
return 0;
}
#endif /* CONFIG_PM */
static ssize_t cyapa_show_fm_ver(struct device *dev,
struct device_attribute *attr, char *buf)
{
int error;
struct cyapa *cyapa = dev_get_drvdata(dev);
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
error = scnprintf(buf, PAGE_SIZE, "%d.%d\n", cyapa->fw_maj_ver,
cyapa->fw_min_ver);
mutex_unlock(&cyapa->state_sync_lock);
return error;
}
static ssize_t cyapa_show_product_id(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
int size;
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
size = scnprintf(buf, PAGE_SIZE, "%s\n", cyapa->product_id);
mutex_unlock(&cyapa->state_sync_lock);
return size;
}
static int cyapa_firmware(struct cyapa *cyapa, const char *fw_name)
{
struct device *dev = &cyapa->client->dev;
const struct firmware *fw;
int error;
error = request_firmware(&fw, fw_name, dev);
if (error) {
dev_err(dev, "Could not load firmware from %s: %d\n",
fw_name, error);
return error;
}
error = cyapa->ops->check_fw(cyapa, fw);
if (error) {
dev_err(dev, "Invalid CYAPA firmware image: %s\n",
fw_name);
goto done;
}
/*
* Resume the potentially suspended device because doing FW
* update on a device not in the FULL mode has a chance to
* fail.
*/
pm_runtime_get_sync(dev);
/* Require IRQ support for firmware update commands. */
cyapa_enable_irq_for_cmd(cyapa);
error = cyapa->ops->bl_enter(cyapa);
if (error) {
dev_err(dev, "bl_enter failed, %d\n", error);
goto err_detect;
}
error = cyapa->ops->bl_activate(cyapa);
if (error) {
dev_err(dev, "bl_activate failed, %d\n", error);
goto err_detect;
}
error = cyapa->ops->bl_initiate(cyapa, fw);
if (error) {
dev_err(dev, "bl_initiate failed, %d\n", error);
goto err_detect;
}
error = cyapa->ops->update_fw(cyapa, fw);
if (error) {
dev_err(dev, "update_fw failed, %d\n", error);
goto err_detect;
}
err_detect:
cyapa_disable_irq_for_cmd(cyapa);
pm_runtime_put_noidle(dev);
done:
release_firmware(fw);
return error;
}
static ssize_t cyapa_update_fw_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
char fw_name[NAME_MAX];
int ret, error;
if (count >= NAME_MAX) {
dev_err(dev, "File name too long\n");
return -EINVAL;
}
memcpy(fw_name, buf, count);
if (fw_name[count - 1] == '\n')
fw_name[count - 1] = '\0';
else
fw_name[count] = '\0';
if (cyapa->input) {
/*
* Force the input device to be registered after the firmware
* image is updated, so if the corresponding parameters updated
* in the new firmware image can taken effect immediately.
*/
input_unregister_device(cyapa->input);
cyapa->input = NULL;
}
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error) {
/*
* Whatever, do reinitialize to try to recover TP state to
* previous state just as it entered fw update entrance.
*/
cyapa_reinitialize(cyapa);
return error;
}
error = cyapa_firmware(cyapa, fw_name);
if (error)
dev_err(dev, "firmware update failed: %d\n", error);
else
dev_dbg(dev, "firmware update successfully done.\n");
/*
* Re-detect trackpad device states because firmware update process
* will reset trackpad device into bootloader mode.
*/
ret = cyapa_reinitialize(cyapa);
if (ret) {
dev_err(dev, "failed to re-detect after updated: %d\n", ret);
error = error ? error : ret;
}
mutex_unlock(&cyapa->state_sync_lock);
return error ? error : count;
}
static ssize_t cyapa_calibrate_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
if (cyapa->operational) {
cyapa_enable_irq_for_cmd(cyapa);
error = cyapa->ops->calibrate_store(dev, attr, buf, count);
cyapa_disable_irq_for_cmd(cyapa);
} else {
error = -EBUSY; /* Still running in bootloader mode. */
}
mutex_unlock(&cyapa->state_sync_lock);
return error < 0 ? error : count;
}
static ssize_t cyapa_show_baseline(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
ssize_t error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
if (cyapa->operational) {
cyapa_enable_irq_for_cmd(cyapa);
error = cyapa->ops->show_baseline(dev, attr, buf);
cyapa_disable_irq_for_cmd(cyapa);
} else {
error = -EBUSY; /* Still running in bootloader mode. */
}
mutex_unlock(&cyapa->state_sync_lock);
return error;
}
static char *cyapa_state_to_string(struct cyapa *cyapa)
{
switch (cyapa->state) {
case CYAPA_STATE_BL_BUSY:
return "bootloader busy";
case CYAPA_STATE_BL_IDLE:
return "bootloader idle";
case CYAPA_STATE_BL_ACTIVE:
return "bootloader active";
case CYAPA_STATE_GEN5_BL:
case CYAPA_STATE_GEN6_BL:
return "bootloader";
case CYAPA_STATE_OP:
case CYAPA_STATE_GEN5_APP:
case CYAPA_STATE_GEN6_APP:
return "operational"; /* Normal valid state. */
default:
return "invalid mode";
}
}
static ssize_t cyapa_show_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
int size;
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
size = scnprintf(buf, PAGE_SIZE, "gen%d %s\n",
cyapa->gen, cyapa_state_to_string(cyapa));
mutex_unlock(&cyapa->state_sync_lock);
return size;
}
static DEVICE_ATTR(firmware_version, S_IRUGO, cyapa_show_fm_ver, NULL);
static DEVICE_ATTR(product_id, S_IRUGO, cyapa_show_product_id, NULL);
static DEVICE_ATTR(update_fw, S_IWUSR, NULL, cyapa_update_fw_store);
static DEVICE_ATTR(baseline, S_IRUGO, cyapa_show_baseline, NULL);
static DEVICE_ATTR(calibrate, S_IWUSR, NULL, cyapa_calibrate_store);
static DEVICE_ATTR(mode, S_IRUGO, cyapa_show_mode, NULL);
static struct attribute *cyapa_sysfs_entries[] = {
&dev_attr_firmware_version.attr,
&dev_attr_product_id.attr,
&dev_attr_update_fw.attr,
&dev_attr_baseline.attr,
&dev_attr_calibrate.attr,
&dev_attr_mode.attr,
NULL,
};
static const struct attribute_group cyapa_sysfs_group = {
.attrs = cyapa_sysfs_entries,
};
static void cyapa_disable_regulator(void *data)
{
struct cyapa *cyapa = data;
regulator_disable(cyapa->vcc);
}
static int cyapa_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
struct cyapa *cyapa;
u8 adapter_func;
union i2c_smbus_data dummy;
int error;
adapter_func = cyapa_check_adapter_functionality(client);
if (adapter_func == CYAPA_ADAPTER_FUNC_NONE) {
dev_err(dev, "not a supported I2C/SMBus adapter\n");
return -EIO;
}
/* Make sure there is something at this address */
if (i2c_smbus_xfer(client->adapter, client->addr, 0,
I2C_SMBUS_READ, 0, I2C_SMBUS_BYTE, &dummy) < 0)
return -ENODEV;
cyapa = devm_kzalloc(dev, sizeof(struct cyapa), GFP_KERNEL);
if (!cyapa)
return -ENOMEM;
/* i2c isn't supported, use smbus */
if (adapter_func == CYAPA_ADAPTER_FUNC_SMBUS)
cyapa->smbus = true;
cyapa->client = client;
i2c_set_clientdata(client, cyapa);
sprintf(cyapa->phys, "i2c-%d-%04x/input0", client->adapter->nr,
client->addr);
cyapa->vcc = devm_regulator_get(dev, "vcc");
if (IS_ERR(cyapa->vcc)) {
error = PTR_ERR(cyapa->vcc);
dev_err(dev, "failed to get vcc regulator: %d\n", error);
return error;
}
error = regulator_enable(cyapa->vcc);
if (error) {
dev_err(dev, "failed to enable regulator: %d\n", error);
return error;
}
error = devm_add_action_or_reset(dev, cyapa_disable_regulator, cyapa);
if (error) {
dev_err(dev, "failed to add disable regulator action: %d\n",
error);
return error;
}
error = cyapa_initialize(cyapa);
if (error) {
dev_err(dev, "failed to detect and initialize tp device.\n");
return error;
}
error = devm_device_add_group(dev, &cyapa_sysfs_group);
if (error) {
dev_err(dev, "failed to create sysfs entries: %d\n", error);
return error;
}
error = cyapa_prepare_wakeup_controls(cyapa);
if (error) {
dev_err(dev, "failed to prepare wakeup controls: %d\n", error);
return error;
}
error = cyapa_start_runtime(cyapa);
if (error) {
dev_err(dev, "failed to start pm_runtime: %d\n", error);
return error;
}
error = devm_request_threaded_irq(dev, client->irq,
NULL, cyapa_irq,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
"cyapa", cyapa);
if (error) {
dev_err(dev, "failed to request threaded irq: %d\n", error);
return error;
}
/* Disable IRQ until the device is opened */
disable_irq(client->irq);
/*
* Register the device in the input subsystem when it's operational.
* Otherwise, keep in this driver, so it can be be recovered or updated
* through the sysfs mode and update_fw interfaces by user or apps.
*/
if (cyapa->operational) {
error = cyapa_create_input_dev(cyapa);
if (error) {
dev_err(dev, "create input_dev instance failed: %d\n",
error);
return error;
}
}
return 0;
}
static int cyapa_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct cyapa *cyapa = i2c_get_clientdata(client);
u8 power_mode;
int error;
error = mutex_lock_interruptible(&cyapa->state_sync_lock);
if (error)
return error;
/*
* Runtime PM is enable only when device is in operational mode and
* users in use, so need check it before disable it to
* avoid unbalance warning.
*/
if (pm_runtime_enabled(dev))
pm_runtime_disable(dev);
disable_irq(client->irq);
/*
* Set trackpad device to idle mode if wakeup is allowed,
* otherwise turn off.
*/
if (cyapa->operational) {
power_mode = device_may_wakeup(dev) ? cyapa->suspend_power_mode
: PWR_MODE_OFF;
error = cyapa->ops->set_power_mode(cyapa, power_mode,
cyapa->suspend_sleep_time, CYAPA_PM_SUSPEND);
if (error)
dev_err(dev, "suspend set power mode failed: %d\n",
error);
}
/*
* Disable proximity interrupt when system idle, want true touch to
* wake the system.
*/
if (cyapa->dev_pwr_mode != PWR_MODE_OFF)
cyapa->ops->set_proximity(cyapa, false);
if (device_may_wakeup(dev))
cyapa->irq_wake = (enable_irq_wake(client->irq) == 0);
mutex_unlock(&cyapa->state_sync_lock);
return 0;
}
static int cyapa_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct cyapa *cyapa = i2c_get_clientdata(client);
int error;
mutex_lock(&cyapa->state_sync_lock);
if (device_may_wakeup(dev) && cyapa->irq_wake) {
disable_irq_wake(client->irq);
cyapa->irq_wake = false;
}
/*
* Update device states and runtime PM states.
* Re-Enable proximity interrupt after enter operational mode.
*/
error = cyapa_reinitialize(cyapa);
if (error)
dev_warn(dev, "failed to reinitialize TP device: %d\n", error);
enable_irq(client->irq);
mutex_unlock(&cyapa->state_sync_lock);
return 0;
}
static int cyapa_runtime_suspend(struct device *dev)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
int error;
error = cyapa->ops->set_power_mode(cyapa,
cyapa->runtime_suspend_power_mode,
cyapa->runtime_suspend_sleep_time,
CYAPA_PM_RUNTIME_SUSPEND);
if (error)
dev_warn(dev, "runtime suspend failed: %d\n", error);
return 0;
}
static int cyapa_runtime_resume(struct device *dev)
{
struct cyapa *cyapa = dev_get_drvdata(dev);
int error;
error = cyapa->ops->set_power_mode(cyapa,
PWR_MODE_FULL_ACTIVE, 0, CYAPA_PM_RUNTIME_RESUME);
if (error)
dev_warn(dev, "runtime resume failed: %d\n", error);
return 0;
}
static const struct dev_pm_ops cyapa_pm_ops = {
SYSTEM_SLEEP_PM_OPS(cyapa_suspend, cyapa_resume)
RUNTIME_PM_OPS(cyapa_runtime_suspend, cyapa_runtime_resume, NULL)
};
static const struct i2c_device_id cyapa_id_table[] = {
{ "cyapa", 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, cyapa_id_table);
#ifdef CONFIG_ACPI
static const struct acpi_device_id cyapa_acpi_id[] = {
{ "CYAP0000", 0 }, /* Gen3 trackpad with 0x67 I2C address. */
{ "CYAP0001", 0 }, /* Gen5 trackpad with 0x24 I2C address. */
{ "CYAP0002", 0 }, /* Gen6 trackpad with 0x24 I2C address. */
{ }
};
MODULE_DEVICE_TABLE(acpi, cyapa_acpi_id);
#endif
#ifdef CONFIG_OF
static const struct of_device_id cyapa_of_match[] = {
{ .compatible = "cypress,cyapa" },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, cyapa_of_match);
#endif
static struct i2c_driver cyapa_driver = {
.driver = {
.name = "cyapa",
.pm = pm_ptr(&cyapa_pm_ops),
.acpi_match_table = ACPI_PTR(cyapa_acpi_id),
.of_match_table = of_match_ptr(cyapa_of_match),
},
.probe = cyapa_probe,
.id_table = cyapa_id_table,
};
module_i2c_driver(cyapa_driver);
MODULE_DESCRIPTION("Cypress APA I2C Trackpad Driver");
MODULE_AUTHOR("Dudley Du <[email protected]>");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/mouse/cyapa.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Focaltech TouchPad PS/2 mouse driver
*
* Copyright (c) 2014 Red Hat Inc.
* Copyright (c) 2014 Mathias Gottschlag <[email protected]>
*
* Red Hat authors:
*
* Hans de Goede <[email protected]>
*/
#include <linux/device.h>
#include <linux/libps2.h>
#include <linux/input/mt.h>
#include <linux/serio.h>
#include <linux/slab.h>
#include "psmouse.h"
#include "focaltech.h"
static const char * const focaltech_pnp_ids[] = {
"FLT0101",
"FLT0102",
"FLT0103",
NULL
};
/*
* Even if the kernel is built without support for Focaltech PS/2 touchpads (or
* when the real driver fails to recognize the device), we still have to detect
* them in order to avoid further detection attempts confusing the touchpad.
* This way it at least works in PS/2 mouse compatibility mode.
*/
int focaltech_detect(struct psmouse *psmouse, bool set_properties)
{
if (!psmouse_matches_pnp_id(psmouse, focaltech_pnp_ids))
return -ENODEV;
if (set_properties) {
psmouse->vendor = "FocalTech";
psmouse->name = "Touchpad";
}
return 0;
}
#ifdef CONFIG_MOUSE_PS2_FOCALTECH
/*
* Packet types - the numbers are not consecutive, so we might be missing
* something here.
*/
#define FOC_TOUCH 0x3 /* bitmap of active fingers */
#define FOC_ABS 0x6 /* absolute position of one finger */
#define FOC_REL 0x9 /* relative position of 1-2 fingers */
#define FOC_MAX_FINGERS 5
/*
* Current state of a single finger on the touchpad.
*/
struct focaltech_finger_state {
/* The touchpad has generated a touch event for the finger */
bool active;
/*
* The touchpad has sent position data for the finger. The
* flag is 0 when the finger is not active, and there is a
* time between the first touch event for the finger and the
* following absolute position packet for the finger where the
* touchpad has declared the finger to be valid, but we do not
* have any valid position yet.
*/
bool valid;
/*
* Absolute position (from the bottom left corner) of the
* finger.
*/
unsigned int x;
unsigned int y;
};
/*
* Description of the current state of the touchpad hardware.
*/
struct focaltech_hw_state {
/*
* The touchpad tracks the positions of the fingers for us,
* the array indices correspond to the finger indices returned
* in the report packages.
*/
struct focaltech_finger_state fingers[FOC_MAX_FINGERS];
/*
* Finger width 0-7 and 15 for a very big contact area.
* 15 value stays until the finger is released.
* Width is reported only in absolute packets.
* Since hardware reports width only for last touching finger,
* there is no need to store width for every specific finger,
* so we keep only last value reported.
*/
unsigned int width;
/* True if the clickpad has been pressed. */
bool pressed;
};
struct focaltech_data {
unsigned int x_max, y_max;
struct focaltech_hw_state state;
};
static void focaltech_report_state(struct psmouse *psmouse)
{
struct focaltech_data *priv = psmouse->private;
struct focaltech_hw_state *state = &priv->state;
struct input_dev *dev = psmouse->dev;
int i;
for (i = 0; i < FOC_MAX_FINGERS; i++) {
struct focaltech_finger_state *finger = &state->fingers[i];
bool active = finger->active && finger->valid;
input_mt_slot(dev, i);
input_mt_report_slot_state(dev, MT_TOOL_FINGER, active);
if (active) {
unsigned int clamped_x, clamped_y;
/*
* The touchpad might report invalid data, so we clamp
* the resulting values so that we do not confuse
* userspace.
*/
clamped_x = clamp(finger->x, 0U, priv->x_max);
clamped_y = clamp(finger->y, 0U, priv->y_max);
input_report_abs(dev, ABS_MT_POSITION_X, clamped_x);
input_report_abs(dev, ABS_MT_POSITION_Y,
priv->y_max - clamped_y);
input_report_abs(dev, ABS_TOOL_WIDTH, state->width);
}
}
input_mt_report_pointer_emulation(dev, true);
input_report_key(dev, BTN_LEFT, state->pressed);
input_sync(dev);
}
static void focaltech_process_touch_packet(struct psmouse *psmouse,
unsigned char *packet)
{
struct focaltech_data *priv = psmouse->private;
struct focaltech_hw_state *state = &priv->state;
unsigned char fingers = packet[1];
int i;
state->pressed = (packet[0] >> 4) & 1;
/* the second byte contains a bitmap of all fingers touching the pad */
for (i = 0; i < FOC_MAX_FINGERS; i++) {
state->fingers[i].active = fingers & 0x1;
if (!state->fingers[i].active) {
/*
* Even when the finger becomes active again, we still
* will have to wait for the first valid position.
*/
state->fingers[i].valid = false;
}
fingers >>= 1;
}
}
static void focaltech_process_abs_packet(struct psmouse *psmouse,
unsigned char *packet)
{
struct focaltech_data *priv = psmouse->private;
struct focaltech_hw_state *state = &priv->state;
unsigned int finger;
finger = (packet[1] >> 4) - 1;
if (finger >= FOC_MAX_FINGERS) {
psmouse_err(psmouse, "Invalid finger in abs packet: %d\n",
finger);
return;
}
state->pressed = (packet[0] >> 4) & 1;
state->fingers[finger].x = ((packet[1] & 0xf) << 8) | packet[2];
state->fingers[finger].y = (packet[3] << 8) | packet[4];
state->width = packet[5] >> 4;
state->fingers[finger].valid = true;
}
static void focaltech_process_rel_packet(struct psmouse *psmouse,
unsigned char *packet)
{
struct focaltech_data *priv = psmouse->private;
struct focaltech_hw_state *state = &priv->state;
int finger1, finger2;
state->pressed = packet[0] >> 7;
finger1 = ((packet[0] >> 4) & 0x7) - 1;
if (finger1 < FOC_MAX_FINGERS) {
state->fingers[finger1].x += (s8)packet[1];
state->fingers[finger1].y += (s8)packet[2];
} else {
psmouse_err(psmouse, "First finger in rel packet invalid: %d\n",
finger1);
}
/*
* If there is an odd number of fingers, the last relative
* packet only contains one finger. In this case, the second
* finger index in the packet is 0 (we subtract 1 in the lines
* above to create array indices, so the finger will overflow
* and be above FOC_MAX_FINGERS).
*/
finger2 = ((packet[3] >> 4) & 0x7) - 1;
if (finger2 < FOC_MAX_FINGERS) {
state->fingers[finger2].x += (s8)packet[4];
state->fingers[finger2].y += (s8)packet[5];
}
}
static void focaltech_process_packet(struct psmouse *psmouse)
{
unsigned char *packet = psmouse->packet;
switch (packet[0] & 0xf) {
case FOC_TOUCH:
focaltech_process_touch_packet(psmouse, packet);
break;
case FOC_ABS:
focaltech_process_abs_packet(psmouse, packet);
break;
case FOC_REL:
focaltech_process_rel_packet(psmouse, packet);
break;
default:
psmouse_err(psmouse, "Unknown packet type: %02x\n", packet[0]);
break;
}
focaltech_report_state(psmouse);
}
static psmouse_ret_t focaltech_process_byte(struct psmouse *psmouse)
{
if (psmouse->pktcnt >= 6) { /* Full packet received */
focaltech_process_packet(psmouse);
return PSMOUSE_FULL_PACKET;
}
/*
* We might want to do some validation of the data here, but
* we do not know the protocol well enough
*/
return PSMOUSE_GOOD_DATA;
}
static int focaltech_switch_protocol(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[3];
param[0] = 0;
if (ps2_command(ps2dev, param, 0x10f8))
return -EIO;
if (ps2_command(ps2dev, param, 0x10f8))
return -EIO;
if (ps2_command(ps2dev, param, 0x10f8))
return -EIO;
param[0] = 1;
if (ps2_command(ps2dev, param, 0x10f8))
return -EIO;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETSCALE11))
return -EIO;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_ENABLE))
return -EIO;
return 0;
}
static void focaltech_reset(struct psmouse *psmouse)
{
ps2_command(&psmouse->ps2dev, NULL, PSMOUSE_CMD_RESET_DIS);
psmouse_reset(psmouse);
}
static void focaltech_disconnect(struct psmouse *psmouse)
{
focaltech_reset(psmouse);
kfree(psmouse->private);
psmouse->private = NULL;
}
static int focaltech_reconnect(struct psmouse *psmouse)
{
int error;
focaltech_reset(psmouse);
error = focaltech_switch_protocol(psmouse);
if (error) {
psmouse_err(psmouse, "Unable to initialize the device\n");
return error;
}
return 0;
}
static void focaltech_set_input_params(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct focaltech_data *priv = psmouse->private;
/*
* Undo part of setup done for us by psmouse core since touchpad
* is not a relative device.
*/
__clear_bit(EV_REL, dev->evbit);
__clear_bit(REL_X, dev->relbit);
__clear_bit(REL_Y, dev->relbit);
__clear_bit(BTN_RIGHT, dev->keybit);
__clear_bit(BTN_MIDDLE, dev->keybit);
/*
* Now set up our capabilities.
*/
__set_bit(EV_ABS, dev->evbit);
input_set_abs_params(dev, ABS_MT_POSITION_X, 0, priv->x_max, 0, 0);
input_set_abs_params(dev, ABS_MT_POSITION_Y, 0, priv->y_max, 0, 0);
input_set_abs_params(dev, ABS_TOOL_WIDTH, 0, 15, 0, 0);
input_mt_init_slots(dev, 5, INPUT_MT_POINTER);
__set_bit(INPUT_PROP_BUTTONPAD, dev->propbit);
}
static int focaltech_read_register(struct ps2dev *ps2dev, int reg,
unsigned char *param)
{
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETSCALE11))
return -EIO;
param[0] = 0;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -EIO;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -EIO;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -EIO;
param[0] = reg;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -EIO;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO))
return -EIO;
return 0;
}
static int focaltech_read_size(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct focaltech_data *priv = psmouse->private;
char param[3];
if (focaltech_read_register(ps2dev, 2, param))
return -EIO;
/* not sure whether this is 100% correct */
priv->x_max = (unsigned char)param[1] * 128;
priv->y_max = (unsigned char)param[2] * 128;
return 0;
}
static void focaltech_set_resolution(struct psmouse *psmouse,
unsigned int resolution)
{
/* not supported yet */
}
static void focaltech_set_rate(struct psmouse *psmouse, unsigned int rate)
{
/* not supported yet */
}
static void focaltech_set_scale(struct psmouse *psmouse,
enum psmouse_scale scale)
{
/* not supported yet */
}
int focaltech_init(struct psmouse *psmouse)
{
struct focaltech_data *priv;
int error;
psmouse->private = priv = kzalloc(sizeof(struct focaltech_data),
GFP_KERNEL);
if (!priv)
return -ENOMEM;
focaltech_reset(psmouse);
error = focaltech_read_size(psmouse);
if (error) {
psmouse_err(psmouse,
"Unable to read the size of the touchpad\n");
goto fail;
}
error = focaltech_switch_protocol(psmouse);
if (error) {
psmouse_err(psmouse, "Unable to initialize the device\n");
goto fail;
}
focaltech_set_input_params(psmouse);
psmouse->protocol_handler = focaltech_process_byte;
psmouse->pktsize = 6;
psmouse->disconnect = focaltech_disconnect;
psmouse->reconnect = focaltech_reconnect;
psmouse->cleanup = focaltech_reset;
/* resync is not supported yet */
psmouse->resync_time = 0;
/*
* rate/resolution/scale changes are not supported yet, and
* the generic implementations of these functions seem to
* confuse some touchpads
*/
psmouse->set_resolution = focaltech_set_resolution;
psmouse->set_rate = focaltech_set_rate;
psmouse->set_scale = focaltech_set_scale;
return 0;
fail:
focaltech_reset(psmouse);
kfree(priv);
return error;
}
#endif /* CONFIG_MOUSE_PS2_FOCALTECH */
|
linux-master
|
drivers/input/mouse/focaltech.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* Serial mouse driver for Linux
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Serial mouse driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static const char *sermouse_protocols[] = { "None", "Mouse Systems Mouse", "Sun Mouse", "Microsoft Mouse",
"Logitech M+ Mouse", "Microsoft MZ Mouse", "Logitech MZ+ Mouse",
"Logitech MZ++ Mouse"};
struct sermouse {
struct input_dev *dev;
signed char buf[8];
unsigned char count;
unsigned char type;
unsigned long last;
char phys[32];
};
/*
* sermouse_process_msc() analyzes the incoming MSC/Sun bytestream and
* applies some prediction to the data, resulting in 96 updates per
* second, which is as good as a PS/2 or USB mouse.
*/
static void sermouse_process_msc(struct sermouse *sermouse, signed char data)
{
struct input_dev *dev = sermouse->dev;
signed char *buf = sermouse->buf;
switch (sermouse->count) {
case 0:
if ((data & 0xf8) != 0x80)
return;
input_report_key(dev, BTN_LEFT, !(data & 4));
input_report_key(dev, BTN_RIGHT, !(data & 1));
input_report_key(dev, BTN_MIDDLE, !(data & 2));
break;
case 1:
case 3:
input_report_rel(dev, REL_X, data / 2);
input_report_rel(dev, REL_Y, -buf[1]);
buf[0] = data - data / 2;
break;
case 2:
case 4:
input_report_rel(dev, REL_X, buf[0]);
input_report_rel(dev, REL_Y, buf[1] - data);
buf[1] = data / 2;
break;
}
input_sync(dev);
if (++sermouse->count == 5)
sermouse->count = 0;
}
/*
* sermouse_process_ms() anlyzes the incoming MS(Z/+/++) bytestream and
* generates events. With prediction it gets 80 updates/sec, assuming
* standard 3-byte packets and 1200 bps.
*/
static void sermouse_process_ms(struct sermouse *sermouse, signed char data)
{
struct input_dev *dev = sermouse->dev;
signed char *buf = sermouse->buf;
if (data & 0x40)
sermouse->count = 0;
else if (sermouse->count == 0)
return;
switch (sermouse->count) {
case 0:
buf[1] = data;
input_report_key(dev, BTN_LEFT, (data >> 5) & 1);
input_report_key(dev, BTN_RIGHT, (data >> 4) & 1);
break;
case 1:
buf[2] = data;
data = (signed char) (((buf[1] << 6) & 0xc0) | (data & 0x3f));
input_report_rel(dev, REL_X, data / 2);
input_report_rel(dev, REL_Y, buf[4]);
buf[3] = data - data / 2;
break;
case 2:
/* Guessing the state of the middle button on 3-button MS-protocol mice - ugly. */
if ((sermouse->type == SERIO_MS) && !data && !buf[2] && !((buf[0] & 0xf0) ^ buf[1]))
input_report_key(dev, BTN_MIDDLE, !test_bit(BTN_MIDDLE, dev->key));
buf[0] = buf[1];
data = (signed char) (((buf[1] << 4) & 0xc0) | (data & 0x3f));
input_report_rel(dev, REL_X, buf[3]);
input_report_rel(dev, REL_Y, data - buf[4]);
buf[4] = data / 2;
break;
case 3:
switch (sermouse->type) {
case SERIO_MS:
sermouse->type = SERIO_MP;
fallthrough;
case SERIO_MP:
if ((data >> 2) & 3) break; /* M++ Wireless Extension packet. */
input_report_key(dev, BTN_MIDDLE, (data >> 5) & 1);
input_report_key(dev, BTN_SIDE, (data >> 4) & 1);
break;
case SERIO_MZP:
case SERIO_MZPP:
input_report_key(dev, BTN_SIDE, (data >> 5) & 1);
fallthrough;
case SERIO_MZ:
input_report_key(dev, BTN_MIDDLE, (data >> 4) & 1);
input_report_rel(dev, REL_WHEEL, (data & 8) - (data & 7));
break;
}
break;
case 4:
case 6: /* MZ++ packet type. We can get these bytes for M++ too but we ignore them later. */
buf[1] = (data >> 2) & 0x0f;
break;
case 5:
case 7: /* Ignore anything besides MZ++ */
if (sermouse->type != SERIO_MZPP)
break;
switch (buf[1]) {
case 1: /* Extra mouse info */
input_report_key(dev, BTN_SIDE, (data >> 4) & 1);
input_report_key(dev, BTN_EXTRA, (data >> 5) & 1);
input_report_rel(dev, data & 0x80 ? REL_HWHEEL : REL_WHEEL, (data & 7) - (data & 8));
break;
default: /* We don't decode anything else yet. */
printk(KERN_WARNING
"sermouse.c: Received MZ++ packet %x, don't know how to handle.\n", buf[1]);
break;
}
break;
}
input_sync(dev);
sermouse->count++;
}
/*
* sermouse_interrupt() handles incoming characters, either gathering them into
* packets or passing them to the command routine as command output.
*/
static irqreturn_t sermouse_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct sermouse *sermouse = serio_get_drvdata(serio);
if (time_after(jiffies, sermouse->last + HZ/10))
sermouse->count = 0;
sermouse->last = jiffies;
if (sermouse->type > SERIO_SUN)
sermouse_process_ms(sermouse, data);
else
sermouse_process_msc(sermouse, data);
return IRQ_HANDLED;
}
/*
* sermouse_disconnect() cleans up after we don't want talk
* to the mouse anymore.
*/
static void sermouse_disconnect(struct serio *serio)
{
struct sermouse *sermouse = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(sermouse->dev);
kfree(sermouse);
}
/*
* sermouse_connect() is a callback form the serio module when
* an unhandled serio port is found.
*/
static int sermouse_connect(struct serio *serio, struct serio_driver *drv)
{
struct sermouse *sermouse;
struct input_dev *input_dev;
unsigned char c = serio->id.extra;
int err = -ENOMEM;
sermouse = kzalloc(sizeof(struct sermouse), GFP_KERNEL);
input_dev = input_allocate_device();
if (!sermouse || !input_dev)
goto fail1;
sermouse->dev = input_dev;
snprintf(sermouse->phys, sizeof(sermouse->phys), "%s/input0", serio->phys);
sermouse->type = serio->id.proto;
input_dev->name = sermouse_protocols[sermouse->type];
input_dev->phys = sermouse->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = sermouse->type;
input_dev->id.product = c;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
input_dev->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_RIGHT);
input_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y);
if (c & 0x01) set_bit(BTN_MIDDLE, input_dev->keybit);
if (c & 0x02) set_bit(BTN_SIDE, input_dev->keybit);
if (c & 0x04) set_bit(BTN_EXTRA, input_dev->keybit);
if (c & 0x10) set_bit(REL_WHEEL, input_dev->relbit);
if (c & 0x20) set_bit(REL_HWHEEL, input_dev->relbit);
serio_set_drvdata(serio, sermouse);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(sermouse->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(sermouse);
return err;
}
static struct serio_device_id sermouse_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_MSC,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_SUN,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MS,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MP,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MZ,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MZP,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_MZPP,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, sermouse_serio_ids);
static struct serio_driver sermouse_drv = {
.driver = {
.name = "sermouse",
},
.description = DRIVER_DESC,
.id_table = sermouse_serio_ids,
.interrupt = sermouse_interrupt,
.connect = sermouse_connect,
.disconnect = sermouse_disconnect,
};
module_serio_driver(sermouse_drv);
|
linux-master
|
drivers/input/mouse/sermouse.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* BYD TouchPad PS/2 mouse driver
*
* Copyright (C) 2015 Chris Diamand <[email protected]>
* Copyright (C) 2015 Richard Pospesel
* Copyright (C) 2015 Tai Chi Minh Ralph Eastwood
* Copyright (C) 2015 Martin Wimpress
* Copyright (C) 2015 Jay Kuri
*/
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/libps2.h>
#include <linux/serio.h>
#include <linux/slab.h>
#include "psmouse.h"
#include "byd.h"
/* PS2 Bits */
#define PS2_Y_OVERFLOW BIT_MASK(7)
#define PS2_X_OVERFLOW BIT_MASK(6)
#define PS2_Y_SIGN BIT_MASK(5)
#define PS2_X_SIGN BIT_MASK(4)
#define PS2_ALWAYS_1 BIT_MASK(3)
#define PS2_MIDDLE BIT_MASK(2)
#define PS2_RIGHT BIT_MASK(1)
#define PS2_LEFT BIT_MASK(0)
/*
* BYD pad constants
*/
/*
* True device resolution is unknown, however experiments show the
* resolution is about 111 units/mm.
* Absolute coordinate packets are in the range 0-255 for both X and Y
* we pick ABS_X/ABS_Y dimensions which are multiples of 256 and in
* the right ballpark given the touchpad's physical dimensions and estimate
* resolution per spec sheet, device active area dimensions are
* 101.6 x 60.1 mm.
*/
#define BYD_PAD_WIDTH 11264
#define BYD_PAD_HEIGHT 6656
#define BYD_PAD_RESOLUTION 111
/*
* Given the above dimensions, relative packets velocity is in multiples of
* 1 unit / 11 milliseconds. We use this dt to estimate distance traveled
*/
#define BYD_DT 11
/* Time in jiffies used to timeout various touch events (64 ms) */
#define BYD_TOUCH_TIMEOUT msecs_to_jiffies(64)
/* BYD commands reverse engineered from windows driver */
/*
* Swipe gesture from off-pad to on-pad
* 0 : disable
* 1 : enable
*/
#define BYD_CMD_SET_OFFSCREEN_SWIPE 0x10cc
/*
* Tap and drag delay time
* 0 : disable
* 1 - 8 : least to most delay
*/
#define BYD_CMD_SET_TAP_DRAG_DELAY_TIME 0x10cf
/*
* Physical buttons function mapping
* 0 : enable
* 4 : normal
* 5 : left button custom command
* 6 : right button custom command
* 8 : disable
*/
#define BYD_CMD_SET_PHYSICAL_BUTTONS 0x10d0
/*
* Absolute mode (1 byte X/Y resolution)
* 0 : disable
* 2 : enable
*/
#define BYD_CMD_SET_ABSOLUTE_MODE 0x10d1
/*
* Two finger scrolling
* 1 : vertical
* 2 : horizontal
* 3 : vertical + horizontal
* 4 : disable
*/
#define BYD_CMD_SET_TWO_FINGER_SCROLL 0x10d2
/*
* Handedness
* 1 : right handed
* 2 : left handed
*/
#define BYD_CMD_SET_HANDEDNESS 0x10d3
/*
* Tap to click
* 1 : enable
* 2 : disable
*/
#define BYD_CMD_SET_TAP 0x10d4
/*
* Tap and drag
* 1 : tap and hold to drag
* 2 : tap and hold to drag + lock
* 3 : disable
*/
#define BYD_CMD_SET_TAP_DRAG 0x10d5
/*
* Touch sensitivity
* 1 - 7 : least to most sensitive
*/
#define BYD_CMD_SET_TOUCH_SENSITIVITY 0x10d6
/*
* One finger scrolling
* 1 : vertical
* 2 : horizontal
* 3 : vertical + horizontal
* 4 : disable
*/
#define BYD_CMD_SET_ONE_FINGER_SCROLL 0x10d7
/*
* One finger scrolling function
* 1 : free scrolling
* 2 : edge motion
* 3 : free scrolling + edge motion
* 4 : disable
*/
#define BYD_CMD_SET_ONE_FINGER_SCROLL_FUNC 0x10d8
/*
* Sliding speed
* 1 - 5 : slowest to fastest
*/
#define BYD_CMD_SET_SLIDING_SPEED 0x10da
/*
* Edge motion
* 1 : disable
* 2 : enable when dragging
* 3 : enable when dragging and pointing
*/
#define BYD_CMD_SET_EDGE_MOTION 0x10db
/*
* Left edge region size
* 0 - 7 : smallest to largest width
*/
#define BYD_CMD_SET_LEFT_EDGE_REGION 0x10dc
/*
* Top edge region size
* 0 - 9 : smallest to largest height
*/
#define BYD_CMD_SET_TOP_EDGE_REGION 0x10dd
/*
* Disregard palm press as clicks
* 1 - 6 : smallest to largest
*/
#define BYD_CMD_SET_PALM_CHECK 0x10de
/*
* Right edge region size
* 0 - 7 : smallest to largest width
*/
#define BYD_CMD_SET_RIGHT_EDGE_REGION 0x10df
/*
* Bottom edge region size
* 0 - 9 : smallest to largest height
*/
#define BYD_CMD_SET_BOTTOM_EDGE_REGION 0x10e1
/*
* Multitouch gestures
* 1 : enable
* 2 : disable
*/
#define BYD_CMD_SET_MULTITOUCH 0x10e3
/*
* Edge motion speed
* 0 : control with finger pressure
* 1 - 9 : slowest to fastest
*/
#define BYD_CMD_SET_EDGE_MOTION_SPEED 0x10e4
/*
* Two finger scolling function
* 0 : free scrolling
* 1 : free scrolling (with momentum)
* 2 : edge motion
* 3 : free scrolling (with momentum) + edge motion
* 4 : disable
*/
#define BYD_CMD_SET_TWO_FINGER_SCROLL_FUNC 0x10e5
/*
* The touchpad generates a mixture of absolute and relative packets, indicated
* by the last byte of each packet being set to one of the following:
*/
#define BYD_PACKET_ABSOLUTE 0xf8
#define BYD_PACKET_RELATIVE 0x00
/* Multitouch gesture packets */
#define BYD_PACKET_PINCH_IN 0xd8
#define BYD_PACKET_PINCH_OUT 0x28
#define BYD_PACKET_ROTATE_CLOCKWISE 0x29
#define BYD_PACKET_ROTATE_ANTICLOCKWISE 0xd7
#define BYD_PACKET_TWO_FINGER_SCROLL_RIGHT 0x2a
#define BYD_PACKET_TWO_FINGER_SCROLL_DOWN 0x2b
#define BYD_PACKET_TWO_FINGER_SCROLL_UP 0xd5
#define BYD_PACKET_TWO_FINGER_SCROLL_LEFT 0xd6
#define BYD_PACKET_THREE_FINGER_SWIPE_RIGHT 0x2c
#define BYD_PACKET_THREE_FINGER_SWIPE_DOWN 0x2d
#define BYD_PACKET_THREE_FINGER_SWIPE_UP 0xd3
#define BYD_PACKET_THREE_FINGER_SWIPE_LEFT 0xd4
#define BYD_PACKET_FOUR_FINGER_DOWN 0x33
#define BYD_PACKET_FOUR_FINGER_UP 0xcd
#define BYD_PACKET_REGION_SCROLL_RIGHT 0x35
#define BYD_PACKET_REGION_SCROLL_DOWN 0x36
#define BYD_PACKET_REGION_SCROLL_UP 0xca
#define BYD_PACKET_REGION_SCROLL_LEFT 0xcb
#define BYD_PACKET_RIGHT_CORNER_CLICK 0xd2
#define BYD_PACKET_LEFT_CORNER_CLICK 0x2e
#define BYD_PACKET_LEFT_AND_RIGHT_CORNER_CLICK 0x2f
#define BYD_PACKET_ONTO_PAD_SWIPE_RIGHT 0x37
#define BYD_PACKET_ONTO_PAD_SWIPE_DOWN 0x30
#define BYD_PACKET_ONTO_PAD_SWIPE_UP 0xd0
#define BYD_PACKET_ONTO_PAD_SWIPE_LEFT 0xc9
struct byd_data {
struct timer_list timer;
struct psmouse *psmouse;
s32 abs_x;
s32 abs_y;
typeof(jiffies) last_touch_time;
bool btn_left;
bool btn_right;
bool touch;
};
static void byd_report_input(struct psmouse *psmouse)
{
struct byd_data *priv = psmouse->private;
struct input_dev *dev = psmouse->dev;
input_report_key(dev, BTN_TOUCH, priv->touch);
input_report_key(dev, BTN_TOOL_FINGER, priv->touch);
input_report_abs(dev, ABS_X, priv->abs_x);
input_report_abs(dev, ABS_Y, priv->abs_y);
input_report_key(dev, BTN_LEFT, priv->btn_left);
input_report_key(dev, BTN_RIGHT, priv->btn_right);
input_sync(dev);
}
static void byd_clear_touch(struct timer_list *t)
{
struct byd_data *priv = from_timer(priv, t, timer);
struct psmouse *psmouse = priv->psmouse;
serio_pause_rx(psmouse->ps2dev.serio);
priv->touch = false;
byd_report_input(psmouse);
serio_continue_rx(psmouse->ps2dev.serio);
/*
* Move cursor back to center of pad when we lose touch - this
* specifically improves user experience when moving cursor with one
* finger, and pressing a button with another.
*/
priv->abs_x = BYD_PAD_WIDTH / 2;
priv->abs_y = BYD_PAD_HEIGHT / 2;
}
static psmouse_ret_t byd_process_byte(struct psmouse *psmouse)
{
struct byd_data *priv = psmouse->private;
u8 *pkt = psmouse->packet;
if (psmouse->pktcnt > 0 && !(pkt[0] & PS2_ALWAYS_1)) {
psmouse_warn(psmouse, "Always_1 bit not 1. pkt[0] = %02x\n",
pkt[0]);
return PSMOUSE_BAD_DATA;
}
if (psmouse->pktcnt < psmouse->pktsize)
return PSMOUSE_GOOD_DATA;
/* Otherwise, a full packet has been received */
switch (pkt[3]) {
case BYD_PACKET_ABSOLUTE:
/* Only use absolute packets for the start of movement. */
if (!priv->touch) {
/* needed to detect tap */
typeof(jiffies) tap_time =
priv->last_touch_time + BYD_TOUCH_TIMEOUT;
priv->touch = time_after(jiffies, tap_time);
/* init abs position */
priv->abs_x = pkt[1] * (BYD_PAD_WIDTH / 256);
priv->abs_y = (255 - pkt[2]) * (BYD_PAD_HEIGHT / 256);
}
break;
case BYD_PACKET_RELATIVE: {
/* Standard packet */
/* Sign-extend if a sign bit is set. */
u32 signx = pkt[0] & PS2_X_SIGN ? ~0xFF : 0;
u32 signy = pkt[0] & PS2_Y_SIGN ? ~0xFF : 0;
s32 dx = signx | (int) pkt[1];
s32 dy = signy | (int) pkt[2];
/* Update position based on velocity */
priv->abs_x += dx * BYD_DT;
priv->abs_y -= dy * BYD_DT;
priv->touch = true;
break;
}
default:
psmouse_warn(psmouse,
"Unrecognized Z: pkt = %02x %02x %02x %02x\n",
psmouse->packet[0], psmouse->packet[1],
psmouse->packet[2], psmouse->packet[3]);
return PSMOUSE_BAD_DATA;
}
priv->btn_left = pkt[0] & PS2_LEFT;
priv->btn_right = pkt[0] & PS2_RIGHT;
byd_report_input(psmouse);
/* Reset time since last touch. */
if (priv->touch) {
priv->last_touch_time = jiffies;
mod_timer(&priv->timer, jiffies + BYD_TOUCH_TIMEOUT);
}
return PSMOUSE_FULL_PACKET;
}
static int byd_reset_touchpad(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
u8 param[4];
size_t i;
static const struct {
u16 command;
u8 arg;
} seq[] = {
/*
* Intellimouse initialization sequence, to get 4-byte instead
* of 3-byte packets.
*/
{ PSMOUSE_CMD_SETRATE, 0xC8 },
{ PSMOUSE_CMD_SETRATE, 0x64 },
{ PSMOUSE_CMD_SETRATE, 0x50 },
{ PSMOUSE_CMD_GETID, 0 },
{ PSMOUSE_CMD_ENABLE, 0 },
/*
* BYD-specific initialization, which enables absolute mode and
* (if desired), the touchpad's built-in gesture detection.
*/
{ 0x10E2, 0x00 },
{ 0x10E0, 0x02 },
/* The touchpad should reply with 4 seemingly-random bytes */
{ 0x14E0, 0x01 },
/* Pairs of parameters and values. */
{ BYD_CMD_SET_HANDEDNESS, 0x01 },
{ BYD_CMD_SET_PHYSICAL_BUTTONS, 0x04 },
{ BYD_CMD_SET_TAP, 0x02 },
{ BYD_CMD_SET_ONE_FINGER_SCROLL, 0x04 },
{ BYD_CMD_SET_ONE_FINGER_SCROLL_FUNC, 0x04 },
{ BYD_CMD_SET_EDGE_MOTION, 0x01 },
{ BYD_CMD_SET_PALM_CHECK, 0x00 },
{ BYD_CMD_SET_MULTITOUCH, 0x02 },
{ BYD_CMD_SET_TWO_FINGER_SCROLL, 0x04 },
{ BYD_CMD_SET_TWO_FINGER_SCROLL_FUNC, 0x04 },
{ BYD_CMD_SET_LEFT_EDGE_REGION, 0x00 },
{ BYD_CMD_SET_TOP_EDGE_REGION, 0x00 },
{ BYD_CMD_SET_RIGHT_EDGE_REGION, 0x00 },
{ BYD_CMD_SET_BOTTOM_EDGE_REGION, 0x00 },
{ BYD_CMD_SET_ABSOLUTE_MODE, 0x02 },
/* Finalize initialization. */
{ 0x10E0, 0x00 },
{ 0x10E2, 0x01 },
};
for (i = 0; i < ARRAY_SIZE(seq); ++i) {
memset(param, 0, sizeof(param));
param[0] = seq[i].arg;
if (ps2_command(ps2dev, param, seq[i].command))
return -EIO;
}
psmouse_set_state(psmouse, PSMOUSE_ACTIVATED);
return 0;
}
static int byd_reconnect(struct psmouse *psmouse)
{
int retry = 0, error = 0;
psmouse_dbg(psmouse, "Reconnect\n");
do {
psmouse_reset(psmouse);
if (retry)
ssleep(1);
error = byd_detect(psmouse, 0);
} while (error && ++retry < 3);
if (error)
return error;
psmouse_dbg(psmouse, "Reconnected after %d attempts\n", retry);
error = byd_reset_touchpad(psmouse);
if (error) {
psmouse_err(psmouse, "Unable to initialize device\n");
return error;
}
return 0;
}
static void byd_disconnect(struct psmouse *psmouse)
{
struct byd_data *priv = psmouse->private;
if (priv) {
del_timer(&priv->timer);
kfree(psmouse->private);
psmouse->private = NULL;
}
}
int byd_detect(struct psmouse *psmouse, bool set_properties)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
u8 param[4] = {0x03, 0x00, 0x00, 0x00};
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -1;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -1;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -1;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES))
return -1;
if (ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO))
return -1;
if (param[1] != 0x03 || param[2] != 0x64)
return -ENODEV;
psmouse_dbg(psmouse, "BYD touchpad detected\n");
if (set_properties) {
psmouse->vendor = "BYD";
psmouse->name = "TouchPad";
}
return 0;
}
int byd_init(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
struct byd_data *priv;
if (psmouse_reset(psmouse))
return -EIO;
if (byd_reset_touchpad(psmouse))
return -EIO;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->psmouse = psmouse;
timer_setup(&priv->timer, byd_clear_touch, 0);
psmouse->private = priv;
psmouse->disconnect = byd_disconnect;
psmouse->reconnect = byd_reconnect;
psmouse->protocol_handler = byd_process_byte;
psmouse->pktsize = 4;
psmouse->resync_time = 0;
__set_bit(INPUT_PROP_POINTER, dev->propbit);
/* Touchpad */
__set_bit(BTN_TOUCH, dev->keybit);
__set_bit(BTN_TOOL_FINGER, dev->keybit);
/* Buttons */
__set_bit(BTN_LEFT, dev->keybit);
__set_bit(BTN_RIGHT, dev->keybit);
__clear_bit(BTN_MIDDLE, dev->keybit);
/* Absolute position */
__set_bit(EV_ABS, dev->evbit);
input_set_abs_params(dev, ABS_X, 0, BYD_PAD_WIDTH, 0, 0);
input_set_abs_params(dev, ABS_Y, 0, BYD_PAD_HEIGHT, 0, 0);
input_abs_set_res(dev, ABS_X, BYD_PAD_RESOLUTION);
input_abs_set_res(dev, ABS_Y, BYD_PAD_RESOLUTION);
/* No relative support */
__clear_bit(EV_REL, dev->evbit);
__clear_bit(REL_X, dev->relbit);
__clear_bit(REL_Y, dev->relbit);
return 0;
}
|
linux-master
|
drivers/input/mouse/byd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* OLPC HGPK (XO-1) touchpad PS/2 mouse driver
*
* Copyright (c) 2006-2008 One Laptop Per Child
* Authors:
* Zephaniah E. Hull
* Andres Salomon <[email protected]>
*
* This driver is partly based on the ALPS driver, which is:
*
* Copyright (c) 2003 Neil Brown <[email protected]>
* Copyright (c) 2003-2005 Peter Osterlund <[email protected]>
* Copyright (c) 2004 Dmitry Torokhov <[email protected]>
* Copyright (c) 2005 Vojtech Pavlik <[email protected]>
*/
/*
* The spec from ALPS is available from
* <http://wiki.laptop.org/go/Touch_Pad/Tablet>. It refers to this
* device as HGPK (Hybrid GS, PT, and Keymatrix).
*
* The earliest versions of the device had simultaneous reporting; that
* was removed. After that, the device used the Advanced Mode GS/PT streaming
* stuff. That turned out to be too buggy to support, so we've finally
* switched to Mouse Mode (which utilizes only the center 1/3 of the touchpad).
*/
#define DEBUG
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include <linux/delay.h>
#include <asm/olpc.h>
#include "psmouse.h"
#include "hgpk.h"
#define ILLEGAL_XY 999999
static bool tpdebug;
module_param(tpdebug, bool, 0644);
MODULE_PARM_DESC(tpdebug, "enable debugging, dumping packets to KERN_DEBUG.");
static int recalib_delta = 100;
module_param(recalib_delta, int, 0644);
MODULE_PARM_DESC(recalib_delta,
"packets containing a delta this large will be discarded, and a "
"recalibration may be scheduled.");
static int jumpy_delay = 20;
module_param(jumpy_delay, int, 0644);
MODULE_PARM_DESC(jumpy_delay,
"delay (ms) before recal after jumpiness detected");
static int spew_delay = 1;
module_param(spew_delay, int, 0644);
MODULE_PARM_DESC(spew_delay,
"delay (ms) before recal after packet spew detected");
static int recal_guard_time;
module_param(recal_guard_time, int, 0644);
MODULE_PARM_DESC(recal_guard_time,
"interval (ms) during which recal will be restarted if packet received");
static int post_interrupt_delay = 40;
module_param(post_interrupt_delay, int, 0644);
MODULE_PARM_DESC(post_interrupt_delay,
"delay (ms) before recal after recal interrupt detected");
static bool autorecal = true;
module_param(autorecal, bool, 0644);
MODULE_PARM_DESC(autorecal, "enable recalibration in the driver");
static char hgpk_mode_name[16];
module_param_string(hgpk_mode, hgpk_mode_name, sizeof(hgpk_mode_name), 0644);
MODULE_PARM_DESC(hgpk_mode,
"default hgpk mode: mouse, glidesensor or pentablet");
static int hgpk_default_mode = HGPK_MODE_MOUSE;
static const char * const hgpk_mode_names[] = {
[HGPK_MODE_MOUSE] = "Mouse",
[HGPK_MODE_GLIDESENSOR] = "GlideSensor",
[HGPK_MODE_PENTABLET] = "PenTablet",
};
static int hgpk_mode_from_name(const char *buf, int len)
{
int i;
for (i = 0; i < ARRAY_SIZE(hgpk_mode_names); i++) {
const char *name = hgpk_mode_names[i];
if (strlen(name) == len && !strncasecmp(name, buf, len))
return i;
}
return HGPK_MODE_INVALID;
}
/*
* see if new value is within 20% of half of old value
*/
static int approx_half(int curr, int prev)
{
int belowhalf, abovehalf;
if (curr < 5 || prev < 5)
return 0;
belowhalf = (prev * 8) / 20;
abovehalf = (prev * 12) / 20;
return belowhalf < curr && curr <= abovehalf;
}
/*
* Throw out oddly large delta packets, and any that immediately follow whose
* values are each approximately half of the previous. It seems that the ALPS
* firmware emits errant packets, and they get averaged out slowly.
*/
static int hgpk_discard_decay_hack(struct psmouse *psmouse, int x, int y)
{
struct hgpk_data *priv = psmouse->private;
int avx, avy;
bool do_recal = false;
avx = abs(x);
avy = abs(y);
/* discard if too big, or half that but > 4 times the prev delta */
if (avx > recalib_delta ||
(avx > recalib_delta / 2 && ((avx / 4) > priv->xlast))) {
psmouse_warn(psmouse, "detected %dpx jump in x\n", x);
priv->xbigj = avx;
} else if (approx_half(avx, priv->xbigj)) {
psmouse_warn(psmouse, "detected secondary %dpx jump in x\n", x);
priv->xbigj = avx;
priv->xsaw_secondary++;
} else {
if (priv->xbigj && priv->xsaw_secondary > 1)
do_recal = true;
priv->xbigj = 0;
priv->xsaw_secondary = 0;
}
if (avy > recalib_delta ||
(avy > recalib_delta / 2 && ((avy / 4) > priv->ylast))) {
psmouse_warn(psmouse, "detected %dpx jump in y\n", y);
priv->ybigj = avy;
} else if (approx_half(avy, priv->ybigj)) {
psmouse_warn(psmouse, "detected secondary %dpx jump in y\n", y);
priv->ybigj = avy;
priv->ysaw_secondary++;
} else {
if (priv->ybigj && priv->ysaw_secondary > 1)
do_recal = true;
priv->ybigj = 0;
priv->ysaw_secondary = 0;
}
priv->xlast = avx;
priv->ylast = avy;
if (do_recal && jumpy_delay) {
psmouse_warn(psmouse, "scheduling recalibration\n");
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(jumpy_delay));
}
return priv->xbigj || priv->ybigj;
}
static void hgpk_reset_spew_detection(struct hgpk_data *priv)
{
priv->spew_count = 0;
priv->dupe_count = 0;
priv->x_tally = 0;
priv->y_tally = 0;
priv->spew_flag = NO_SPEW;
}
static void hgpk_reset_hack_state(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
priv->abs_x = priv->abs_y = -1;
priv->xlast = priv->ylast = ILLEGAL_XY;
priv->xbigj = priv->ybigj = 0;
priv->xsaw_secondary = priv->ysaw_secondary = 0;
hgpk_reset_spew_detection(priv);
}
/*
* We have no idea why this particular hardware bug occurs. The touchpad
* will randomly start spewing packets without anything touching the
* pad. This wouldn't necessarily be bad, but it's indicative of a
* severely miscalibrated pad; attempting to use the touchpad while it's
* spewing means the cursor will jump all over the place, and act "drunk".
*
* The packets that are spewed tend to all have deltas between -2 and 2, and
* the cursor will move around without really going very far. It will
* tend to end up in the same location; if we tally up the changes over
* 100 packets, we end up w/ a final delta of close to 0. This happens
* pretty regularly when the touchpad is spewing, and is pretty hard to
* manually trigger (at least for *my* fingers). So, it makes a perfect
* scheme for detecting spews.
*/
static void hgpk_spewing_hack(struct psmouse *psmouse,
int l, int r, int x, int y)
{
struct hgpk_data *priv = psmouse->private;
/* ignore button press packets; many in a row could trigger
* a false-positive! */
if (l || r)
return;
/* don't track spew if the workaround feature has been turned off */
if (!spew_delay)
return;
if (abs(x) > 3 || abs(y) > 3) {
/* no spew, or spew ended */
hgpk_reset_spew_detection(priv);
return;
}
/* Keep a tally of the overall delta to the cursor position caused by
* the spew */
priv->x_tally += x;
priv->y_tally += y;
switch (priv->spew_flag) {
case NO_SPEW:
/* we're not spewing, but this packet might be the start */
priv->spew_flag = MAYBE_SPEWING;
fallthrough;
case MAYBE_SPEWING:
priv->spew_count++;
if (priv->spew_count < SPEW_WATCH_COUNT)
break;
/* excessive spew detected, request recalibration */
priv->spew_flag = SPEW_DETECTED;
fallthrough;
case SPEW_DETECTED:
/* only recalibrate when the overall delta to the cursor
* is really small. if the spew is causing significant cursor
* movement, it is probably a case of the user moving the
* cursor very slowly across the screen. */
if (abs(priv->x_tally) < 3 && abs(priv->y_tally) < 3) {
psmouse_warn(psmouse, "packet spew detected (%d,%d)\n",
priv->x_tally, priv->y_tally);
priv->spew_flag = RECALIBRATING;
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(spew_delay));
}
break;
case RECALIBRATING:
/* we already detected a spew and requested a recalibration,
* just wait for the queue to kick into action. */
break;
}
}
/*
* HGPK Mouse Mode format (standard mouse format, sans middle button)
*
* byte 0: y-over x-over y-neg x-neg 1 0 swr swl
* byte 1: x7 x6 x5 x4 x3 x2 x1 x0
* byte 2: y7 y6 y5 y4 y3 y2 y1 y0
*
* swr/swl are the left/right buttons.
* x-neg/y-neg are the x and y delta negative bits
* x-over/y-over are the x and y overflow bits
*
* ---
*
* HGPK Advanced Mode - single-mode format
*
* byte 0(PT): 1 1 0 0 1 1 1 1
* byte 0(GS): 1 1 1 1 1 1 1 1
* byte 1: 0 x6 x5 x4 x3 x2 x1 x0
* byte 2(PT): 0 0 x9 x8 x7 ? pt-dsw 0
* byte 2(GS): 0 x10 x9 x8 x7 ? gs-dsw pt-dsw
* byte 3: 0 y9 y8 y7 1 0 swr swl
* byte 4: 0 y6 y5 y4 y3 y2 y1 y0
* byte 5: 0 z6 z5 z4 z3 z2 z1 z0
*
* ?'s are not defined in the protocol spec, may vary between models.
*
* swr/swl are the left/right buttons.
*
* pt-dsw/gs-dsw indicate that the pt/gs sensor is detecting a
* pen/finger
*/
static bool hgpk_is_byte_valid(struct psmouse *psmouse, unsigned char *packet)
{
struct hgpk_data *priv = psmouse->private;
int pktcnt = psmouse->pktcnt;
bool valid;
switch (priv->mode) {
case HGPK_MODE_MOUSE:
valid = (packet[0] & 0x0C) == 0x08;
break;
case HGPK_MODE_GLIDESENSOR:
valid = pktcnt == 1 ?
packet[0] == HGPK_GS : !(packet[pktcnt - 1] & 0x80);
break;
case HGPK_MODE_PENTABLET:
valid = pktcnt == 1 ?
packet[0] == HGPK_PT : !(packet[pktcnt - 1] & 0x80);
break;
default:
valid = false;
break;
}
if (!valid)
psmouse_dbg(psmouse,
"bad data, mode %d (%d) %*ph\n",
priv->mode, pktcnt, 6, psmouse->packet);
return valid;
}
static void hgpk_process_advanced_packet(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
struct input_dev *idev = psmouse->dev;
unsigned char *packet = psmouse->packet;
int down = !!(packet[2] & 2);
int left = !!(packet[3] & 1);
int right = !!(packet[3] & 2);
int x = packet[1] | ((packet[2] & 0x78) << 4);
int y = packet[4] | ((packet[3] & 0x70) << 3);
if (priv->mode == HGPK_MODE_GLIDESENSOR) {
int pt_down = !!(packet[2] & 1);
int finger_down = !!(packet[2] & 2);
int z = packet[5];
input_report_abs(idev, ABS_PRESSURE, z);
if (tpdebug)
psmouse_dbg(psmouse, "pd=%d fd=%d z=%d",
pt_down, finger_down, z);
} else {
/*
* PenTablet mode does not report pressure, so we don't
* report it here
*/
if (tpdebug)
psmouse_dbg(psmouse, "pd=%d ", down);
}
if (tpdebug)
psmouse_dbg(psmouse, "l=%d r=%d x=%d y=%d\n",
left, right, x, y);
input_report_key(idev, BTN_TOUCH, down);
input_report_key(idev, BTN_LEFT, left);
input_report_key(idev, BTN_RIGHT, right);
/*
* If this packet says that the finger was removed, reset our position
* tracking so that we don't erroneously detect a jump on next press.
*/
if (!down) {
hgpk_reset_hack_state(psmouse);
goto done;
}
/*
* Weed out duplicate packets (we get quite a few, and they mess up
* our jump detection)
*/
if (x == priv->abs_x && y == priv->abs_y) {
if (++priv->dupe_count > SPEW_WATCH_COUNT) {
if (tpdebug)
psmouse_dbg(psmouse, "hard spew detected\n");
priv->spew_flag = RECALIBRATING;
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(spew_delay));
}
goto done;
}
/* not a duplicate, continue with position reporting */
priv->dupe_count = 0;
/* Don't apply hacks in PT mode, it seems reliable */
if (priv->mode != HGPK_MODE_PENTABLET && priv->abs_x != -1) {
int x_diff = priv->abs_x - x;
int y_diff = priv->abs_y - y;
if (hgpk_discard_decay_hack(psmouse, x_diff, y_diff)) {
if (tpdebug)
psmouse_dbg(psmouse, "discarding\n");
goto done;
}
hgpk_spewing_hack(psmouse, left, right, x_diff, y_diff);
}
input_report_abs(idev, ABS_X, x);
input_report_abs(idev, ABS_Y, y);
priv->abs_x = x;
priv->abs_y = y;
done:
input_sync(idev);
}
static void hgpk_process_simple_packet(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
int left = packet[0] & 1;
int right = (packet[0] >> 1) & 1;
int x = packet[1] - ((packet[0] << 4) & 0x100);
int y = ((packet[0] << 3) & 0x100) - packet[2];
if (packet[0] & 0xc0)
psmouse_dbg(psmouse,
"overflow -- 0x%02x 0x%02x 0x%02x\n",
packet[0], packet[1], packet[2]);
if (hgpk_discard_decay_hack(psmouse, x, y)) {
if (tpdebug)
psmouse_dbg(psmouse, "discarding\n");
return;
}
hgpk_spewing_hack(psmouse, left, right, x, y);
if (tpdebug)
psmouse_dbg(psmouse, "l=%d r=%d x=%d y=%d\n",
left, right, x, y);
input_report_key(dev, BTN_LEFT, left);
input_report_key(dev, BTN_RIGHT, right);
input_report_rel(dev, REL_X, x);
input_report_rel(dev, REL_Y, y);
input_sync(dev);
}
static psmouse_ret_t hgpk_process_byte(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
if (!hgpk_is_byte_valid(psmouse, psmouse->packet))
return PSMOUSE_BAD_DATA;
if (psmouse->pktcnt >= psmouse->pktsize) {
if (priv->mode == HGPK_MODE_MOUSE)
hgpk_process_simple_packet(psmouse);
else
hgpk_process_advanced_packet(psmouse);
return PSMOUSE_FULL_PACKET;
}
if (priv->recalib_window) {
if (time_before(jiffies, priv->recalib_window)) {
/*
* ugh, got a packet inside our recalibration
* window, schedule another recalibration.
*/
psmouse_dbg(psmouse,
"packet inside calibration window, queueing another recalibration\n");
psmouse_queue_work(psmouse, &priv->recalib_wq,
msecs_to_jiffies(post_interrupt_delay));
}
priv->recalib_window = 0;
}
return PSMOUSE_GOOD_DATA;
}
static int hgpk_select_mode(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
struct hgpk_data *priv = psmouse->private;
int i;
int cmd;
/*
* 4 disables to enable advanced mode
* then 3 0xf2 bytes as the preamble for GS/PT selection
*/
const int advanced_init[] = {
PSMOUSE_CMD_DISABLE, PSMOUSE_CMD_DISABLE,
PSMOUSE_CMD_DISABLE, PSMOUSE_CMD_DISABLE,
0xf2, 0xf2, 0xf2,
};
switch (priv->mode) {
case HGPK_MODE_MOUSE:
psmouse->pktsize = 3;
break;
case HGPK_MODE_GLIDESENSOR:
case HGPK_MODE_PENTABLET:
psmouse->pktsize = 6;
/* Switch to 'Advanced mode.', four disables in a row. */
for (i = 0; i < ARRAY_SIZE(advanced_init); i++)
if (ps2_command(ps2dev, NULL, advanced_init[i]))
return -EIO;
/* select between GlideSensor (mouse) or PenTablet */
cmd = priv->mode == HGPK_MODE_GLIDESENSOR ?
PSMOUSE_CMD_SETSCALE11 : PSMOUSE_CMD_SETSCALE21;
if (ps2_command(ps2dev, NULL, cmd))
return -EIO;
break;
default:
return -EINVAL;
}
return 0;
}
static void hgpk_setup_input_device(struct input_dev *input,
struct input_dev *old_input,
enum hgpk_mode mode)
{
if (old_input) {
input->name = old_input->name;
input->phys = old_input->phys;
input->id = old_input->id;
input->dev.parent = old_input->dev.parent;
}
memset(input->evbit, 0, sizeof(input->evbit));
memset(input->relbit, 0, sizeof(input->relbit));
memset(input->keybit, 0, sizeof(input->keybit));
/* All modes report left and right buttons */
__set_bit(EV_KEY, input->evbit);
__set_bit(BTN_LEFT, input->keybit);
__set_bit(BTN_RIGHT, input->keybit);
switch (mode) {
case HGPK_MODE_MOUSE:
__set_bit(EV_REL, input->evbit);
__set_bit(REL_X, input->relbit);
__set_bit(REL_Y, input->relbit);
break;
case HGPK_MODE_GLIDESENSOR:
__set_bit(BTN_TOUCH, input->keybit);
__set_bit(BTN_TOOL_FINGER, input->keybit);
__set_bit(EV_ABS, input->evbit);
/* GlideSensor has pressure sensor, PenTablet does not */
input_set_abs_params(input, ABS_PRESSURE, 0, 15, 0, 0);
/* From device specs */
input_set_abs_params(input, ABS_X, 0, 399, 0, 0);
input_set_abs_params(input, ABS_Y, 0, 290, 0, 0);
/* Calculated by hand based on usable size (52mm x 38mm) */
input_abs_set_res(input, ABS_X, 8);
input_abs_set_res(input, ABS_Y, 8);
break;
case HGPK_MODE_PENTABLET:
__set_bit(BTN_TOUCH, input->keybit);
__set_bit(BTN_TOOL_FINGER, input->keybit);
__set_bit(EV_ABS, input->evbit);
/* From device specs */
input_set_abs_params(input, ABS_X, 0, 999, 0, 0);
input_set_abs_params(input, ABS_Y, 5, 239, 0, 0);
/* Calculated by hand based on usable size (156mm x 38mm) */
input_abs_set_res(input, ABS_X, 6);
input_abs_set_res(input, ABS_Y, 8);
break;
default:
BUG();
}
}
static int hgpk_reset_device(struct psmouse *psmouse, bool recalibrate)
{
int err;
psmouse_reset(psmouse);
if (recalibrate) {
struct ps2dev *ps2dev = &psmouse->ps2dev;
/* send the recalibrate request */
if (ps2_command(ps2dev, NULL, 0xf5) ||
ps2_command(ps2dev, NULL, 0xf5) ||
ps2_command(ps2dev, NULL, 0xe6) ||
ps2_command(ps2dev, NULL, 0xf5)) {
return -1;
}
/* according to ALPS, 150mS is required for recalibration */
msleep(150);
}
err = hgpk_select_mode(psmouse);
if (err) {
psmouse_err(psmouse, "failed to select mode\n");
return err;
}
hgpk_reset_hack_state(psmouse);
return 0;
}
static int hgpk_force_recalibrate(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
int err;
/* C-series touchpads added the recalibrate command */
if (psmouse->model < HGPK_MODEL_C)
return 0;
if (!autorecal) {
psmouse_dbg(psmouse, "recalibration disabled, ignoring\n");
return 0;
}
psmouse_dbg(psmouse, "recalibrating touchpad..\n");
/* we don't want to race with the irq handler, nor with resyncs */
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/* start by resetting the device */
err = hgpk_reset_device(psmouse, true);
if (err)
return err;
/*
* XXX: If a finger is down during this delay, recalibration will
* detect capacitance incorrectly. This is a hardware bug, and
* we don't have a good way to deal with it. The 2s window stuff
* (below) is our best option for now.
*/
if (psmouse_activate(psmouse))
return -1;
if (tpdebug)
psmouse_dbg(psmouse, "touchpad reactivated\n");
/*
* If we get packets right away after recalibrating, it's likely
* that a finger was on the touchpad. If so, it's probably
* miscalibrated, so we optionally schedule another.
*/
if (recal_guard_time)
priv->recalib_window = jiffies +
msecs_to_jiffies(recal_guard_time);
return 0;
}
/*
* This puts the touchpad in a power saving mode; according to ALPS, current
* consumption goes down to 50uA after running this. To turn power back on,
* we drive MS-DAT low. Measuring with a 1mA resolution ammeter says that
* the current on the SUS_3.3V rail drops from 3mA or 4mA to 0 when we do this.
*
* We have no formal spec that details this operation -- the low-power
* sequence came from a long-lost email trail.
*/
static int hgpk_toggle_powersave(struct psmouse *psmouse, int enable)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
int timeo;
int err;
/* Added on D-series touchpads */
if (psmouse->model < HGPK_MODEL_D)
return 0;
if (enable) {
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/*
* Sending a byte will drive MS-DAT low; this will wake up
* the controller. Once we get an ACK back from it, it
* means we can continue with the touchpad re-init. ALPS
* tells us that 1s should be long enough, so set that as
* the upper bound. (in practice, it takes about 3 loops.)
*/
for (timeo = 20; timeo > 0; timeo--) {
if (!ps2_sendbyte(ps2dev, PSMOUSE_CMD_DISABLE, 20))
break;
msleep(25);
}
err = hgpk_reset_device(psmouse, false);
if (err) {
psmouse_err(psmouse, "Failed to reset device!\n");
return err;
}
/* should be all set, enable the touchpad */
psmouse_activate(psmouse);
psmouse_dbg(psmouse, "Touchpad powered up.\n");
} else {
psmouse_dbg(psmouse, "Powering off touchpad.\n");
if (ps2_command(ps2dev, NULL, 0xec) ||
ps2_command(ps2dev, NULL, 0xec) ||
ps2_command(ps2dev, NULL, 0xea)) {
return -1;
}
psmouse_set_state(psmouse, PSMOUSE_IGNORE);
/* probably won't see an ACK, the touchpad will be off */
ps2_sendbyte(ps2dev, 0xec, 20);
}
return 0;
}
static int hgpk_poll(struct psmouse *psmouse)
{
/* We can't poll, so always return failure. */
return -1;
}
static int hgpk_reconnect(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
/*
* During suspend/resume the ps2 rails remain powered. We don't want
* to do a reset because it's flush data out of buffers; however,
* earlier prototypes (B1) had some brokenness that required a reset.
*/
if (olpc_board_at_least(olpc_board(0xb2)))
if (psmouse->ps2dev.serio->dev.power.power_state.event !=
PM_EVENT_ON)
return 0;
priv->powered = 1;
return hgpk_reset_device(psmouse, false);
}
static ssize_t hgpk_show_powered(struct psmouse *psmouse, void *data, char *buf)
{
struct hgpk_data *priv = psmouse->private;
return sprintf(buf, "%d\n", priv->powered);
}
static ssize_t hgpk_set_powered(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct hgpk_data *priv = psmouse->private;
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
if (value != priv->powered) {
/*
* hgpk_toggle_power will deal w/ state so
* we're not racing w/ irq
*/
err = hgpk_toggle_powersave(psmouse, value);
if (!err)
priv->powered = value;
}
return err ? err : count;
}
__PSMOUSE_DEFINE_ATTR(powered, S_IWUSR | S_IRUGO, NULL,
hgpk_show_powered, hgpk_set_powered, false);
static ssize_t attr_show_mode(struct psmouse *psmouse, void *data, char *buf)
{
struct hgpk_data *priv = psmouse->private;
return sprintf(buf, "%s\n", hgpk_mode_names[priv->mode]);
}
static ssize_t attr_set_mode(struct psmouse *psmouse, void *data,
const char *buf, size_t len)
{
struct hgpk_data *priv = psmouse->private;
enum hgpk_mode old_mode = priv->mode;
enum hgpk_mode new_mode = hgpk_mode_from_name(buf, len);
struct input_dev *old_dev = psmouse->dev;
struct input_dev *new_dev;
int err;
if (new_mode == HGPK_MODE_INVALID)
return -EINVAL;
if (old_mode == new_mode)
return len;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
psmouse_set_state(psmouse, PSMOUSE_INITIALIZING);
/* Switch device into the new mode */
priv->mode = new_mode;
err = hgpk_reset_device(psmouse, false);
if (err)
goto err_try_restore;
hgpk_setup_input_device(new_dev, old_dev, new_mode);
psmouse_set_state(psmouse, PSMOUSE_CMD_MODE);
err = input_register_device(new_dev);
if (err)
goto err_try_restore;
psmouse->dev = new_dev;
input_unregister_device(old_dev);
return len;
err_try_restore:
input_free_device(new_dev);
priv->mode = old_mode;
hgpk_reset_device(psmouse, false);
return err;
}
PSMOUSE_DEFINE_ATTR(hgpk_mode, S_IWUSR | S_IRUGO, NULL,
attr_show_mode, attr_set_mode);
static ssize_t hgpk_trigger_recal_show(struct psmouse *psmouse,
void *data, char *buf)
{
return -EINVAL;
}
static ssize_t hgpk_trigger_recal(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
struct hgpk_data *priv = psmouse->private;
unsigned int value;
int err;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value != 1)
return -EINVAL;
/*
* We queue work instead of doing recalibration right here
* to avoid adding locking to hgpk_force_recalibrate()
* since workqueue provides serialization.
*/
psmouse_queue_work(psmouse, &priv->recalib_wq, 0);
return count;
}
__PSMOUSE_DEFINE_ATTR(recalibrate, S_IWUSR | S_IRUGO, NULL,
hgpk_trigger_recal_show, hgpk_trigger_recal, false);
static void hgpk_disconnect(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
if (psmouse->model >= HGPK_MODEL_C)
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_recalibrate.dattr);
psmouse_reset(psmouse);
kfree(priv);
}
static void hgpk_recalib_work(struct work_struct *work)
{
struct delayed_work *w = to_delayed_work(work);
struct hgpk_data *priv = container_of(w, struct hgpk_data, recalib_wq);
struct psmouse *psmouse = priv->psmouse;
if (hgpk_force_recalibrate(psmouse))
psmouse_err(psmouse, "recalibration failed!\n");
}
static int hgpk_register(struct psmouse *psmouse)
{
struct hgpk_data *priv = psmouse->private;
int err;
/* register handlers */
psmouse->protocol_handler = hgpk_process_byte;
psmouse->poll = hgpk_poll;
psmouse->disconnect = hgpk_disconnect;
psmouse->reconnect = hgpk_reconnect;
/* Disable the idle resync. */
psmouse->resync_time = 0;
/* Reset after a lot of bad bytes. */
psmouse->resetafter = 1024;
hgpk_setup_input_device(psmouse->dev, NULL, priv->mode);
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
if (err) {
psmouse_err(psmouse, "Failed creating 'powered' sysfs node\n");
return err;
}
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
if (err) {
psmouse_err(psmouse,
"Failed creating 'hgpk_mode' sysfs node\n");
goto err_remove_powered;
}
/* C-series touchpads added the recalibrate command */
if (psmouse->model >= HGPK_MODEL_C) {
err = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_recalibrate.dattr);
if (err) {
psmouse_err(psmouse,
"Failed creating 'recalibrate' sysfs node\n");
goto err_remove_mode;
}
}
return 0;
err_remove_mode:
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_hgpk_mode.dattr);
err_remove_powered:
device_remove_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_powered.dattr);
return err;
}
int hgpk_init(struct psmouse *psmouse)
{
struct hgpk_data *priv;
int err;
priv = kzalloc(sizeof(struct hgpk_data), GFP_KERNEL);
if (!priv) {
err = -ENOMEM;
goto alloc_fail;
}
psmouse->private = priv;
priv->psmouse = psmouse;
priv->powered = true;
priv->mode = hgpk_default_mode;
INIT_DELAYED_WORK(&priv->recalib_wq, hgpk_recalib_work);
err = hgpk_reset_device(psmouse, false);
if (err)
goto init_fail;
err = hgpk_register(psmouse);
if (err)
goto init_fail;
return 0;
init_fail:
kfree(priv);
alloc_fail:
return err;
}
static enum hgpk_model_t hgpk_get_model(struct psmouse *psmouse)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[3];
/* E7, E7, E7, E9 gets us a 3 byte identifier */
if (ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE21) ||
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO)) {
return -EIO;
}
psmouse_dbg(psmouse, "ID: %*ph\n", 3, param);
/* HGPK signature: 0x67, 0x00, 0x<model> */
if (param[0] != 0x67 || param[1] != 0x00)
return -ENODEV;
psmouse_info(psmouse, "OLPC touchpad revision 0x%x\n", param[2]);
return param[2];
}
int hgpk_detect(struct psmouse *psmouse, bool set_properties)
{
int version;
version = hgpk_get_model(psmouse);
if (version < 0)
return version;
if (set_properties) {
psmouse->vendor = "ALPS";
psmouse->name = "HGPK";
psmouse->model = version;
}
return 0;
}
void hgpk_module_init(void)
{
hgpk_default_mode = hgpk_mode_from_name(hgpk_mode_name,
strlen(hgpk_mode_name));
if (hgpk_default_mode == HGPK_MODE_INVALID) {
hgpk_default_mode = HGPK_MODE_MOUSE;
strscpy(hgpk_mode_name, hgpk_mode_names[HGPK_MODE_MOUSE],
sizeof(hgpk_mode_name));
}
}
|
linux-master
|
drivers/input/mouse/hgpk.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
* Copyright (c) 1999 Brian Gerst
*/
/*
* NS558 based standard IBM game port driver for Linux
*/
#include <asm/io.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/gameport.h>
#include <linux/slab.h>
#include <linux/pnp.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("Classic gameport (ISA/PnP) driver");
MODULE_LICENSE("GPL");
static int ns558_isa_portlist[] = { 0x201, 0x200, 0x202, 0x203, 0x204, 0x205, 0x207, 0x209,
0x20b, 0x20c, 0x20e, 0x20f, 0x211, 0x219, 0x101, 0 };
struct ns558 {
int type;
int io;
int size;
struct pnp_dev *dev;
struct gameport *gameport;
struct list_head node;
};
static LIST_HEAD(ns558_list);
/*
* ns558_isa_probe() tries to find an isa gameport at the
* specified address, and also checks for mirrors.
* A joystick must be attached for this to work.
*/
static int ns558_isa_probe(int io)
{
int i, j, b;
unsigned char c, u, v;
struct ns558 *ns558;
struct gameport *port;
/*
* No one should be using this address.
*/
if (!request_region(io, 1, "ns558-isa"))
return -EBUSY;
/*
* We must not be able to write arbitrary values to the port.
* The lower two axis bits must be 1 after a write.
*/
c = inb(io);
outb(~c & ~3, io);
if (~(u = v = inb(io)) & 3) {
outb(c, io);
release_region(io, 1);
return -ENODEV;
}
/*
* After a trigger, there must be at least some bits changing.
*/
for (i = 0; i < 1000; i++) v &= inb(io);
if (u == v) {
outb(c, io);
release_region(io, 1);
return -ENODEV;
}
msleep(3);
/*
* After some time (4ms) the axes shouldn't change anymore.
*/
u = inb(io);
for (i = 0; i < 1000; i++)
if ((u ^ inb(io)) & 0xf) {
outb(c, io);
release_region(io, 1);
return -ENODEV;
}
/*
* And now find the number of mirrors of the port.
*/
for (i = 1; i < 5; i++) {
release_region(io & (-1 << (i - 1)), (1 << (i - 1)));
if (!request_region(io & (-1 << i), (1 << i), "ns558-isa"))
break; /* Don't disturb anyone */
outb(0xff, io & (-1 << i));
for (j = b = 0; j < 1000; j++)
if (inb(io & (-1 << i)) != inb((io & (-1 << i)) + (1 << i) - 1)) b++;
msleep(3);
if (b > 300) { /* We allow 30% difference */
release_region(io & (-1 << i), (1 << i));
break;
}
}
i--;
if (i != 4) {
if (!request_region(io & (-1 << i), (1 << i), "ns558-isa"))
return -EBUSY;
}
ns558 = kzalloc(sizeof(struct ns558), GFP_KERNEL);
port = gameport_allocate_port();
if (!ns558 || !port) {
printk(KERN_ERR "ns558: Memory allocation failed.\n");
release_region(io & (-1 << i), (1 << i));
kfree(ns558);
gameport_free_port(port);
return -ENOMEM;
}
ns558->io = io;
ns558->size = 1 << i;
ns558->gameport = port;
port->io = io;
gameport_set_name(port, "NS558 ISA Gameport");
gameport_set_phys(port, "isa%04x/gameport0", io & (-1 << i));
gameport_register_port(port);
list_add(&ns558->node, &ns558_list);
return 0;
}
#ifdef CONFIG_PNP
static const struct pnp_device_id pnp_devids[] = {
{ .id = "@P@0001", .driver_data = 0 }, /* ALS 100 */
{ .id = "@P@0020", .driver_data = 0 }, /* ALS 200 */
{ .id = "@P@1001", .driver_data = 0 }, /* ALS 100+ */
{ .id = "@P@2001", .driver_data = 0 }, /* ALS 120 */
{ .id = "ASB16fd", .driver_data = 0 }, /* AdLib NSC16 */
{ .id = "AZT3001", .driver_data = 0 }, /* AZT1008 */
{ .id = "CDC0001", .driver_data = 0 }, /* Opl3-SAx */
{ .id = "CSC0001", .driver_data = 0 }, /* CS4232 */
{ .id = "CSC000f", .driver_data = 0 }, /* CS4236 */
{ .id = "CSC0101", .driver_data = 0 }, /* CS4327 */
{ .id = "CTL7001", .driver_data = 0 }, /* SB16 */
{ .id = "CTL7002", .driver_data = 0 }, /* AWE64 */
{ .id = "CTL7005", .driver_data = 0 }, /* Vibra16 */
{ .id = "ENS2020", .driver_data = 0 }, /* SoundscapeVIVO */
{ .id = "ESS0001", .driver_data = 0 }, /* ES1869 */
{ .id = "ESS0005", .driver_data = 0 }, /* ES1878 */
{ .id = "ESS6880", .driver_data = 0 }, /* ES688 */
{ .id = "IBM0012", .driver_data = 0 }, /* CS4232 */
{ .id = "OPT0001", .driver_data = 0 }, /* OPTi Audio16 */
{ .id = "YMH0006", .driver_data = 0 }, /* Opl3-SA */
{ .id = "YMH0022", .driver_data = 0 }, /* Opl3-SAx */
{ .id = "PNPb02f", .driver_data = 0 }, /* Generic */
{ .id = "", },
};
MODULE_DEVICE_TABLE(pnp, pnp_devids);
static int ns558_pnp_probe(struct pnp_dev *dev, const struct pnp_device_id *did)
{
int ioport, iolen;
struct ns558 *ns558;
struct gameport *port;
if (!pnp_port_valid(dev, 0)) {
printk(KERN_WARNING "ns558: No i/o ports on a gameport? Weird\n");
return -ENODEV;
}
ioport = pnp_port_start(dev, 0);
iolen = pnp_port_len(dev, 0);
if (!request_region(ioport, iolen, "ns558-pnp"))
return -EBUSY;
ns558 = kzalloc(sizeof(struct ns558), GFP_KERNEL);
port = gameport_allocate_port();
if (!ns558 || !port) {
printk(KERN_ERR "ns558: Memory allocation failed\n");
kfree(ns558);
gameport_free_port(port);
return -ENOMEM;
}
ns558->io = ioport;
ns558->size = iolen;
ns558->dev = dev;
ns558->gameport = port;
gameport_set_name(port, "NS558 PnP Gameport");
gameport_set_phys(port, "pnp%s/gameport0", dev_name(&dev->dev));
port->dev.parent = &dev->dev;
port->io = ioport;
gameport_register_port(port);
list_add_tail(&ns558->node, &ns558_list);
return 0;
}
static struct pnp_driver ns558_pnp_driver = {
.name = "ns558",
.id_table = pnp_devids,
.probe = ns558_pnp_probe,
};
#else
static struct pnp_driver ns558_pnp_driver;
#endif
static int __init ns558_init(void)
{
int i = 0;
int error;
error = pnp_register_driver(&ns558_pnp_driver);
if (error && error != -ENODEV) /* should be ENOSYS really */
return error;
/*
* Probe ISA ports after PnP, so that PnP ports that are already
* enabled get detected as PnP. This may be suboptimal in multi-device
* configurations, but saves hassle with simple setups.
*/
while (ns558_isa_portlist[i])
ns558_isa_probe(ns558_isa_portlist[i++]);
return list_empty(&ns558_list) && error ? -ENODEV : 0;
}
static void __exit ns558_exit(void)
{
struct ns558 *ns558, *safe;
list_for_each_entry_safe(ns558, safe, &ns558_list, node) {
gameport_unregister_port(ns558->gameport);
release_region(ns558->io & ~(ns558->size - 1), ns558->size);
kfree(ns558);
}
pnp_unregister_driver(&ns558_pnp_driver);
}
module_init(ns558_init);
module_exit(ns558_exit);
|
linux-master
|
drivers/input/gameport/ns558.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* FM801 gameport driver for Linux
*
* Copyright (c) by Takashi Iwai <[email protected]>
*/
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#define PCI_VENDOR_ID_FORTEMEDIA 0x1319
#define PCI_DEVICE_ID_FM801_GP 0x0802
#define HAVE_COOKED
struct fm801_gp {
struct gameport *gameport;
struct resource *res_port;
};
#ifdef HAVE_COOKED
static int fm801_gp_cooked_read(struct gameport *gameport, int *axes, int *buttons)
{
unsigned short w;
w = inw(gameport->io + 2);
*buttons = (~w >> 14) & 0x03;
axes[0] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
w = inw(gameport->io + 4);
axes[1] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
w = inw(gameport->io + 6);
*buttons |= ((~w >> 14) & 0x03) << 2;
axes[2] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
w = inw(gameport->io + 8);
axes[3] = (w == 0xffff) ? -1 : ((w & 0x1fff) << 5);
outw(0xff, gameport->io); /* reset */
return 0;
}
#endif
static int fm801_gp_open(struct gameport *gameport, int mode)
{
switch (mode) {
#ifdef HAVE_COOKED
case GAMEPORT_MODE_COOKED:
return 0;
#endif
case GAMEPORT_MODE_RAW:
return 0;
default:
return -1;
}
return 0;
}
static int fm801_gp_probe(struct pci_dev *pci, const struct pci_device_id *id)
{
struct fm801_gp *gp;
struct gameport *port;
int error;
gp = kzalloc(sizeof(struct fm801_gp), GFP_KERNEL);
port = gameport_allocate_port();
if (!gp || !port) {
printk(KERN_ERR "fm801-gp: Memory allocation failed\n");
error = -ENOMEM;
goto err_out_free;
}
error = pci_enable_device(pci);
if (error)
goto err_out_free;
port->open = fm801_gp_open;
#ifdef HAVE_COOKED
port->cooked_read = fm801_gp_cooked_read;
#endif
gameport_set_name(port, "FM801");
gameport_set_phys(port, "pci%s/gameport0", pci_name(pci));
port->dev.parent = &pci->dev;
port->io = pci_resource_start(pci, 0);
gp->gameport = port;
gp->res_port = request_region(port->io, 0x10, "FM801 GP");
if (!gp->res_port) {
printk(KERN_DEBUG "fm801-gp: unable to grab region 0x%x-0x%x\n",
port->io, port->io + 0x0f);
error = -EBUSY;
goto err_out_disable_dev;
}
pci_set_drvdata(pci, gp);
outb(0x60, port->io + 0x0d); /* enable joystick 1 and 2 */
gameport_register_port(port);
return 0;
err_out_disable_dev:
pci_disable_device(pci);
err_out_free:
gameport_free_port(port);
kfree(gp);
return error;
}
static void fm801_gp_remove(struct pci_dev *pci)
{
struct fm801_gp *gp = pci_get_drvdata(pci);
gameport_unregister_port(gp->gameport);
release_resource(gp->res_port);
kfree(gp);
pci_disable_device(pci);
}
static const struct pci_device_id fm801_gp_id_table[] = {
{ PCI_VENDOR_ID_FORTEMEDIA, PCI_DEVICE_ID_FM801_GP, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, fm801_gp_id_table);
static struct pci_driver fm801_gp_driver = {
.name = "FM801_gameport",
.id_table = fm801_gp_id_table,
.probe = fm801_gp_probe,
.remove = fm801_gp_remove,
};
module_pci_driver(fm801_gp_driver);
MODULE_DESCRIPTION("FM801 gameport driver");
MODULE_AUTHOR("Takashi Iwai <[email protected]>");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/gameport/fm801-gp.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2001 Vojtech Pavlik
*/
/*
* EMU10k1 - SB Live / Audigy - gameport driver for Linux
*/
#include <asm/io.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/gameport.h>
#include <linux/slab.h>
#include <linux/pci.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("EMU10k1 gameport driver");
MODULE_LICENSE("GPL");
struct emu {
struct pci_dev *dev;
struct gameport *gameport;
int io;
int size;
};
static const struct pci_device_id emu_tbl[] = {
{ 0x1102, 0x7002, PCI_ANY_ID, PCI_ANY_ID }, /* SB Live gameport */
{ 0x1102, 0x7003, PCI_ANY_ID, PCI_ANY_ID }, /* Audigy gameport */
{ 0x1102, 0x7004, PCI_ANY_ID, PCI_ANY_ID }, /* Dell SB Live */
{ 0x1102, 0x7005, PCI_ANY_ID, PCI_ANY_ID }, /* Audigy LS gameport */
{ 0, }
};
MODULE_DEVICE_TABLE(pci, emu_tbl);
static int emu_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
{
struct emu *emu;
struct gameport *port;
int error;
emu = kzalloc(sizeof(struct emu), GFP_KERNEL);
port = gameport_allocate_port();
if (!emu || !port) {
printk(KERN_ERR "emu10k1-gp: Memory allocation failed\n");
error = -ENOMEM;
goto err_out_free;
}
error = pci_enable_device(pdev);
if (error)
goto err_out_free;
emu->io = pci_resource_start(pdev, 0);
emu->size = pci_resource_len(pdev, 0);
emu->dev = pdev;
emu->gameport = port;
gameport_set_name(port, "EMU10K1");
gameport_set_phys(port, "pci%s/gameport0", pci_name(pdev));
port->dev.parent = &pdev->dev;
port->io = emu->io;
if (!request_region(emu->io, emu->size, "emu10k1-gp")) {
printk(KERN_ERR "emu10k1-gp: unable to grab region 0x%x-0x%x\n",
emu->io, emu->io + emu->size - 1);
error = -EBUSY;
goto err_out_disable_dev;
}
pci_set_drvdata(pdev, emu);
gameport_register_port(port);
return 0;
err_out_disable_dev:
pci_disable_device(pdev);
err_out_free:
gameport_free_port(port);
kfree(emu);
return error;
}
static void emu_remove(struct pci_dev *pdev)
{
struct emu *emu = pci_get_drvdata(pdev);
gameport_unregister_port(emu->gameport);
release_region(emu->io, emu->size);
kfree(emu);
pci_disable_device(pdev);
}
static struct pci_driver emu_driver = {
.name = "Emu10k1_gameport",
.id_table = emu_tbl,
.probe = emu_probe,
.remove = emu_remove,
};
module_pci_driver(emu_driver);
|
linux-master
|
drivers/input/gameport/emu10k1-gp.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2001 Vojtech Pavlik
*/
/*
* PDPI Lightning 4 gamecard driver for Linux.
*/
#include <asm/io.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/gameport.h>
#define L4_PORT 0x201
#define L4_SELECT_ANALOG 0xa4
#define L4_SELECT_DIGITAL 0xa5
#define L4_SELECT_SECONDARY 0xa6
#define L4_CMD_ID 0x80
#define L4_CMD_GETCAL 0x92
#define L4_CMD_SETCAL 0x93
#define L4_ID 0x04
#define L4_BUSY 0x01
#define L4_TIMEOUT 80 /* 80 us */
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("PDPI Lightning 4 gamecard driver");
MODULE_LICENSE("GPL");
struct l4 {
struct gameport *gameport;
unsigned char port;
};
static struct l4 l4_ports[8];
/*
* l4_wait_ready() waits for the L4 to become ready.
*/
static int l4_wait_ready(void)
{
unsigned int t = L4_TIMEOUT;
while ((inb(L4_PORT) & L4_BUSY) && t > 0) t--;
return -(t <= 0);
}
/*
* l4_cooked_read() reads data from the Lightning 4.
*/
static int l4_cooked_read(struct gameport *gameport, int *axes, int *buttons)
{
struct l4 *l4 = gameport->port_data;
unsigned char status;
int i, result = -1;
outb(L4_SELECT_ANALOG, L4_PORT);
outb(L4_SELECT_DIGITAL + (l4->port >> 2), L4_PORT);
if (inb(L4_PORT) & L4_BUSY) goto fail;
outb(l4->port & 3, L4_PORT);
if (l4_wait_ready()) goto fail;
status = inb(L4_PORT);
for (i = 0; i < 4; i++)
if (status & (1 << i)) {
if (l4_wait_ready()) goto fail;
axes[i] = inb(L4_PORT);
if (axes[i] > 252) axes[i] = -1;
}
if (status & 0x10) {
if (l4_wait_ready()) goto fail;
*buttons = inb(L4_PORT) & 0x0f;
}
result = 0;
fail: outb(L4_SELECT_ANALOG, L4_PORT);
return result;
}
static int l4_open(struct gameport *gameport, int mode)
{
struct l4 *l4 = gameport->port_data;
if (l4->port != 0 && mode != GAMEPORT_MODE_COOKED)
return -1;
outb(L4_SELECT_ANALOG, L4_PORT);
return 0;
}
/*
* l4_getcal() reads the L4 with calibration values.
*/
static int l4_getcal(int port, int *cal)
{
int i, result = -1;
outb(L4_SELECT_ANALOG, L4_PORT);
outb(L4_SELECT_DIGITAL + (port >> 2), L4_PORT);
if (inb(L4_PORT) & L4_BUSY)
goto out;
outb(L4_CMD_GETCAL, L4_PORT);
if (l4_wait_ready())
goto out;
if (inb(L4_PORT) != L4_SELECT_DIGITAL + (port >> 2))
goto out;
if (l4_wait_ready())
goto out;
outb(port & 3, L4_PORT);
for (i = 0; i < 4; i++) {
if (l4_wait_ready())
goto out;
cal[i] = inb(L4_PORT);
}
result = 0;
out: outb(L4_SELECT_ANALOG, L4_PORT);
return result;
}
/*
* l4_setcal() programs the L4 with calibration values.
*/
static int l4_setcal(int port, int *cal)
{
int i, result = -1;
outb(L4_SELECT_ANALOG, L4_PORT);
outb(L4_SELECT_DIGITAL + (port >> 2), L4_PORT);
if (inb(L4_PORT) & L4_BUSY)
goto out;
outb(L4_CMD_SETCAL, L4_PORT);
if (l4_wait_ready())
goto out;
if (inb(L4_PORT) != L4_SELECT_DIGITAL + (port >> 2))
goto out;
if (l4_wait_ready())
goto out;
outb(port & 3, L4_PORT);
for (i = 0; i < 4; i++) {
if (l4_wait_ready())
goto out;
outb(cal[i], L4_PORT);
}
result = 0;
out: outb(L4_SELECT_ANALOG, L4_PORT);
return result;
}
/*
* l4_calibrate() calibrates the L4 for the attached device, so
* that the device's resistance fits into the L4's 8-bit range.
*/
static int l4_calibrate(struct gameport *gameport, int *axes, int *max)
{
int i, t;
int cal[4];
struct l4 *l4 = gameport->port_data;
if (l4_getcal(l4->port, cal))
return -1;
for (i = 0; i < 4; i++) {
t = (max[i] * cal[i]) / 200;
t = (t < 1) ? 1 : ((t > 255) ? 255 : t);
axes[i] = (axes[i] < 0) ? -1 : (axes[i] * cal[i]) / t;
axes[i] = (axes[i] > 252) ? 252 : axes[i];
cal[i] = t;
}
if (l4_setcal(l4->port, cal))
return -1;
return 0;
}
static int __init l4_create_ports(int card_no)
{
struct l4 *l4;
struct gameport *port;
int i, idx;
for (i = 0; i < 4; i++) {
idx = card_no * 4 + i;
l4 = &l4_ports[idx];
if (!(l4->gameport = port = gameport_allocate_port())) {
printk(KERN_ERR "lightning: Memory allocation failed\n");
while (--i >= 0) {
gameport_free_port(l4->gameport);
l4->gameport = NULL;
}
return -ENOMEM;
}
l4->port = idx;
port->port_data = l4;
port->open = l4_open;
port->cooked_read = l4_cooked_read;
port->calibrate = l4_calibrate;
gameport_set_name(port, "PDPI Lightning 4");
gameport_set_phys(port, "isa%04x/gameport%d", L4_PORT, idx);
if (idx == 0)
port->io = L4_PORT;
}
return 0;
}
static int __init l4_add_card(int card_no)
{
int cal[4] = { 255, 255, 255, 255 };
int i, rev, result;
struct l4 *l4;
outb(L4_SELECT_ANALOG, L4_PORT);
outb(L4_SELECT_DIGITAL + card_no, L4_PORT);
if (inb(L4_PORT) & L4_BUSY)
return -1;
outb(L4_CMD_ID, L4_PORT);
if (l4_wait_ready())
return -1;
if (inb(L4_PORT) != L4_SELECT_DIGITAL + card_no)
return -1;
if (l4_wait_ready())
return -1;
if (inb(L4_PORT) != L4_ID)
return -1;
if (l4_wait_ready())
return -1;
rev = inb(L4_PORT);
if (!rev)
return -1;
result = l4_create_ports(card_no);
if (result)
return result;
printk(KERN_INFO "gameport: PDPI Lightning 4 %s card v%d.%d at %#x\n",
card_no ? "secondary" : "primary", rev >> 4, rev, L4_PORT);
for (i = 0; i < 4; i++) {
l4 = &l4_ports[card_no * 4 + i];
if (rev > 0x28) /* on 2.9+ the setcal command works correctly */
l4_setcal(l4->port, cal);
gameport_register_port(l4->gameport);
}
return 0;
}
static int __init l4_init(void)
{
int i, cards = 0;
if (!request_region(L4_PORT, 1, "lightning"))
return -EBUSY;
for (i = 0; i < 2; i++)
if (l4_add_card(i) == 0)
cards++;
outb(L4_SELECT_ANALOG, L4_PORT);
if (!cards) {
release_region(L4_PORT, 1);
return -ENODEV;
}
return 0;
}
static void __exit l4_exit(void)
{
int i;
int cal[4] = { 59, 59, 59, 59 };
for (i = 0; i < 8; i++)
if (l4_ports[i].gameport) {
l4_setcal(l4_ports[i].port, cal);
gameport_unregister_port(l4_ports[i].gameport);
}
outb(L4_SELECT_ANALOG, L4_PORT);
release_region(L4_PORT, 1);
}
module_init(l4_init);
module_exit(l4_exit);
|
linux-master
|
drivers/input/gameport/lightning.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Generic gameport layer
*
* Copyright (c) 1999-2002 Vojtech Pavlik
* Copyright (c) 2005 Dmitry Torokhov
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/stddef.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/gameport.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/workqueue.h>
#include <linux/sched.h> /* HZ */
#include <linux/mutex.h>
#include <linux/timekeeping.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("Generic gameport layer");
MODULE_LICENSE("GPL");
static bool use_ktime = true;
module_param(use_ktime, bool, 0400);
MODULE_PARM_DESC(use_ktime, "Use ktime for measuring I/O speed");
/*
* gameport_mutex protects entire gameport subsystem and is taken
* every time gameport port or driver registrered or unregistered.
*/
static DEFINE_MUTEX(gameport_mutex);
static LIST_HEAD(gameport_list);
static struct bus_type gameport_bus;
static void gameport_add_port(struct gameport *gameport);
static void gameport_attach_driver(struct gameport_driver *drv);
static void gameport_reconnect_port(struct gameport *gameport);
static void gameport_disconnect_port(struct gameport *gameport);
#if defined(__i386__)
#include <linux/i8253.h>
#define DELTA(x,y) ((y)-(x)+((y)<(x)?1193182/HZ:0))
#define GET_TIME(x) do { x = get_time_pit(); } while (0)
static unsigned int get_time_pit(void)
{
unsigned long flags;
unsigned int count;
raw_spin_lock_irqsave(&i8253_lock, flags);
outb_p(0x00, 0x43);
count = inb_p(0x40);
count |= inb_p(0x40) << 8;
raw_spin_unlock_irqrestore(&i8253_lock, flags);
return count;
}
#endif
/*
* gameport_measure_speed() measures the gameport i/o speed.
*/
static int gameport_measure_speed(struct gameport *gameport)
{
unsigned int i, t, tx;
u64 t1, t2, t3;
unsigned long flags;
if (gameport_open(gameport, NULL, GAMEPORT_MODE_RAW))
return 0;
tx = ~0;
for (i = 0; i < 50; i++) {
local_irq_save(flags);
t1 = ktime_get_ns();
for (t = 0; t < 50; t++)
gameport_read(gameport);
t2 = ktime_get_ns();
t3 = ktime_get_ns();
local_irq_restore(flags);
udelay(i * 10);
t = (t2 - t1) - (t3 - t2);
if (t < tx)
tx = t;
}
gameport_close(gameport);
t = 1000000 * 50;
if (tx)
t /= tx;
return t;
}
static int old_gameport_measure_speed(struct gameport *gameport)
{
#if defined(__i386__)
unsigned int i, t, t1, t2, t3, tx;
unsigned long flags;
if (gameport_open(gameport, NULL, GAMEPORT_MODE_RAW))
return 0;
tx = 1 << 30;
for(i = 0; i < 50; i++) {
local_irq_save(flags);
GET_TIME(t1);
for (t = 0; t < 50; t++) gameport_read(gameport);
GET_TIME(t2);
GET_TIME(t3);
local_irq_restore(flags);
udelay(i * 10);
if ((t = DELTA(t2,t1) - DELTA(t3,t2)) < tx) tx = t;
}
gameport_close(gameport);
return 59659 / (tx < 1 ? 1 : tx);
#elif defined (__x86_64__)
unsigned int i, t;
unsigned long tx, t1, t2, flags;
if (gameport_open(gameport, NULL, GAMEPORT_MODE_RAW))
return 0;
tx = 1 << 30;
for(i = 0; i < 50; i++) {
local_irq_save(flags);
t1 = rdtsc();
for (t = 0; t < 50; t++) gameport_read(gameport);
t2 = rdtsc();
local_irq_restore(flags);
udelay(i * 10);
if (t2 - t1 < tx) tx = t2 - t1;
}
gameport_close(gameport);
return (this_cpu_read(cpu_info.loops_per_jiffy) *
(unsigned long)HZ / (1000 / 50)) / (tx < 1 ? 1 : tx);
#else
unsigned int j, t = 0;
if (gameport_open(gameport, NULL, GAMEPORT_MODE_RAW))
return 0;
j = jiffies; while (j == jiffies);
j = jiffies; while (j == jiffies) { t++; gameport_read(gameport); }
gameport_close(gameport);
return t * HZ / 1000;
#endif
}
void gameport_start_polling(struct gameport *gameport)
{
spin_lock(&gameport->timer_lock);
if (!gameport->poll_cnt++) {
BUG_ON(!gameport->poll_handler);
BUG_ON(!gameport->poll_interval);
mod_timer(&gameport->poll_timer, jiffies + msecs_to_jiffies(gameport->poll_interval));
}
spin_unlock(&gameport->timer_lock);
}
EXPORT_SYMBOL(gameport_start_polling);
void gameport_stop_polling(struct gameport *gameport)
{
spin_lock(&gameport->timer_lock);
if (!--gameport->poll_cnt)
del_timer(&gameport->poll_timer);
spin_unlock(&gameport->timer_lock);
}
EXPORT_SYMBOL(gameport_stop_polling);
static void gameport_run_poll_handler(struct timer_list *t)
{
struct gameport *gameport = from_timer(gameport, t, poll_timer);
gameport->poll_handler(gameport);
if (gameport->poll_cnt)
mod_timer(&gameport->poll_timer, jiffies + msecs_to_jiffies(gameport->poll_interval));
}
/*
* Basic gameport -> driver core mappings
*/
static int gameport_bind_driver(struct gameport *gameport, struct gameport_driver *drv)
{
int error;
gameport->dev.driver = &drv->driver;
if (drv->connect(gameport, drv)) {
gameport->dev.driver = NULL;
return -ENODEV;
}
error = device_bind_driver(&gameport->dev);
if (error) {
dev_warn(&gameport->dev,
"device_bind_driver() failed for %s (%s) and %s, error: %d\n",
gameport->phys, gameport->name,
drv->description, error);
drv->disconnect(gameport);
gameport->dev.driver = NULL;
return error;
}
return 0;
}
static void gameport_find_driver(struct gameport *gameport)
{
int error;
error = device_attach(&gameport->dev);
if (error < 0)
dev_warn(&gameport->dev,
"device_attach() failed for %s (%s), error: %d\n",
gameport->phys, gameport->name, error);
}
/*
* Gameport event processing.
*/
enum gameport_event_type {
GAMEPORT_REGISTER_PORT,
GAMEPORT_ATTACH_DRIVER,
};
struct gameport_event {
enum gameport_event_type type;
void *object;
struct module *owner;
struct list_head node;
};
static DEFINE_SPINLOCK(gameport_event_lock); /* protects gameport_event_list */
static LIST_HEAD(gameport_event_list);
static struct gameport_event *gameport_get_event(void)
{
struct gameport_event *event = NULL;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
if (!list_empty(&gameport_event_list)) {
event = list_first_entry(&gameport_event_list,
struct gameport_event, node);
list_del_init(&event->node);
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
return event;
}
static void gameport_free_event(struct gameport_event *event)
{
module_put(event->owner);
kfree(event);
}
static void gameport_remove_duplicate_events(struct gameport_event *event)
{
struct gameport_event *e, *next;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
list_for_each_entry_safe(e, next, &gameport_event_list, node) {
if (event->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 (event->type != e->type)
break;
list_del_init(&e->node);
gameport_free_event(e);
}
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
}
static void gameport_handle_events(struct work_struct *work)
{
struct gameport_event *event;
mutex_lock(&gameport_mutex);
/*
* Note that we handle only one event here to give swsusp
* a chance to freeze kgameportd thread. Gameport events
* should be pretty rare so we are not concerned about
* taking performance hit.
*/
if ((event = gameport_get_event())) {
switch (event->type) {
case GAMEPORT_REGISTER_PORT:
gameport_add_port(event->object);
break;
case GAMEPORT_ATTACH_DRIVER:
gameport_attach_driver(event->object);
break;
}
gameport_remove_duplicate_events(event);
gameport_free_event(event);
}
mutex_unlock(&gameport_mutex);
}
static DECLARE_WORK(gameport_event_work, gameport_handle_events);
static int gameport_queue_event(void *object, struct module *owner,
enum gameport_event_type event_type)
{
unsigned long flags;
struct gameport_event *event;
int retval = 0;
spin_lock_irqsave(&gameport_event_lock, flags);
/*
* Scan event list for the other events for the same gameport 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 preserve sequence of distinct events.
*/
list_for_each_entry_reverse(event, &gameport_event_list, node) {
if (event->object == object) {
if (event->type == event_type)
goto out;
break;
}
}
event = kmalloc(sizeof(struct gameport_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, &gameport_event_list);
queue_work(system_long_wq, &gameport_event_work);
out:
spin_unlock_irqrestore(&gameport_event_lock, flags);
return retval;
}
/*
* Remove all events that have been submitted for a given object,
* be it a gameport port or a driver.
*/
static void gameport_remove_pending_events(void *object)
{
struct gameport_event *event, *next;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
list_for_each_entry_safe(event, next, &gameport_event_list, node) {
if (event->object == object) {
list_del_init(&event->node);
gameport_free_event(event);
}
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
}
/*
* Destroy child gameport port (if any) that has not been fully registered yet.
*
* Note that we rely on the fact that port can have only one child and therefore
* only one child registration request can be pending. Additionally, children
* are registered by driver's connect() handler so there can't be a grandchild
* pending registration together with a child.
*/
static struct gameport *gameport_get_pending_child(struct gameport *parent)
{
struct gameport_event *event;
struct gameport *gameport, *child = NULL;
unsigned long flags;
spin_lock_irqsave(&gameport_event_lock, flags);
list_for_each_entry(event, &gameport_event_list, node) {
if (event->type == GAMEPORT_REGISTER_PORT) {
gameport = event->object;
if (gameport->parent == parent) {
child = gameport;
break;
}
}
}
spin_unlock_irqrestore(&gameport_event_lock, flags);
return child;
}
/*
* Gameport port operations
*/
static ssize_t gameport_description_show(struct device *dev, struct device_attribute *attr, char *buf)
{
struct gameport *gameport = to_gameport_port(dev);
return sprintf(buf, "%s\n", gameport->name);
}
static DEVICE_ATTR(description, S_IRUGO, gameport_description_show, NULL);
static ssize_t drvctl_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct gameport *gameport = to_gameport_port(dev);
struct device_driver *drv;
int error;
error = mutex_lock_interruptible(&gameport_mutex);
if (error)
return error;
if (!strncmp(buf, "none", count)) {
gameport_disconnect_port(gameport);
} else if (!strncmp(buf, "reconnect", count)) {
gameport_reconnect_port(gameport);
} else if (!strncmp(buf, "rescan", count)) {
gameport_disconnect_port(gameport);
gameport_find_driver(gameport);
} else if ((drv = driver_find(buf, &gameport_bus)) != NULL) {
gameport_disconnect_port(gameport);
error = gameport_bind_driver(gameport, to_gameport_driver(drv));
} else {
error = -EINVAL;
}
mutex_unlock(&gameport_mutex);
return error ? error : count;
}
static DEVICE_ATTR_WO(drvctl);
static struct attribute *gameport_device_attrs[] = {
&dev_attr_description.attr,
&dev_attr_drvctl.attr,
NULL,
};
ATTRIBUTE_GROUPS(gameport_device);
static void gameport_release_port(struct device *dev)
{
struct gameport *gameport = to_gameport_port(dev);
kfree(gameport);
module_put(THIS_MODULE);
}
void gameport_set_phys(struct gameport *gameport, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsnprintf(gameport->phys, sizeof(gameport->phys), fmt, args);
va_end(args);
}
EXPORT_SYMBOL(gameport_set_phys);
static void gameport_default_trigger(struct gameport *gameport)
{
#ifdef CONFIG_HAS_IOPORT
outb(0xff, gameport->io);
#endif
}
static unsigned char gameport_default_read(struct gameport *gameport)
{
#ifdef CONFIG_HAS_IOPORT
return inb(gameport->io);
#else
return 0xff;
#endif
}
static void gameport_setup_default_handlers(struct gameport *gameport)
{
if ((!gameport->trigger || !gameport->read) &&
!IS_ENABLED(CONFIG_HAS_IOPORT))
dev_err(&gameport->dev,
"I/O port access is required for %s (%s) but is not available\n",
gameport->phys, gameport->name);
if (!gameport->trigger)
gameport->trigger = gameport_default_trigger;
if (!gameport->read)
gameport->read = gameport_default_read;
}
/*
* Prepare gameport port for registration.
*/
static void gameport_init_port(struct gameport *gameport)
{
static atomic_t gameport_no = ATOMIC_INIT(-1);
__module_get(THIS_MODULE);
mutex_init(&gameport->drv_mutex);
device_initialize(&gameport->dev);
dev_set_name(&gameport->dev, "gameport%lu",
(unsigned long)atomic_inc_return(&gameport_no));
gameport->dev.bus = &gameport_bus;
gameport->dev.release = gameport_release_port;
if (gameport->parent)
gameport->dev.parent = &gameport->parent->dev;
gameport_setup_default_handlers(gameport);
INIT_LIST_HEAD(&gameport->node);
spin_lock_init(&gameport->timer_lock);
timer_setup(&gameport->poll_timer, gameport_run_poll_handler, 0);
}
/*
* Complete gameport port registration.
* Driver core will attempt to find appropriate driver for the port.
*/
static void gameport_add_port(struct gameport *gameport)
{
int error;
if (gameport->parent)
gameport->parent->child = gameport;
gameport->speed = use_ktime ?
gameport_measure_speed(gameport) :
old_gameport_measure_speed(gameport);
list_add_tail(&gameport->node, &gameport_list);
if (gameport->io)
dev_info(&gameport->dev, "%s is %s, io %#x, speed %dkHz\n",
gameport->name, gameport->phys, gameport->io, gameport->speed);
else
dev_info(&gameport->dev, "%s is %s, speed %dkHz\n",
gameport->name, gameport->phys, gameport->speed);
error = device_add(&gameport->dev);
if (error)
dev_err(&gameport->dev,
"device_add() failed for %s (%s), error: %d\n",
gameport->phys, gameport->name, error);
}
/*
* gameport_destroy_port() completes deregistration process and removes
* port from the system
*/
static void gameport_destroy_port(struct gameport *gameport)
{
struct gameport *child;
child = gameport_get_pending_child(gameport);
if (child) {
gameport_remove_pending_events(child);
put_device(&child->dev);
}
if (gameport->parent) {
gameport->parent->child = NULL;
gameport->parent = NULL;
}
if (device_is_registered(&gameport->dev))
device_del(&gameport->dev);
list_del_init(&gameport->node);
gameport_remove_pending_events(gameport);
put_device(&gameport->dev);
}
/*
* Reconnect gameport port and all its children (re-initialize attached devices)
*/
static void gameport_reconnect_port(struct gameport *gameport)
{
do {
if (!gameport->drv || !gameport->drv->reconnect || gameport->drv->reconnect(gameport)) {
gameport_disconnect_port(gameport);
gameport_find_driver(gameport);
/* Ok, old children are now gone, we are done */
break;
}
gameport = gameport->child;
} while (gameport);
}
/*
* gameport_disconnect_port() unbinds a port from its driver. As a side effect
* all child ports are unbound and destroyed.
*/
static void gameport_disconnect_port(struct gameport *gameport)
{
struct gameport *s, *parent;
if (gameport->child) {
/*
* Children ports should be disconnected and destroyed
* first, staring with the leaf one, since we don't want
* to do recursion
*/
for (s = gameport; s->child; s = s->child)
/* empty */;
do {
parent = s->parent;
device_release_driver(&s->dev);
gameport_destroy_port(s);
} while ((s = parent) != gameport);
}
/*
* Ok, no children left, now disconnect this port
*/
device_release_driver(&gameport->dev);
}
/*
* Submits register request to kgameportd for subsequent execution.
* Note that port registration is always asynchronous.
*/
void __gameport_register_port(struct gameport *gameport, struct module *owner)
{
gameport_init_port(gameport);
gameport_queue_event(gameport, owner, GAMEPORT_REGISTER_PORT);
}
EXPORT_SYMBOL(__gameport_register_port);
/*
* Synchronously unregisters gameport port.
*/
void gameport_unregister_port(struct gameport *gameport)
{
mutex_lock(&gameport_mutex);
gameport_disconnect_port(gameport);
gameport_destroy_port(gameport);
mutex_unlock(&gameport_mutex);
}
EXPORT_SYMBOL(gameport_unregister_port);
/*
* Gameport driver operations
*/
static ssize_t description_show(struct device_driver *drv, char *buf)
{
struct gameport_driver *driver = to_gameport_driver(drv);
return sprintf(buf, "%s\n", driver->description ? driver->description : "(none)");
}
static DRIVER_ATTR_RO(description);
static struct attribute *gameport_driver_attrs[] = {
&driver_attr_description.attr,
NULL
};
ATTRIBUTE_GROUPS(gameport_driver);
static int gameport_driver_probe(struct device *dev)
{
struct gameport *gameport = to_gameport_port(dev);
struct gameport_driver *drv = to_gameport_driver(dev->driver);
drv->connect(gameport, drv);
return gameport->drv ? 0 : -ENODEV;
}
static void gameport_driver_remove(struct device *dev)
{
struct gameport *gameport = to_gameport_port(dev);
struct gameport_driver *drv = to_gameport_driver(dev->driver);
drv->disconnect(gameport);
}
static void gameport_attach_driver(struct gameport_driver *drv)
{
int error;
error = driver_attach(&drv->driver);
if (error)
pr_err("driver_attach() failed for %s, error: %d\n",
drv->driver.name, error);
}
int __gameport_register_driver(struct gameport_driver *drv, struct module *owner,
const char *mod_name)
{
int error;
drv->driver.bus = &gameport_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 kgameportd
*/
drv->ignore = true;
error = driver_register(&drv->driver);
if (error) {
pr_err("driver_register() failed for %s, error: %d\n",
drv->driver.name, error);
return error;
}
/*
* Reset ignore flag and let kgameportd bind the driver to free ports
*/
drv->ignore = false;
error = gameport_queue_event(drv, NULL, GAMEPORT_ATTACH_DRIVER);
if (error) {
driver_unregister(&drv->driver);
return error;
}
return 0;
}
EXPORT_SYMBOL(__gameport_register_driver);
void gameport_unregister_driver(struct gameport_driver *drv)
{
struct gameport *gameport;
mutex_lock(&gameport_mutex);
drv->ignore = true; /* so gameport_find_driver ignores it */
gameport_remove_pending_events(drv);
start_over:
list_for_each_entry(gameport, &gameport_list, node) {
if (gameport->drv == drv) {
gameport_disconnect_port(gameport);
gameport_find_driver(gameport);
/* we could've deleted some ports, restart */
goto start_over;
}
}
driver_unregister(&drv->driver);
mutex_unlock(&gameport_mutex);
}
EXPORT_SYMBOL(gameport_unregister_driver);
static int gameport_bus_match(struct device *dev, struct device_driver *drv)
{
struct gameport_driver *gameport_drv = to_gameport_driver(drv);
return !gameport_drv->ignore;
}
static struct bus_type gameport_bus = {
.name = "gameport",
.dev_groups = gameport_device_groups,
.drv_groups = gameport_driver_groups,
.match = gameport_bus_match,
.probe = gameport_driver_probe,
.remove = gameport_driver_remove,
};
static void gameport_set_drv(struct gameport *gameport, struct gameport_driver *drv)
{
mutex_lock(&gameport->drv_mutex);
gameport->drv = drv;
mutex_unlock(&gameport->drv_mutex);
}
int gameport_open(struct gameport *gameport, struct gameport_driver *drv, int mode)
{
if (gameport->open) {
if (gameport->open(gameport, mode)) {
return -1;
}
} else {
if (mode != GAMEPORT_MODE_RAW)
return -1;
}
gameport_set_drv(gameport, drv);
return 0;
}
EXPORT_SYMBOL(gameport_open);
void gameport_close(struct gameport *gameport)
{
del_timer_sync(&gameport->poll_timer);
gameport->poll_handler = NULL;
gameport->poll_interval = 0;
gameport_set_drv(gameport, NULL);
if (gameport->close)
gameport->close(gameport);
}
EXPORT_SYMBOL(gameport_close);
static int __init gameport_init(void)
{
int error;
error = bus_register(&gameport_bus);
if (error) {
pr_err("failed to register gameport bus, error: %d\n", error);
return error;
}
return 0;
}
static void __exit gameport_exit(void)
{
bus_unregister(&gameport_bus);
/*
* There should not be any outstanding events but work may
* still be scheduled so simply cancel it.
*/
cancel_work_sync(&gameport_event_work);
}
subsys_initcall(gameport_init);
module_exit(gameport_exit);
|
linux-master
|
drivers/input/gameport/gameport.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*
* Based on the work of:
* David Thompson
*/
/*
* SpaceTec SpaceOrb 360 and Avenger 6dof controller driver for Linux
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "SpaceTec SpaceOrb 360 and Avenger 6dof controller driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Constants.
*/
#define SPACEORB_MAX_LENGTH 64
static int spaceorb_buttons[] = { BTN_TL, BTN_TR, BTN_Y, BTN_X, BTN_B, BTN_A };
static int spaceorb_axes[] = { ABS_X, ABS_Y, ABS_Z, ABS_RX, ABS_RY, ABS_RZ };
/*
* Per-Orb data.
*/
struct spaceorb {
struct input_dev *dev;
int idx;
unsigned char data[SPACEORB_MAX_LENGTH];
char phys[32];
};
static unsigned char spaceorb_xor[] = "SpaceWare";
static unsigned char *spaceorb_errors[] = { "EEPROM storing 0 failed", "Receive queue overflow", "Transmit queue timeout",
"Bad packet", "Power brown-out", "EEPROM checksum error", "Hardware fault" };
/*
* spaceorb_process_packet() decodes packets the driver receives from the
* SpaceOrb.
*/
static void spaceorb_process_packet(struct spaceorb *spaceorb)
{
struct input_dev *dev = spaceorb->dev;
unsigned char *data = spaceorb->data;
unsigned char c = 0;
int axes[6];
int i;
if (spaceorb->idx < 2) return;
for (i = 0; i < spaceorb->idx; i++) c ^= data[i];
if (c) return;
switch (data[0]) {
case 'R': /* Reset packet */
spaceorb->data[spaceorb->idx - 1] = 0;
for (i = 1; i < spaceorb->idx && spaceorb->data[i] == ' '; i++);
printk(KERN_INFO "input: %s [%s] is %s\n",
dev->name, spaceorb->data + i, spaceorb->phys);
break;
case 'D': /* Ball + button data */
if (spaceorb->idx != 12) return;
for (i = 0; i < 9; i++) spaceorb->data[i+2] ^= spaceorb_xor[i];
axes[0] = ( data[2] << 3) | (data[ 3] >> 4);
axes[1] = ((data[3] & 0x0f) << 6) | (data[ 4] >> 1);
axes[2] = ((data[4] & 0x01) << 9) | (data[ 5] << 2) | (data[4] >> 5);
axes[3] = ((data[6] & 0x1f) << 5) | (data[ 7] >> 2);
axes[4] = ((data[7] & 0x03) << 8) | (data[ 8] << 1) | (data[7] >> 6);
axes[5] = ((data[9] & 0x3f) << 4) | (data[10] >> 3);
for (i = 0; i < 6; i++)
input_report_abs(dev, spaceorb_axes[i], axes[i] - ((axes[i] & 0x200) ? 1024 : 0));
for (i = 0; i < 6; i++)
input_report_key(dev, spaceorb_buttons[i], (data[1] >> i) & 1);
break;
case 'K': /* Button data */
if (spaceorb->idx != 5) return;
for (i = 0; i < 6; i++)
input_report_key(dev, spaceorb_buttons[i], (data[2] >> i) & 1);
break;
case 'E': /* Error packet */
if (spaceorb->idx != 4) return;
printk(KERN_ERR "spaceorb: Device error. [ ");
for (i = 0; i < 7; i++) if (data[1] & (1 << i)) printk("%s ", spaceorb_errors[i]);
printk("]\n");
break;
}
input_sync(dev);
}
static irqreturn_t spaceorb_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct spaceorb* spaceorb = serio_get_drvdata(serio);
if (~data & 0x80) {
if (spaceorb->idx) spaceorb_process_packet(spaceorb);
spaceorb->idx = 0;
}
if (spaceorb->idx < SPACEORB_MAX_LENGTH)
spaceorb->data[spaceorb->idx++] = data & 0x7f;
return IRQ_HANDLED;
}
/*
* spaceorb_disconnect() is the opposite of spaceorb_connect()
*/
static void spaceorb_disconnect(struct serio *serio)
{
struct spaceorb* spaceorb = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(spaceorb->dev);
kfree(spaceorb);
}
/*
* spaceorb_connect() is the routine that is called when someone adds a
* new serio device that supports SpaceOrb/Avenger protocol and registers
* it as an input device.
*/
static int spaceorb_connect(struct serio *serio, struct serio_driver *drv)
{
struct spaceorb *spaceorb;
struct input_dev *input_dev;
int err = -ENOMEM;
int i;
spaceorb = kzalloc(sizeof(struct spaceorb), GFP_KERNEL);
input_dev = input_allocate_device();
if (!spaceorb || !input_dev)
goto fail1;
spaceorb->dev = input_dev;
snprintf(spaceorb->phys, sizeof(spaceorb->phys), "%s/input0", serio->phys);
input_dev->name = "SpaceTec SpaceOrb 360 / Avenger";
input_dev->phys = spaceorb->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_SPACEORB;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; i < 6; i++)
set_bit(spaceorb_buttons[i], input_dev->keybit);
for (i = 0; i < 6; i++)
input_set_abs_params(input_dev, spaceorb_axes[i], -508, 508, 0, 0);
serio_set_drvdata(serio, spaceorb);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(spaceorb->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(spaceorb);
return err;
}
/*
* The serio driver structure.
*/
static const struct serio_device_id spaceorb_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_SPACEORB,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, spaceorb_serio_ids);
static struct serio_driver spaceorb_drv = {
.driver = {
.name = "spaceorb",
},
.description = DRIVER_DESC,
.id_table = spaceorb_serio_ids,
.interrupt = spaceorb_interrupt,
.connect = spaceorb_connect,
.disconnect = spaceorb_disconnect,
};
module_serio_driver(spaceorb_drv);
|
linux-master
|
drivers/input/joystick/spaceorb.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1996-2001 Vojtech Pavlik
*/
/*
* This is just a very simple driver that can dump the data
* out of the joystick port into the syslog ...
*/
#include <linux/module.h>
#include <linux/gameport.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/slab.h>
#define DRIVER_DESC "Gameport data dumper module"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define BUF_SIZE 256
struct joydump {
unsigned int time;
unsigned char data;
};
static int joydump_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct joydump *buf; /* all entries */
struct joydump *dump, *prev; /* one entry each */
int axes[4], buttons;
int i, j, t, timeout;
unsigned long flags;
unsigned char u;
printk(KERN_INFO "joydump: ,------------------ START ----------------.\n");
printk(KERN_INFO "joydump: | Dumping: %30s |\n", gameport->phys);
printk(KERN_INFO "joydump: | Speed: %28d kHz |\n", gameport->speed);
if (gameport_open(gameport, drv, GAMEPORT_MODE_RAW)) {
printk(KERN_INFO "joydump: | Raw mode not available - trying cooked. |\n");
if (gameport_open(gameport, drv, GAMEPORT_MODE_COOKED)) {
printk(KERN_INFO "joydump: | Cooked not available either. Failing. |\n");
printk(KERN_INFO "joydump: `------------------- END -----------------'\n");
return -ENODEV;
}
gameport_cooked_read(gameport, axes, &buttons);
for (i = 0; i < 4; i++)
printk(KERN_INFO "joydump: | Axis %d: %4d. |\n", i, axes[i]);
printk(KERN_INFO "joydump: | Buttons %02x. |\n", buttons);
printk(KERN_INFO "joydump: `------------------- END -----------------'\n");
}
timeout = gameport_time(gameport, 10000); /* 10 ms */
buf = kmalloc_array(BUF_SIZE, sizeof(struct joydump), GFP_KERNEL);
if (!buf) {
printk(KERN_INFO "joydump: no memory for testing\n");
goto jd_end;
}
dump = buf;
t = 0;
i = 1;
local_irq_save(flags);
u = gameport_read(gameport);
dump->data = u;
dump->time = t;
dump++;
gameport_trigger(gameport);
while (i < BUF_SIZE && t < timeout) {
dump->data = gameport_read(gameport);
if (dump->data ^ u) {
u = dump->data;
dump->time = t;
i++;
dump++;
}
t++;
}
local_irq_restore(flags);
/*
* Dump data.
*/
t = i;
dump = buf;
prev = dump;
printk(KERN_INFO "joydump: >------------------ DATA -----------------<\n");
printk(KERN_INFO "joydump: | index: %3d delta: %3d us data: ", 0, 0);
for (j = 7; j >= 0; j--)
printk("%d", (dump->data >> j) & 1);
printk(" |\n");
dump++;
for (i = 1; i < t; i++, dump++, prev++) {
printk(KERN_INFO "joydump: | index: %3d delta: %3d us data: ",
i, dump->time - prev->time);
for (j = 7; j >= 0; j--)
printk("%d", (dump->data >> j) & 1);
printk(" |\n");
}
kfree(buf);
jd_end:
printk(KERN_INFO "joydump: `------------------- END -----------------'\n");
return 0;
}
static void joydump_disconnect(struct gameport *gameport)
{
gameport_close(gameport);
}
static struct gameport_driver joydump_drv = {
.driver = {
.name = "joydump",
},
.description = DRIVER_DESC,
.connect = joydump_connect,
.disconnect = joydump_disconnect,
};
module_gameport_driver(joydump_drv);
|
linux-master
|
drivers/input/joystick/joydump.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* NES, SNES, N64, MultiSystem, PSX gamepad driver for Linux
*
* Copyright (c) 1999-2004 Vojtech Pavlik <[email protected]>
* Copyright (c) 2004 Peter Nelson <[email protected]>
*
* Based on the work of:
* Andree Borrmann John Dahlstrom
* David Kuder Nathan Hand
* Raphael Assenat
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/parport.h>
#include <linux/input.h>
#include <linux/mutex.h>
#include <linux/slab.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("NES, SNES, N64, MultiSystem, PSX gamepad driver");
MODULE_LICENSE("GPL");
#define GC_MAX_PORTS 3
#define GC_MAX_DEVICES 5
struct gc_config {
int args[GC_MAX_DEVICES + 1];
unsigned int nargs;
};
static struct gc_config gc_cfg[GC_MAX_PORTS];
module_param_array_named(map, gc_cfg[0].args, int, &gc_cfg[0].nargs, 0);
MODULE_PARM_DESC(map, "Describes first set of devices (<parport#>,<pad1>,<pad2>,..<pad5>)");
module_param_array_named(map2, gc_cfg[1].args, int, &gc_cfg[1].nargs, 0);
MODULE_PARM_DESC(map2, "Describes second set of devices");
module_param_array_named(map3, gc_cfg[2].args, int, &gc_cfg[2].nargs, 0);
MODULE_PARM_DESC(map3, "Describes third set of devices");
/* see also gs_psx_delay parameter in PSX support section */
enum gc_type {
GC_NONE = 0,
GC_SNES,
GC_NES,
GC_NES4,
GC_MULTI,
GC_MULTI2,
GC_N64,
GC_PSX,
GC_DDR,
GC_SNESMOUSE,
GC_MAX
};
#define GC_REFRESH_TIME HZ/100
struct gc_pad {
struct input_dev *dev;
enum gc_type type;
char phys[32];
};
struct gc {
struct pardevice *pd;
struct gc_pad pads[GC_MAX_DEVICES];
struct timer_list timer;
int pad_count[GC_MAX];
int used;
int parportno;
struct mutex mutex;
};
struct gc_subdev {
unsigned int idx;
};
static struct gc *gc_base[3];
static const int gc_status_bit[] = { 0x40, 0x80, 0x20, 0x10, 0x08 };
static const char *gc_names[] = {
NULL, "SNES pad", "NES pad", "NES FourPort", "Multisystem joystick",
"Multisystem 2-button joystick", "N64 controller", "PSX controller",
"PSX DDR controller", "SNES mouse"
};
/*
* N64 support.
*/
static const unsigned char gc_n64_bytes[] = { 0, 1, 13, 15, 14, 12, 10, 11, 2, 3 };
static const short gc_n64_btn[] = {
BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z,
BTN_TL, BTN_TR, BTN_TRIGGER, BTN_START
};
#define GC_N64_LENGTH 32 /* N64 bit length, not including stop bit */
#define GC_N64_STOP_LENGTH 5 /* Length of encoded stop bit */
#define GC_N64_CMD_00 0x11111111UL
#define GC_N64_CMD_01 0xd1111111UL
#define GC_N64_CMD_03 0xdd111111UL
#define GC_N64_CMD_1b 0xdd1dd111UL
#define GC_N64_CMD_c0 0x111111ddUL
#define GC_N64_CMD_80 0x1111111dUL
#define GC_N64_STOP_BIT 0x1d /* Encoded stop bit */
#define GC_N64_REQUEST_DATA GC_N64_CMD_01 /* the request data command */
#define GC_N64_DELAY 133 /* delay between transmit request, and response ready (us) */
#define GC_N64_DWS 3 /* delay between write segments (required for sound playback because of ISA DMA) */
/* GC_N64_DWS > 24 is known to fail */
#define GC_N64_POWER_W 0xe2 /* power during write (transmit request) */
#define GC_N64_POWER_R 0xfd /* power during read */
#define GC_N64_OUT 0x1d /* output bits to the 4 pads */
/* Reading the main axes of any N64 pad is known to fail if the corresponding bit */
/* in GC_N64_OUT is pulled low on the output port (by any routine) for more */
/* than 123 us */
#define GC_N64_CLOCK 0x02 /* clock bits for read */
/*
* Used for rumble code.
*/
/* Send encoded command */
static void gc_n64_send_command(struct gc *gc, unsigned long cmd,
unsigned char target)
{
struct parport *port = gc->pd->port;
int i;
for (i = 0; i < GC_N64_LENGTH; i++) {
unsigned char data = (cmd >> i) & 1 ? target : 0;
parport_write_data(port, GC_N64_POWER_W | data);
udelay(GC_N64_DWS);
}
}
/* Send stop bit */
static void gc_n64_send_stop_bit(struct gc *gc, unsigned char target)
{
struct parport *port = gc->pd->port;
int i;
for (i = 0; i < GC_N64_STOP_LENGTH; i++) {
unsigned char data = (GC_N64_STOP_BIT >> i) & 1 ? target : 0;
parport_write_data(port, GC_N64_POWER_W | data);
udelay(GC_N64_DWS);
}
}
/*
* gc_n64_read_packet() reads an N64 packet.
* Each pad uses one bit per byte. So all pads connected to this port
* are read in parallel.
*/
static void gc_n64_read_packet(struct gc *gc, unsigned char *data)
{
int i;
unsigned long flags;
/*
* Request the pad to transmit data
*/
local_irq_save(flags);
gc_n64_send_command(gc, GC_N64_REQUEST_DATA, GC_N64_OUT);
gc_n64_send_stop_bit(gc, GC_N64_OUT);
local_irq_restore(flags);
/*
* Wait for the pad response to be loaded into the 33-bit register
* of the adapter.
*/
udelay(GC_N64_DELAY);
/*
* Grab data (ignoring the last bit, which is a stop bit)
*/
for (i = 0; i < GC_N64_LENGTH; i++) {
parport_write_data(gc->pd->port, GC_N64_POWER_R);
udelay(2);
data[i] = parport_read_status(gc->pd->port);
parport_write_data(gc->pd->port, GC_N64_POWER_R | GC_N64_CLOCK);
}
/*
* We must wait 200 ms here for the controller to reinitialize before
* the next read request. No worries as long as gc_read is polled less
* frequently than this.
*/
}
static void gc_n64_process_packet(struct gc *gc)
{
unsigned char data[GC_N64_LENGTH];
struct input_dev *dev;
int i, j, s;
signed char x, y;
gc_n64_read_packet(gc, data);
for (i = 0; i < GC_MAX_DEVICES; i++) {
if (gc->pads[i].type != GC_N64)
continue;
dev = gc->pads[i].dev;
s = gc_status_bit[i];
if (s & ~(data[8] | data[9])) {
x = y = 0;
for (j = 0; j < 8; j++) {
if (data[23 - j] & s)
x |= 1 << j;
if (data[31 - j] & s)
y |= 1 << j;
}
input_report_abs(dev, ABS_X, x);
input_report_abs(dev, ABS_Y, -y);
input_report_abs(dev, ABS_HAT0X,
!(s & data[6]) - !(s & data[7]));
input_report_abs(dev, ABS_HAT0Y,
!(s & data[4]) - !(s & data[5]));
for (j = 0; j < 10; j++)
input_report_key(dev, gc_n64_btn[j],
s & data[gc_n64_bytes[j]]);
input_sync(dev);
}
}
}
static int gc_n64_play_effect(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
int i;
unsigned long flags;
struct gc *gc = input_get_drvdata(dev);
struct gc_subdev *sdev = data;
unsigned char target = 1 << sdev->idx; /* select desired pin */
if (effect->type == FF_RUMBLE) {
struct ff_rumble_effect *rumble = &effect->u.rumble;
unsigned int cmd =
rumble->strong_magnitude || rumble->weak_magnitude ?
GC_N64_CMD_01 : GC_N64_CMD_00;
local_irq_save(flags);
/* Init Rumble - 0x03, 0x80, 0x01, (34)0x80 */
gc_n64_send_command(gc, GC_N64_CMD_03, target);
gc_n64_send_command(gc, GC_N64_CMD_80, target);
gc_n64_send_command(gc, GC_N64_CMD_01, target);
for (i = 0; i < 32; i++)
gc_n64_send_command(gc, GC_N64_CMD_80, target);
gc_n64_send_stop_bit(gc, target);
udelay(GC_N64_DELAY);
/* Now start or stop it - 0x03, 0xc0, 0zx1b, (32)0x01/0x00 */
gc_n64_send_command(gc, GC_N64_CMD_03, target);
gc_n64_send_command(gc, GC_N64_CMD_c0, target);
gc_n64_send_command(gc, GC_N64_CMD_1b, target);
for (i = 0; i < 32; i++)
gc_n64_send_command(gc, cmd, target);
gc_n64_send_stop_bit(gc, target);
local_irq_restore(flags);
}
return 0;
}
static int gc_n64_init_ff(struct input_dev *dev, int i)
{
struct gc_subdev *sdev;
int err;
sdev = kmalloc(sizeof(*sdev), GFP_KERNEL);
if (!sdev)
return -ENOMEM;
sdev->idx = i;
input_set_capability(dev, EV_FF, FF_RUMBLE);
err = input_ff_create_memless(dev, sdev, gc_n64_play_effect);
if (err) {
kfree(sdev);
return err;
}
return 0;
}
/*
* NES/SNES support.
*/
#define GC_NES_DELAY 6 /* Delay between bits - 6us */
#define GC_NES_LENGTH 8 /* The NES pads use 8 bits of data */
#define GC_SNES_LENGTH 12 /* The SNES true length is 16, but the
last 4 bits are unused */
#define GC_SNESMOUSE_LENGTH 32 /* The SNES mouse uses 32 bits, the first
16 bits are equivalent to a gamepad */
#define GC_NES_POWER 0xfc
#define GC_NES_CLOCK 0x01
#define GC_NES_LATCH 0x02
static const unsigned char gc_nes_bytes[] = { 0, 1, 2, 3 };
static const unsigned char gc_snes_bytes[] = { 8, 0, 2, 3, 9, 1, 10, 11 };
static const short gc_snes_btn[] = {
BTN_A, BTN_B, BTN_SELECT, BTN_START, BTN_X, BTN_Y, BTN_TL, BTN_TR
};
/*
* gc_nes_read_packet() reads a NES/SNES packet.
* Each pad uses one bit per byte. So all pads connected to
* this port are read in parallel.
*/
static void gc_nes_read_packet(struct gc *gc, int length, unsigned char *data)
{
int i;
parport_write_data(gc->pd->port, GC_NES_POWER | GC_NES_CLOCK | GC_NES_LATCH);
udelay(GC_NES_DELAY * 2);
parport_write_data(gc->pd->port, GC_NES_POWER | GC_NES_CLOCK);
for (i = 0; i < length; i++) {
udelay(GC_NES_DELAY);
parport_write_data(gc->pd->port, GC_NES_POWER);
data[i] = parport_read_status(gc->pd->port) ^ 0x7f;
udelay(GC_NES_DELAY);
parport_write_data(gc->pd->port, GC_NES_POWER | GC_NES_CLOCK);
}
}
static void gc_nes_process_packet(struct gc *gc)
{
unsigned char data[GC_SNESMOUSE_LENGTH];
struct gc_pad *pad;
struct input_dev *dev;
int i, j, s, len;
char x_rel, y_rel;
len = gc->pad_count[GC_SNESMOUSE] ? GC_SNESMOUSE_LENGTH :
(gc->pad_count[GC_SNES] ? GC_SNES_LENGTH : GC_NES_LENGTH);
gc_nes_read_packet(gc, len, data);
for (i = 0; i < GC_MAX_DEVICES; i++) {
pad = &gc->pads[i];
dev = pad->dev;
s = gc_status_bit[i];
switch (pad->type) {
case GC_NES:
input_report_abs(dev, ABS_X, !(s & data[6]) - !(s & data[7]));
input_report_abs(dev, ABS_Y, !(s & data[4]) - !(s & data[5]));
for (j = 0; j < 4; j++)
input_report_key(dev, gc_snes_btn[j],
s & data[gc_nes_bytes[j]]);
input_sync(dev);
break;
case GC_SNES:
input_report_abs(dev, ABS_X, !(s & data[6]) - !(s & data[7]));
input_report_abs(dev, ABS_Y, !(s & data[4]) - !(s & data[5]));
for (j = 0; j < 8; j++)
input_report_key(dev, gc_snes_btn[j],
s & data[gc_snes_bytes[j]]);
input_sync(dev);
break;
case GC_SNESMOUSE:
/*
* The 4 unused bits from SNES controllers appear
* to be ID bits so use them to make sure we are
* dealing with a mouse.
* gamepad is connected. This is important since
* my SNES gamepad sends 1's for bits 16-31, which
* cause the mouse pointer to quickly move to the
* upper left corner of the screen.
*/
if (!(s & data[12]) && !(s & data[13]) &&
!(s & data[14]) && (s & data[15])) {
input_report_key(dev, BTN_LEFT, s & data[9]);
input_report_key(dev, BTN_RIGHT, s & data[8]);
x_rel = y_rel = 0;
for (j = 0; j < 7; j++) {
x_rel <<= 1;
if (data[25 + j] & s)
x_rel |= 1;
y_rel <<= 1;
if (data[17 + j] & s)
y_rel |= 1;
}
if (x_rel) {
if (data[24] & s)
x_rel = -x_rel;
input_report_rel(dev, REL_X, x_rel);
}
if (y_rel) {
if (data[16] & s)
y_rel = -y_rel;
input_report_rel(dev, REL_Y, y_rel);
}
input_sync(dev);
}
break;
default:
break;
}
}
}
/*
* Multisystem joystick support
*/
#define GC_MULTI_LENGTH 5 /* Multi system joystick packet length is 5 */
#define GC_MULTI2_LENGTH 6 /* One more bit for one more button */
/*
* gc_multi_read_packet() reads a Multisystem joystick packet.
*/
static void gc_multi_read_packet(struct gc *gc, int length, unsigned char *data)
{
int i;
for (i = 0; i < length; i++) {
parport_write_data(gc->pd->port, ~(1 << i));
data[i] = parport_read_status(gc->pd->port) ^ 0x7f;
}
}
static void gc_multi_process_packet(struct gc *gc)
{
unsigned char data[GC_MULTI2_LENGTH];
int data_len = gc->pad_count[GC_MULTI2] ? GC_MULTI2_LENGTH : GC_MULTI_LENGTH;
struct gc_pad *pad;
struct input_dev *dev;
int i, s;
gc_multi_read_packet(gc, data_len, data);
for (i = 0; i < GC_MAX_DEVICES; i++) {
pad = &gc->pads[i];
dev = pad->dev;
s = gc_status_bit[i];
switch (pad->type) {
case GC_MULTI2:
input_report_key(dev, BTN_THUMB, s & data[5]);
fallthrough;
case GC_MULTI:
input_report_abs(dev, ABS_X,
!(s & data[2]) - !(s & data[3]));
input_report_abs(dev, ABS_Y,
!(s & data[0]) - !(s & data[1]));
input_report_key(dev, BTN_TRIGGER, s & data[4]);
input_sync(dev);
break;
default:
break;
}
}
}
/*
* PSX support
*
* See documentation at:
* http://www.geocities.co.jp/Playtown/2004/psx/ps_eng.txt
* http://www.gamesx.com/controldata/psxcont/psxcont.htm
*
*/
#define GC_PSX_DELAY 25 /* 25 usec */
#define GC_PSX_LENGTH 8 /* talk to the controller in bits */
#define GC_PSX_BYTES 6 /* the maximum number of bytes to read off the controller */
#define GC_PSX_MOUSE 1 /* Mouse */
#define GC_PSX_NEGCON 2 /* NegCon */
#define GC_PSX_NORMAL 4 /* Digital / Analog or Rumble in Digital mode */
#define GC_PSX_ANALOG 5 /* Analog in Analog mode / Rumble in Green mode */
#define GC_PSX_RUMBLE 7 /* Rumble in Red mode */
#define GC_PSX_CLOCK 0x04 /* Pin 4 */
#define GC_PSX_COMMAND 0x01 /* Pin 2 */
#define GC_PSX_POWER 0xf8 /* Pins 5-9 */
#define GC_PSX_SELECT 0x02 /* Pin 3 */
#define GC_PSX_ID(x) ((x) >> 4) /* High nibble is device type */
#define GC_PSX_LEN(x) (((x) & 0xf) << 1) /* Low nibble is length in bytes/2 */
static int gc_psx_delay = GC_PSX_DELAY;
module_param_named(psx_delay, gc_psx_delay, uint, 0);
MODULE_PARM_DESC(psx_delay, "Delay when accessing Sony PSX controller (usecs)");
static const short gc_psx_abs[] = {
ABS_X, ABS_Y, ABS_RX, ABS_RY, ABS_HAT0X, ABS_HAT0Y
};
static const short gc_psx_btn[] = {
BTN_TL, BTN_TR, BTN_TL2, BTN_TR2, BTN_A, BTN_B, BTN_X, BTN_Y,
BTN_START, BTN_SELECT, BTN_THUMBL, BTN_THUMBR
};
static const short gc_psx_ddr_btn[] = { BTN_0, BTN_1, BTN_2, BTN_3 };
/*
* gc_psx_command() writes 8bit command and reads 8bit data from
* the psx pad.
*/
static void gc_psx_command(struct gc *gc, int b, unsigned char *data)
{
struct parport *port = gc->pd->port;
int i, j, cmd, read;
memset(data, 0, GC_MAX_DEVICES);
for (i = 0; i < GC_PSX_LENGTH; i++, b >>= 1) {
cmd = (b & 1) ? GC_PSX_COMMAND : 0;
parport_write_data(port, cmd | GC_PSX_POWER);
udelay(gc_psx_delay);
read = parport_read_status(port) ^ 0x80;
for (j = 0; j < GC_MAX_DEVICES; j++) {
struct gc_pad *pad = &gc->pads[j];
if (pad->type == GC_PSX || pad->type == GC_DDR)
data[j] |= (read & gc_status_bit[j]) ? (1 << i) : 0;
}
parport_write_data(gc->pd->port, cmd | GC_PSX_CLOCK | GC_PSX_POWER);
udelay(gc_psx_delay);
}
}
/*
* gc_psx_read_packet() reads a whole psx packet and returns
* device identifier code.
*/
static void gc_psx_read_packet(struct gc *gc,
unsigned char data[GC_MAX_DEVICES][GC_PSX_BYTES],
unsigned char id[GC_MAX_DEVICES])
{
int i, j, max_len = 0;
unsigned long flags;
unsigned char data2[GC_MAX_DEVICES];
/* Select pad */
parport_write_data(gc->pd->port, GC_PSX_CLOCK | GC_PSX_SELECT | GC_PSX_POWER);
udelay(gc_psx_delay);
/* Deselect, begin command */
parport_write_data(gc->pd->port, GC_PSX_CLOCK | GC_PSX_POWER);
udelay(gc_psx_delay);
local_irq_save(flags);
gc_psx_command(gc, 0x01, data2); /* Access pad */
gc_psx_command(gc, 0x42, id); /* Get device ids */
gc_psx_command(gc, 0, data2); /* Dump status */
/* Find the longest pad */
for (i = 0; i < GC_MAX_DEVICES; i++) {
struct gc_pad *pad = &gc->pads[i];
if ((pad->type == GC_PSX || pad->type == GC_DDR) &&
GC_PSX_LEN(id[i]) > max_len &&
GC_PSX_LEN(id[i]) <= GC_PSX_BYTES) {
max_len = GC_PSX_LEN(id[i]);
}
}
/* Read in all the data */
for (i = 0; i < max_len; i++) {
gc_psx_command(gc, 0, data2);
for (j = 0; j < GC_MAX_DEVICES; j++)
data[j][i] = data2[j];
}
local_irq_restore(flags);
parport_write_data(gc->pd->port, GC_PSX_CLOCK | GC_PSX_SELECT | GC_PSX_POWER);
/* Set id's to the real value */
for (i = 0; i < GC_MAX_DEVICES; i++)
id[i] = GC_PSX_ID(id[i]);
}
static void gc_psx_report_one(struct gc_pad *pad, unsigned char psx_type,
unsigned char *data)
{
struct input_dev *dev = pad->dev;
int i;
switch (psx_type) {
case GC_PSX_RUMBLE:
input_report_key(dev, BTN_THUMBL, ~data[0] & 0x04);
input_report_key(dev, BTN_THUMBR, ~data[0] & 0x02);
fallthrough;
case GC_PSX_NEGCON:
case GC_PSX_ANALOG:
if (pad->type == GC_DDR) {
for (i = 0; i < 4; i++)
input_report_key(dev, gc_psx_ddr_btn[i],
~data[0] & (0x10 << i));
} else {
for (i = 0; i < 4; i++)
input_report_abs(dev, gc_psx_abs[i + 2],
data[i + 2]);
input_report_abs(dev, ABS_X,
!!(data[0] & 0x80) * 128 + !(data[0] & 0x20) * 127);
input_report_abs(dev, ABS_Y,
!!(data[0] & 0x10) * 128 + !(data[0] & 0x40) * 127);
}
for (i = 0; i < 8; i++)
input_report_key(dev, gc_psx_btn[i], ~data[1] & (1 << i));
input_report_key(dev, BTN_START, ~data[0] & 0x08);
input_report_key(dev, BTN_SELECT, ~data[0] & 0x01);
input_sync(dev);
break;
case GC_PSX_NORMAL:
if (pad->type == GC_DDR) {
for (i = 0; i < 4; i++)
input_report_key(dev, gc_psx_ddr_btn[i],
~data[0] & (0x10 << i));
} else {
input_report_abs(dev, ABS_X,
!!(data[0] & 0x80) * 128 + !(data[0] & 0x20) * 127);
input_report_abs(dev, ABS_Y,
!!(data[0] & 0x10) * 128 + !(data[0] & 0x40) * 127);
/*
* For some reason if the extra axes are left unset
* they drift.
* for (i = 0; i < 4; i++)
input_report_abs(dev, gc_psx_abs[i + 2], 128);
* This needs to be debugged properly,
* maybe fuzz processing needs to be done
* in input_sync()
* --vojtech
*/
}
for (i = 0; i < 8; i++)
input_report_key(dev, gc_psx_btn[i], ~data[1] & (1 << i));
input_report_key(dev, BTN_START, ~data[0] & 0x08);
input_report_key(dev, BTN_SELECT, ~data[0] & 0x01);
input_sync(dev);
break;
default: /* not a pad, ignore */
break;
}
}
static void gc_psx_process_packet(struct gc *gc)
{
unsigned char data[GC_MAX_DEVICES][GC_PSX_BYTES];
unsigned char id[GC_MAX_DEVICES];
struct gc_pad *pad;
int i;
gc_psx_read_packet(gc, data, id);
for (i = 0; i < GC_MAX_DEVICES; i++) {
pad = &gc->pads[i];
if (pad->type == GC_PSX || pad->type == GC_DDR)
gc_psx_report_one(pad, id[i], data[i]);
}
}
/*
* gc_timer() initiates reads of console pads data.
*/
static void gc_timer(struct timer_list *t)
{
struct gc *gc = from_timer(gc, t, timer);
/*
* N64 pads - must be read first, any read confuses them for 200 us
*/
if (gc->pad_count[GC_N64])
gc_n64_process_packet(gc);
/*
* NES and SNES pads or mouse
*/
if (gc->pad_count[GC_NES] ||
gc->pad_count[GC_SNES] ||
gc->pad_count[GC_SNESMOUSE]) {
gc_nes_process_packet(gc);
}
/*
* Multi and Multi2 joysticks
*/
if (gc->pad_count[GC_MULTI] || gc->pad_count[GC_MULTI2])
gc_multi_process_packet(gc);
/*
* PSX controllers
*/
if (gc->pad_count[GC_PSX] || gc->pad_count[GC_DDR])
gc_psx_process_packet(gc);
mod_timer(&gc->timer, jiffies + GC_REFRESH_TIME);
}
static int gc_open(struct input_dev *dev)
{
struct gc *gc = input_get_drvdata(dev);
int err;
err = mutex_lock_interruptible(&gc->mutex);
if (err)
return err;
if (!gc->used++) {
parport_claim(gc->pd);
parport_write_control(gc->pd->port, 0x04);
mod_timer(&gc->timer, jiffies + GC_REFRESH_TIME);
}
mutex_unlock(&gc->mutex);
return 0;
}
static void gc_close(struct input_dev *dev)
{
struct gc *gc = input_get_drvdata(dev);
mutex_lock(&gc->mutex);
if (!--gc->used) {
del_timer_sync(&gc->timer);
parport_write_control(gc->pd->port, 0x00);
parport_release(gc->pd);
}
mutex_unlock(&gc->mutex);
}
static int gc_setup_pad(struct gc *gc, int idx, int pad_type)
{
struct gc_pad *pad = &gc->pads[idx];
struct input_dev *input_dev;
int i;
int err;
if (pad_type < 1 || pad_type >= GC_MAX) {
pr_err("Pad type %d unknown\n", pad_type);
return -EINVAL;
}
pad->dev = input_dev = input_allocate_device();
if (!input_dev) {
pr_err("Not enough memory for input device\n");
return -ENOMEM;
}
pad->type = pad_type;
snprintf(pad->phys, sizeof(pad->phys),
"%s/input%d", gc->pd->port->name, idx);
input_dev->name = gc_names[pad_type];
input_dev->phys = pad->phys;
input_dev->id.bustype = BUS_PARPORT;
input_dev->id.vendor = 0x0001;
input_dev->id.product = pad_type;
input_dev->id.version = 0x0100;
input_set_drvdata(input_dev, gc);
input_dev->open = gc_open;
input_dev->close = gc_close;
if (pad_type != GC_SNESMOUSE) {
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; i < 2; i++)
input_set_abs_params(input_dev, ABS_X + i, -1, 1, 0, 0);
} else
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
gc->pad_count[pad_type]++;
switch (pad_type) {
case GC_N64:
for (i = 0; i < 10; i++)
input_set_capability(input_dev, EV_KEY, gc_n64_btn[i]);
for (i = 0; i < 2; i++) {
input_set_abs_params(input_dev, ABS_X + i, -127, 126, 0, 2);
input_set_abs_params(input_dev, ABS_HAT0X + i, -1, 1, 0, 0);
}
err = gc_n64_init_ff(input_dev, idx);
if (err) {
pr_warn("Failed to initiate rumble for N64 device %d\n",
idx);
goto err_free_dev;
}
break;
case GC_SNESMOUSE:
input_set_capability(input_dev, EV_KEY, BTN_LEFT);
input_set_capability(input_dev, EV_KEY, BTN_RIGHT);
input_set_capability(input_dev, EV_REL, REL_X);
input_set_capability(input_dev, EV_REL, REL_Y);
break;
case GC_SNES:
for (i = 4; i < 8; i++)
input_set_capability(input_dev, EV_KEY, gc_snes_btn[i]);
fallthrough;
case GC_NES:
for (i = 0; i < 4; i++)
input_set_capability(input_dev, EV_KEY, gc_snes_btn[i]);
break;
case GC_MULTI2:
input_set_capability(input_dev, EV_KEY, BTN_THUMB);
fallthrough;
case GC_MULTI:
input_set_capability(input_dev, EV_KEY, BTN_TRIGGER);
break;
case GC_PSX:
for (i = 0; i < 6; i++)
input_set_abs_params(input_dev,
gc_psx_abs[i], 4, 252, 0, 2);
for (i = 0; i < 12; i++)
input_set_capability(input_dev, EV_KEY, gc_psx_btn[i]);
break;
break;
case GC_DDR:
for (i = 0; i < 4; i++)
input_set_capability(input_dev, EV_KEY,
gc_psx_ddr_btn[i]);
for (i = 0; i < 12; i++)
input_set_capability(input_dev, EV_KEY, gc_psx_btn[i]);
break;
}
err = input_register_device(pad->dev);
if (err)
goto err_free_dev;
return 0;
err_free_dev:
input_free_device(pad->dev);
pad->dev = NULL;
return err;
}
static void gc_attach(struct parport *pp)
{
struct gc *gc;
struct pardevice *pd;
int i, port_idx;
int count = 0;
int *pads, n_pads;
struct pardev_cb gc_parport_cb;
for (port_idx = 0; port_idx < GC_MAX_PORTS; port_idx++) {
if (gc_cfg[port_idx].nargs == 0 || gc_cfg[port_idx].args[0] < 0)
continue;
if (gc_cfg[port_idx].args[0] == pp->number)
break;
}
if (port_idx == GC_MAX_PORTS) {
pr_debug("Not using parport%d.\n", pp->number);
return;
}
pads = gc_cfg[port_idx].args + 1;
n_pads = gc_cfg[port_idx].nargs - 1;
memset(&gc_parport_cb, 0, sizeof(gc_parport_cb));
gc_parport_cb.flags = PARPORT_FLAG_EXCL;
pd = parport_register_dev_model(pp, "gamecon", &gc_parport_cb,
port_idx);
if (!pd) {
pr_err("parport busy already - lp.o loaded?\n");
return;
}
gc = kzalloc(sizeof(struct gc), GFP_KERNEL);
if (!gc) {
pr_err("Not enough memory\n");
goto err_unreg_pardev;
}
mutex_init(&gc->mutex);
gc->pd = pd;
gc->parportno = pp->number;
timer_setup(&gc->timer, gc_timer, 0);
for (i = 0; i < n_pads && i < GC_MAX_DEVICES; i++) {
if (!pads[i])
continue;
if (gc_setup_pad(gc, i, pads[i]))
goto err_unreg_devs;
count++;
}
if (count == 0) {
pr_err("No valid devices specified\n");
goto err_free_gc;
}
gc_base[port_idx] = gc;
return;
err_unreg_devs:
while (--i >= 0)
if (gc->pads[i].dev)
input_unregister_device(gc->pads[i].dev);
err_free_gc:
kfree(gc);
err_unreg_pardev:
parport_unregister_device(pd);
}
static void gc_detach(struct parport *port)
{
int i;
struct gc *gc;
for (i = 0; i < GC_MAX_PORTS; i++) {
if (gc_base[i] && gc_base[i]->parportno == port->number)
break;
}
if (i == GC_MAX_PORTS)
return;
gc = gc_base[i];
gc_base[i] = NULL;
for (i = 0; i < GC_MAX_DEVICES; i++)
if (gc->pads[i].dev)
input_unregister_device(gc->pads[i].dev);
parport_unregister_device(gc->pd);
kfree(gc);
}
static struct parport_driver gc_parport_driver = {
.name = "gamecon",
.match_port = gc_attach,
.detach = gc_detach,
.devmodel = true,
};
static int __init gc_init(void)
{
int i;
int have_dev = 0;
for (i = 0; i < GC_MAX_PORTS; i++) {
if (gc_cfg[i].nargs == 0 || gc_cfg[i].args[0] < 0)
continue;
if (gc_cfg[i].nargs < 2) {
pr_err("at least one device must be specified\n");
return -EINVAL;
}
have_dev = 1;
}
if (!have_dev)
return -ENODEV;
return parport_register_driver(&gc_parport_driver);
}
static void __exit gc_exit(void)
{
parport_unregister_driver(&gc_parport_driver);
}
module_init(gc_init);
module_exit(gc_exit);
|
linux-master
|
drivers/input/joystick/gamecon.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Driver for the Gravis Grip Multiport, a gamepad "hub" that
* connects up to four 9-pin digital gamepads/joysticks.
* Driver tested on SMP and UP kernel versions 2.4.18-4 and 2.4.18-5.
*
* Thanks to Chris Gassib for helpful advice.
*
* Copyright (c) 2002 Brian Bonnlander, Bill Soudan
* Copyright (c) 1998-2000 Vojtech Pavlik
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/input.h>
#include <linux/delay.h>
#include <linux/proc_fs.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "Gravis Grip Multiport driver"
MODULE_AUTHOR("Brian Bonnlander");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#ifdef GRIP_DEBUG
#define dbg(format, arg...) printk(KERN_ERR __FILE__ ": " format "\n" , ## arg)
#else
#define dbg(format, arg...) do {} while (0)
#endif
#define GRIP_MAX_PORTS 4
/*
* Grip multiport state
*/
struct grip_port {
struct input_dev *dev;
int mode;
int registered;
/* individual gamepad states */
int buttons;
int xaxes;
int yaxes;
int dirty; /* has the state been updated? */
};
struct grip_mp {
struct gameport *gameport;
struct grip_port *port[GRIP_MAX_PORTS];
int reads;
int bads;
};
/*
* Multiport packet interpretation
*/
#define PACKET_FULL 0x80000000 /* packet is full */
#define PACKET_IO_FAST 0x40000000 /* 3 bits per gameport read */
#define PACKET_IO_SLOW 0x20000000 /* 1 bit per gameport read */
#define PACKET_MP_MORE 0x04000000 /* multiport wants to send more */
#define PACKET_MP_DONE 0x02000000 /* multiport done sending */
/*
* Packet status code interpretation
*/
#define IO_GOT_PACKET 0x0100 /* Got a packet */
#define IO_MODE_FAST 0x0200 /* Used 3 data bits per gameport read */
#define IO_SLOT_CHANGE 0x0800 /* Multiport physical slot status changed */
#define IO_DONE 0x1000 /* Multiport is done sending packets */
#define IO_RETRY 0x4000 /* Try again later to get packet */
#define IO_RESET 0x8000 /* Force multiport to resend all packets */
/*
* Gamepad configuration data. Other 9-pin digital joystick devices
* may work with the multiport, so this may not be an exhaustive list!
* Commodore 64 joystick remains untested.
*/
#define GRIP_INIT_DELAY 2000 /* 2 ms */
#define GRIP_MODE_NONE 0
#define GRIP_MODE_RESET 1
#define GRIP_MODE_GP 2
#define GRIP_MODE_C64 3
static const int grip_btn_gp[] = { BTN_TR, BTN_TL, BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, -1 };
static const int grip_btn_c64[] = { BTN_JOYSTICK, -1 };
static const int grip_abs_gp[] = { ABS_X, ABS_Y, -1 };
static const int grip_abs_c64[] = { ABS_X, ABS_Y, -1 };
static const int *grip_abs[] = { NULL, NULL, grip_abs_gp, grip_abs_c64 };
static const int *grip_btn[] = { NULL, NULL, grip_btn_gp, grip_btn_c64 };
static const char *grip_name[] = { NULL, NULL, "Gravis Grip Pad", "Commodore 64 Joystick" };
static const int init_seq[] = {
1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1,
1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1,
1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1 };
/* Maps multiport directional values to X,Y axis values (each axis encoded in 3 bits) */
static const int axis_map[] = { 5, 9, 1, 5, 6, 10, 2, 6, 4, 8, 0, 4, 5, 9, 1, 5 };
static int register_slot(int i, struct grip_mp *grip);
/*
* Returns whether an odd or even number of bits are on in pkt.
*/
static int bit_parity(u32 pkt)
{
int x = pkt ^ (pkt >> 16);
x ^= x >> 8;
x ^= x >> 4;
x ^= x >> 2;
x ^= x >> 1;
return x & 1;
}
/*
* Poll gameport; return true if all bits set in 'onbits' are on and
* all bits set in 'offbits' are off.
*/
static inline int poll_until(u8 onbits, u8 offbits, int u_sec, struct gameport* gp, u8 *data)
{
int i, nloops;
nloops = gameport_time(gp, u_sec);
for (i = 0; i < nloops; i++) {
*data = gameport_read(gp);
if ((*data & onbits) == onbits &&
(~(*data) & offbits) == offbits)
return 1;
}
dbg("gameport timed out after %d microseconds.\n", u_sec);
return 0;
}
/*
* Gets a 28-bit packet from the multiport.
*
* After getting a packet successfully, commands encoded by sendcode may
* be sent to the multiport.
*
* The multiport clock value is reflected in gameport bit B4.
*
* Returns a packet status code indicating whether packet is valid, the transfer
* mode, and any error conditions.
*
* sendflags: current I/O status
* sendcode: data to send to the multiport if sendflags is nonzero
*/
static int mp_io(struct gameport* gameport, int sendflags, int sendcode, u32 *packet)
{
u8 raw_data; /* raw data from gameport */
u8 data_mask; /* packet data bits from raw_data */
u32 pkt; /* packet temporary storage */
int bits_per_read; /* num packet bits per gameport read */
int portvals = 0; /* used for port value sanity check */
int i;
/* Gameport bits B0, B4, B5 should first be off, then B4 should come on. */
*packet = 0;
raw_data = gameport_read(gameport);
if (raw_data & 1)
return IO_RETRY;
for (i = 0; i < 64; i++) {
raw_data = gameport_read(gameport);
portvals |= 1 << ((raw_data >> 4) & 3); /* Demux B4, B5 */
}
if (portvals == 1) { /* B4, B5 off */
raw_data = gameport_read(gameport);
portvals = raw_data & 0xf0;
if (raw_data & 0x31)
return IO_RESET;
gameport_trigger(gameport);
if (!poll_until(0x10, 0, 308, gameport, &raw_data))
return IO_RESET;
} else
return IO_RETRY;
/* Determine packet transfer mode and prepare for packet construction. */
if (raw_data & 0x20) { /* 3 data bits/read */
portvals |= raw_data >> 4; /* Compare B4-B7 before & after trigger */
if (portvals != 0xb)
return 0;
data_mask = 7;
bits_per_read = 3;
pkt = (PACKET_FULL | PACKET_IO_FAST) >> 28;
} else { /* 1 data bit/read */
data_mask = 1;
bits_per_read = 1;
pkt = (PACKET_FULL | PACKET_IO_SLOW) >> 28;
}
/* Construct a packet. Final data bits must be zero. */
while (1) {
if (!poll_until(0, 0x10, 77, gameport, &raw_data))
return IO_RESET;
raw_data = (raw_data >> 5) & data_mask;
if (pkt & PACKET_FULL)
break;
pkt = (pkt << bits_per_read) | raw_data;
if (!poll_until(0x10, 0, 77, gameport, &raw_data))
return IO_RESET;
}
if (raw_data)
return IO_RESET;
/* If 3 bits/read used, drop from 30 bits to 28. */
if (bits_per_read == 3) {
pkt = (pkt & 0xffff0000) | ((pkt << 1) & 0xffff);
pkt = (pkt >> 2) | 0xf0000000;
}
if (bit_parity(pkt) == 1)
return IO_RESET;
/* Acknowledge packet receipt */
if (!poll_until(0x30, 0, 77, gameport, &raw_data))
return IO_RESET;
raw_data = gameport_read(gameport);
if (raw_data & 1)
return IO_RESET;
gameport_trigger(gameport);
if (!poll_until(0, 0x20, 77, gameport, &raw_data))
return IO_RESET;
/* Return if we just wanted the packet or multiport wants to send more */
*packet = pkt;
if ((sendflags == 0) || ((sendflags & IO_RETRY) && !(pkt & PACKET_MP_DONE)))
return IO_GOT_PACKET;
if (pkt & PACKET_MP_MORE)
return IO_GOT_PACKET | IO_RETRY;
/* Multiport is done sending packets and is ready to receive data */
if (!poll_until(0x20, 0, 77, gameport, &raw_data))
return IO_GOT_PACKET | IO_RESET;
raw_data = gameport_read(gameport);
if (raw_data & 1)
return IO_GOT_PACKET | IO_RESET;
/* Trigger gameport based on bits in sendcode */
gameport_trigger(gameport);
do {
if (!poll_until(0x20, 0x10, 116, gameport, &raw_data))
return IO_GOT_PACKET | IO_RESET;
if (!poll_until(0x30, 0, 193, gameport, &raw_data))
return IO_GOT_PACKET | IO_RESET;
if (raw_data & 1)
return IO_GOT_PACKET | IO_RESET;
if (sendcode & 1)
gameport_trigger(gameport);
sendcode >>= 1;
} while (sendcode);
return IO_GOT_PACKET | IO_MODE_FAST;
}
/*
* Disables and restores interrupts for mp_io(), which does the actual I/O.
*/
static int multiport_io(struct gameport* gameport, int sendflags, int sendcode, u32 *packet)
{
int status;
unsigned long flags;
local_irq_save(flags);
status = mp_io(gameport, sendflags, sendcode, packet);
local_irq_restore(flags);
return status;
}
/*
* Puts multiport into digital mode. Multiport LED turns green.
*
* Returns true if a valid digital packet was received, false otherwise.
*/
static int dig_mode_start(struct gameport *gameport, u32 *packet)
{
int i;
int flags, tries = 0, bads = 0;
for (i = 0; i < ARRAY_SIZE(init_seq); i++) { /* Send magic sequence */
if (init_seq[i])
gameport_trigger(gameport);
udelay(GRIP_INIT_DELAY);
}
for (i = 0; i < 16; i++) /* Wait for multiport to settle */
udelay(GRIP_INIT_DELAY);
while (tries < 64 && bads < 8) { /* Reset multiport and try getting a packet */
flags = multiport_io(gameport, IO_RESET, 0x27, packet);
if (flags & IO_MODE_FAST)
return 1;
if (flags & IO_RETRY)
tries++;
else
bads++;
}
return 0;
}
/*
* Packet structure: B0-B15 => gamepad state
* B16-B20 => gamepad device type
* B21-B24 => multiport slot index (1-4)
*
* Known device types: 0x1f (grip pad), 0x0 (no device). Others may exist.
*
* Returns the packet status.
*/
static int get_and_decode_packet(struct grip_mp *grip, int flags)
{
struct grip_port *port;
u32 packet;
int joytype = 0;
int slot;
/* Get a packet and check for validity */
flags &= IO_RESET | IO_RETRY;
flags = multiport_io(grip->gameport, flags, 0, &packet);
grip->reads++;
if (packet & PACKET_MP_DONE)
flags |= IO_DONE;
if (flags && !(flags & IO_GOT_PACKET)) {
grip->bads++;
return flags;
}
/* Ignore non-gamepad packets, e.g. multiport hardware version */
slot = ((packet >> 21) & 0xf) - 1;
if ((slot < 0) || (slot > 3))
return flags;
port = grip->port[slot];
/*
* Handle "reset" packets, which occur at startup, and when gamepads
* are removed or plugged in. May contain configuration of a new gamepad.
*/
joytype = (packet >> 16) & 0x1f;
if (!joytype) {
if (port->registered) {
printk(KERN_INFO "grip_mp: removing %s, slot %d\n",
grip_name[port->mode], slot);
input_unregister_device(port->dev);
port->registered = 0;
}
dbg("Reset: grip multiport slot %d\n", slot);
port->mode = GRIP_MODE_RESET;
flags |= IO_SLOT_CHANGE;
return flags;
}
/* Interpret a grip pad packet */
if (joytype == 0x1f) {
int dir = (packet >> 8) & 0xf; /* eight way directional value */
port->buttons = (~packet) & 0xff;
port->yaxes = ((axis_map[dir] >> 2) & 3) - 1;
port->xaxes = (axis_map[dir] & 3) - 1;
port->dirty = 1;
if (port->mode == GRIP_MODE_RESET)
flags |= IO_SLOT_CHANGE;
port->mode = GRIP_MODE_GP;
if (!port->registered) {
dbg("New Grip pad in multiport slot %d.\n", slot);
if (register_slot(slot, grip)) {
port->mode = GRIP_MODE_RESET;
port->dirty = 0;
}
}
return flags;
}
/* Handle non-grip device codes. For now, just print diagnostics. */
{
static int strange_code = 0;
if (strange_code != joytype) {
printk(KERN_INFO "Possible non-grip pad/joystick detected.\n");
printk(KERN_INFO "Got joy type 0x%x and packet 0x%x.\n", joytype, packet);
strange_code = joytype;
}
}
return flags;
}
/*
* Returns true if all multiport slot states appear valid.
*/
static int slots_valid(struct grip_mp *grip)
{
int flags, slot, invalid = 0, active = 0;
flags = get_and_decode_packet(grip, 0);
if (!(flags & IO_GOT_PACKET))
return 0;
for (slot = 0; slot < 4; slot++) {
if (grip->port[slot]->mode == GRIP_MODE_RESET)
invalid = 1;
if (grip->port[slot]->mode != GRIP_MODE_NONE)
active = 1;
}
/* Return true if no active slot but multiport sent all its data */
if (!active)
return (flags & IO_DONE) ? 1 : 0;
/* Return false if invalid device code received */
return invalid ? 0 : 1;
}
/*
* Returns whether the multiport was placed into digital mode and
* able to communicate its state successfully.
*/
static int multiport_init(struct grip_mp *grip)
{
int dig_mode, initialized = 0, tries = 0;
u32 packet;
dig_mode = dig_mode_start(grip->gameport, &packet);
while (!dig_mode && tries < 4) {
dig_mode = dig_mode_start(grip->gameport, &packet);
tries++;
}
if (dig_mode)
dbg("multiport_init(): digital mode activated.\n");
else {
dbg("multiport_init(): unable to activate digital mode.\n");
return 0;
}
/* Get packets, store multiport state, and check state's validity */
for (tries = 0; tries < 4096; tries++) {
if (slots_valid(grip)) {
initialized = 1;
break;
}
}
dbg("multiport_init(): initialized == %d\n", initialized);
return initialized;
}
/*
* Reports joystick state to the linux input layer.
*/
static void report_slot(struct grip_mp *grip, int slot)
{
struct grip_port *port = grip->port[slot];
int i;
/* Store button states with linux input driver */
for (i = 0; i < 8; i++)
input_report_key(port->dev, grip_btn_gp[i], (port->buttons >> i) & 1);
/* Store axis states with linux driver */
input_report_abs(port->dev, ABS_X, port->xaxes);
input_report_abs(port->dev, ABS_Y, port->yaxes);
/* Tell the receiver of the events to process them */
input_sync(port->dev);
port->dirty = 0;
}
/*
* Get the multiport state.
*/
static void grip_poll(struct gameport *gameport)
{
struct grip_mp *grip = gameport_get_drvdata(gameport);
int i, npkts, flags;
for (npkts = 0; npkts < 4; npkts++) {
flags = IO_RETRY;
for (i = 0; i < 32; i++) {
flags = get_and_decode_packet(grip, flags);
if ((flags & IO_GOT_PACKET) || !(flags & IO_RETRY))
break;
}
if (flags & IO_DONE)
break;
}
for (i = 0; i < 4; i++)
if (grip->port[i]->dirty)
report_slot(grip, i);
}
/*
* Called when a joystick device file is opened
*/
static int grip_open(struct input_dev *dev)
{
struct grip_mp *grip = input_get_drvdata(dev);
gameport_start_polling(grip->gameport);
return 0;
}
/*
* Called when a joystick device file is closed
*/
static void grip_close(struct input_dev *dev)
{
struct grip_mp *grip = input_get_drvdata(dev);
gameport_stop_polling(grip->gameport);
}
/*
* Tell the linux input layer about a newly plugged-in gamepad.
*/
static int register_slot(int slot, struct grip_mp *grip)
{
struct grip_port *port = grip->port[slot];
struct input_dev *input_dev;
int j, t;
int err;
port->dev = input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
input_dev->name = grip_name[port->mode];
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_GRAVIS;
input_dev->id.product = 0x0100 + port->mode;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &grip->gameport->dev;
input_set_drvdata(input_dev, grip);
input_dev->open = grip_open;
input_dev->close = grip_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (j = 0; (t = grip_abs[port->mode][j]) >= 0; j++)
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
for (j = 0; (t = grip_btn[port->mode][j]) >= 0; j++)
if (t > 0)
set_bit(t, input_dev->keybit);
err = input_register_device(port->dev);
if (err) {
input_free_device(port->dev);
return err;
}
port->registered = 1;
if (port->dirty) /* report initial state, if any */
report_slot(grip, slot);
return 0;
}
static int grip_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct grip_mp *grip;
int err;
if (!(grip = kzalloc(sizeof(struct grip_mp), GFP_KERNEL)))
return -ENOMEM;
grip->gameport = gameport;
gameport_set_drvdata(gameport, grip);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
gameport_set_poll_handler(gameport, grip_poll);
gameport_set_poll_interval(gameport, 20);
if (!multiport_init(grip)) {
err = -ENODEV;
goto fail2;
}
if (!grip->port[0]->mode && !grip->port[1]->mode && !grip->port[2]->mode && !grip->port[3]->mode) {
/* nothing plugged in */
err = -ENODEV;
goto fail2;
}
return 0;
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(grip);
return err;
}
static void grip_disconnect(struct gameport *gameport)
{
struct grip_mp *grip = gameport_get_drvdata(gameport);
int i;
for (i = 0; i < 4; i++)
if (grip->port[i]->registered)
input_unregister_device(grip->port[i]->dev);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(grip);
}
static struct gameport_driver grip_drv = {
.driver = {
.name = "grip_mp",
},
.description = DRIVER_DESC,
.connect = grip_connect,
.disconnect = grip_disconnect,
};
module_gameport_driver(grip_drv);
|
linux-master
|
drivers/input/joystick/grip_mp.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Xbox gamepad driver
*
* Copyright (c) 2002 Marko Friedemann <[email protected]>
* 2004 Oliver Schwartz <[email protected]>,
* Steven Toth <[email protected]>,
* Franz Lehner <[email protected]>,
* Ivan Hawkes <[email protected]>
* 2005 Dominic Cerquetti <[email protected]>
* 2006 Adam Buchbinder <[email protected]>
* 2007 Jan Kratochvil <[email protected]>
* 2010 Christoph Fritz <[email protected]>
*
* This driver is based on:
* - information from http://euc.jp/periphs/xbox-controller.ja.html
* - the iForce driver drivers/char/joystick/iforce.c
* - the skeleton-driver drivers/usb/usb-skeleton.c
* - Xbox 360 information http://www.free60.org/wiki/Gamepad
* - Xbox One information https://github.com/quantus/xbox-one-controller-protocol
*
* Thanks to:
* - ITO Takayuki for providing essential xpad information on his website
* - Vojtech Pavlik - iforce driver / input subsystem
* - Greg Kroah-Hartman - usb-skeleton driver
* - Xbox Linux project - extra USB IDs
* - Pekka Pöyry (quantus) - Xbox One controller reverse-engineering
*
* TODO:
* - fine tune axes (especially trigger axes)
* - fix "analog" buttons (reported as digital now)
* - get rumble working
* - need USB IDs for other dance pads
*
* History:
*
* 2002-06-27 - 0.0.1 : first version, just said "XBOX HID controller"
*
* 2002-07-02 - 0.0.2 : basic working version
* - all axes and 9 of the 10 buttons work (german InterAct device)
* - the black button does not work
*
* 2002-07-14 - 0.0.3 : rework by Vojtech Pavlik
* - indentation fixes
* - usb + input init sequence fixes
*
* 2002-07-16 - 0.0.4 : minor changes, merge with Vojtech's v0.0.3
* - verified the lack of HID and report descriptors
* - verified that ALL buttons WORK
* - fixed d-pad to axes mapping
*
* 2002-07-17 - 0.0.5 : simplified d-pad handling
*
* 2004-10-02 - 0.0.6 : DDR pad support
* - borrowed from the Xbox Linux kernel
* - USB id's for commonly used dance pads are present
* - dance pads will map D-PAD to buttons, not axes
* - pass the module paramater 'dpad_to_buttons' to force
* the D-PAD to map to buttons if your pad is not detected
*
* Later changes can be tracked in SCM.
*/
#include <linux/bits.h>
#include <linux/kernel.h>
#include <linux/input.h>
#include <linux/rcupdate.h>
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/module.h>
#include <linux/usb/input.h>
#include <linux/usb/quirks.h>
#define XPAD_PKT_LEN 64
/*
* xbox d-pads should map to buttons, as is required for DDR pads
* but we map them to axes when possible to simplify things
*/
#define MAP_DPAD_TO_BUTTONS (1 << 0)
#define MAP_TRIGGERS_TO_BUTTONS (1 << 1)
#define MAP_STICKS_TO_NULL (1 << 2)
#define MAP_SELECT_BUTTON (1 << 3)
#define MAP_PADDLES (1 << 4)
#define MAP_PROFILE_BUTTON (1 << 5)
#define DANCEPAD_MAP_CONFIG (MAP_DPAD_TO_BUTTONS | \
MAP_TRIGGERS_TO_BUTTONS | MAP_STICKS_TO_NULL)
#define XTYPE_XBOX 0
#define XTYPE_XBOX360 1
#define XTYPE_XBOX360W 2
#define XTYPE_XBOXONE 3
#define XTYPE_UNKNOWN 4
/* Send power-off packet to xpad360w after holding the mode button for this many
* seconds
*/
#define XPAD360W_POWEROFF_TIMEOUT 5
#define PKT_XB 0
#define PKT_XBE1 1
#define PKT_XBE2_FW_OLD 2
#define PKT_XBE2_FW_5_EARLY 3
#define PKT_XBE2_FW_5_11 4
static bool dpad_to_buttons;
module_param(dpad_to_buttons, bool, S_IRUGO);
MODULE_PARM_DESC(dpad_to_buttons, "Map D-PAD to buttons rather than axes for unknown pads");
static bool triggers_to_buttons;
module_param(triggers_to_buttons, bool, S_IRUGO);
MODULE_PARM_DESC(triggers_to_buttons, "Map triggers to buttons rather than axes for unknown pads");
static bool sticks_to_null;
module_param(sticks_to_null, bool, S_IRUGO);
MODULE_PARM_DESC(sticks_to_null, "Do not map sticks at all for unknown pads");
static bool auto_poweroff = true;
module_param(auto_poweroff, bool, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(auto_poweroff, "Power off wireless controllers on suspend");
static const struct xpad_device {
u16 idVendor;
u16 idProduct;
char *name;
u8 mapping;
u8 xtype;
} xpad_device[] = {
{ 0x0079, 0x18d4, "GPD Win 2 X-Box Controller", 0, XTYPE_XBOX360 },
{ 0x03eb, 0xff01, "Wooting One (Legacy)", 0, XTYPE_XBOX360 },
{ 0x03eb, 0xff02, "Wooting Two (Legacy)", 0, XTYPE_XBOX360 },
{ 0x044f, 0x0f00, "Thrustmaster Wheel", 0, XTYPE_XBOX },
{ 0x044f, 0x0f03, "Thrustmaster Wheel", 0, XTYPE_XBOX },
{ 0x044f, 0x0f07, "Thrustmaster, Inc. Controller", 0, XTYPE_XBOX },
{ 0x044f, 0x0f10, "Thrustmaster Modena GT Wheel", 0, XTYPE_XBOX },
{ 0x044f, 0xb326, "Thrustmaster Gamepad GP XID", 0, XTYPE_XBOX360 },
{ 0x045e, 0x0202, "Microsoft X-Box pad v1 (US)", 0, XTYPE_XBOX },
{ 0x045e, 0x0285, "Microsoft X-Box pad (Japan)", 0, XTYPE_XBOX },
{ 0x045e, 0x0287, "Microsoft Xbox Controller S", 0, XTYPE_XBOX },
{ 0x045e, 0x0288, "Microsoft Xbox Controller S v2", 0, XTYPE_XBOX },
{ 0x045e, 0x0289, "Microsoft X-Box pad v2 (US)", 0, XTYPE_XBOX },
{ 0x045e, 0x028e, "Microsoft X-Box 360 pad", 0, XTYPE_XBOX360 },
{ 0x045e, 0x028f, "Microsoft X-Box 360 pad v2", 0, XTYPE_XBOX360 },
{ 0x045e, 0x0291, "Xbox 360 Wireless Receiver (XBOX)", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360W },
{ 0x045e, 0x02d1, "Microsoft X-Box One pad", 0, XTYPE_XBOXONE },
{ 0x045e, 0x02dd, "Microsoft X-Box One pad (Firmware 2015)", 0, XTYPE_XBOXONE },
{ 0x045e, 0x02e3, "Microsoft X-Box One Elite pad", MAP_PADDLES, XTYPE_XBOXONE },
{ 0x045e, 0x0b00, "Microsoft X-Box One Elite 2 pad", MAP_PADDLES, XTYPE_XBOXONE },
{ 0x045e, 0x02ea, "Microsoft X-Box One S pad", 0, XTYPE_XBOXONE },
{ 0x045e, 0x0719, "Xbox 360 Wireless Receiver", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360W },
{ 0x045e, 0x0b0a, "Microsoft X-Box Adaptive Controller", MAP_PROFILE_BUTTON, XTYPE_XBOXONE },
{ 0x045e, 0x0b12, "Microsoft Xbox Series S|X Controller", MAP_SELECT_BUTTON, XTYPE_XBOXONE },
{ 0x046d, 0xc21d, "Logitech Gamepad F310", 0, XTYPE_XBOX360 },
{ 0x046d, 0xc21e, "Logitech Gamepad F510", 0, XTYPE_XBOX360 },
{ 0x046d, 0xc21f, "Logitech Gamepad F710", 0, XTYPE_XBOX360 },
{ 0x046d, 0xc242, "Logitech Chillstream Controller", 0, XTYPE_XBOX360 },
{ 0x046d, 0xca84, "Logitech Xbox Cordless Controller", 0, XTYPE_XBOX },
{ 0x046d, 0xca88, "Logitech Compact Controller for Xbox", 0, XTYPE_XBOX },
{ 0x046d, 0xca8a, "Logitech Precision Vibration Feedback Wheel", 0, XTYPE_XBOX },
{ 0x046d, 0xcaa3, "Logitech DriveFx Racing Wheel", 0, XTYPE_XBOX360 },
{ 0x056e, 0x2004, "Elecom JC-U3613M", 0, XTYPE_XBOX360 },
{ 0x05fd, 0x1007, "Mad Catz Controller (unverified)", 0, XTYPE_XBOX },
{ 0x05fd, 0x107a, "InterAct 'PowerPad Pro' X-Box pad (Germany)", 0, XTYPE_XBOX },
{ 0x05fe, 0x3030, "Chic Controller", 0, XTYPE_XBOX },
{ 0x05fe, 0x3031, "Chic Controller", 0, XTYPE_XBOX },
{ 0x062a, 0x0020, "Logic3 Xbox GamePad", 0, XTYPE_XBOX },
{ 0x062a, 0x0033, "Competition Pro Steering Wheel", 0, XTYPE_XBOX },
{ 0x06a3, 0x0200, "Saitek Racing Wheel", 0, XTYPE_XBOX },
{ 0x06a3, 0x0201, "Saitek Adrenalin", 0, XTYPE_XBOX },
{ 0x06a3, 0xf51a, "Saitek P3600", 0, XTYPE_XBOX360 },
{ 0x0738, 0x4506, "Mad Catz 4506 Wireless Controller", 0, XTYPE_XBOX },
{ 0x0738, 0x4516, "Mad Catz Control Pad", 0, XTYPE_XBOX },
{ 0x0738, 0x4520, "Mad Catz Control Pad Pro", 0, XTYPE_XBOX },
{ 0x0738, 0x4522, "Mad Catz LumiCON", 0, XTYPE_XBOX },
{ 0x0738, 0x4526, "Mad Catz Control Pad Pro", 0, XTYPE_XBOX },
{ 0x0738, 0x4530, "Mad Catz Universal MC2 Racing Wheel and Pedals", 0, XTYPE_XBOX },
{ 0x0738, 0x4536, "Mad Catz MicroCON", 0, XTYPE_XBOX },
{ 0x0738, 0x4540, "Mad Catz Beat Pad", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX },
{ 0x0738, 0x4556, "Mad Catz Lynx Wireless Controller", 0, XTYPE_XBOX },
{ 0x0738, 0x4586, "Mad Catz MicroCon Wireless Controller", 0, XTYPE_XBOX },
{ 0x0738, 0x4588, "Mad Catz Blaster", 0, XTYPE_XBOX },
{ 0x0738, 0x45ff, "Mad Catz Beat Pad (w/ Handle)", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX },
{ 0x0738, 0x4716, "Mad Catz Wired Xbox 360 Controller", 0, XTYPE_XBOX360 },
{ 0x0738, 0x4718, "Mad Catz Street Fighter IV FightStick SE", 0, XTYPE_XBOX360 },
{ 0x0738, 0x4726, "Mad Catz Xbox 360 Controller", 0, XTYPE_XBOX360 },
{ 0x0738, 0x4728, "Mad Catz Street Fighter IV FightPad", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0738, 0x4736, "Mad Catz MicroCon Gamepad", 0, XTYPE_XBOX360 },
{ 0x0738, 0x4738, "Mad Catz Wired Xbox 360 Controller (SFIV)", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0738, 0x4740, "Mad Catz Beat Pad", 0, XTYPE_XBOX360 },
{ 0x0738, 0x4743, "Mad Catz Beat Pad Pro", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX },
{ 0x0738, 0x4758, "Mad Catz Arcade Game Stick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0738, 0x4a01, "Mad Catz FightStick TE 2", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE },
{ 0x0738, 0x6040, "Mad Catz Beat Pad Pro", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX },
{ 0x0738, 0x9871, "Mad Catz Portable Drum", 0, XTYPE_XBOX360 },
{ 0x0738, 0xb726, "Mad Catz Xbox controller - MW2", 0, XTYPE_XBOX360 },
{ 0x0738, 0xb738, "Mad Catz MVC2TE Stick 2", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0738, 0xbeef, "Mad Catz JOYTECH NEO SE Advanced GamePad", XTYPE_XBOX360 },
{ 0x0738, 0xcb02, "Saitek Cyborg Rumble Pad - PC/Xbox 360", 0, XTYPE_XBOX360 },
{ 0x0738, 0xcb03, "Saitek P3200 Rumble Pad - PC/Xbox 360", 0, XTYPE_XBOX360 },
{ 0x0738, 0xcb29, "Saitek Aviator Stick AV8R02", 0, XTYPE_XBOX360 },
{ 0x0738, 0xf738, "Super SFIV FightStick TE S", 0, XTYPE_XBOX360 },
{ 0x07ff, 0xffff, "Mad Catz GamePad", 0, XTYPE_XBOX360 },
{ 0x0c12, 0x0005, "Intec wireless", 0, XTYPE_XBOX },
{ 0x0c12, 0x8801, "Nyko Xbox Controller", 0, XTYPE_XBOX },
{ 0x0c12, 0x8802, "Zeroplus Xbox Controller", 0, XTYPE_XBOX },
{ 0x0c12, 0x8809, "RedOctane Xbox Dance Pad", DANCEPAD_MAP_CONFIG, XTYPE_XBOX },
{ 0x0c12, 0x880a, "Pelican Eclipse PL-2023", 0, XTYPE_XBOX },
{ 0x0c12, 0x8810, "Zeroplus Xbox Controller", 0, XTYPE_XBOX },
{ 0x0c12, 0x9902, "HAMA VibraX - *FAULTY HARDWARE*", 0, XTYPE_XBOX },
{ 0x0d2f, 0x0002, "Andamiro Pump It Up pad", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX },
{ 0x0e4c, 0x1097, "Radica Gamester Controller", 0, XTYPE_XBOX },
{ 0x0e4c, 0x1103, "Radica Gamester Reflex", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX },
{ 0x0e4c, 0x2390, "Radica Games Jtech Controller", 0, XTYPE_XBOX },
{ 0x0e4c, 0x3510, "Radica Gamester", 0, XTYPE_XBOX },
{ 0x0e6f, 0x0003, "Logic3 Freebird wireless Controller", 0, XTYPE_XBOX },
{ 0x0e6f, 0x0005, "Eclipse wireless Controller", 0, XTYPE_XBOX },
{ 0x0e6f, 0x0006, "Edge wireless Controller", 0, XTYPE_XBOX },
{ 0x0e6f, 0x0008, "After Glow Pro Controller", 0, XTYPE_XBOX },
{ 0x0e6f, 0x0105, "HSM3 Xbox360 dancepad", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0e6f, 0x0113, "Afterglow AX.1 Gamepad for Xbox 360", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x011f, "Rock Candy Gamepad Wired Controller", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0131, "PDP EA Sports Controller", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0133, "Xbox 360 Wired Controller", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0139, "Afterglow Prismatic Wired Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x013a, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0146, "Rock Candy Wired Controller for Xbox One", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0147, "PDP Marvel Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x015c, "PDP Xbox One Arcade Stick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE },
{ 0x0e6f, 0x0161, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0162, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0163, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0164, "PDP Battlefield One", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0165, "PDP Titanfall 2", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0201, "Pelican PL-3601 'TSZ' Wired Xbox 360 Controller", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0213, "Afterglow Gamepad for Xbox 360", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x021f, "Rock Candy Gamepad for Xbox 360", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0246, "Rock Candy Gamepad for Xbox One 2015", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02a0, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02a1, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02a2, "PDP Wired Controller for Xbox One - Crimson Red", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02a4, "PDP Wired Controller for Xbox One - Stealth Series", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02a6, "PDP Wired Controller for Xbox One - Camo Series", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02a7, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02a8, "PDP Xbox One Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02ab, "PDP Controller for Xbox One", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02ad, "PDP Wired Controller for Xbox One - Stealth Series", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02b3, "Afterglow Prismatic Wired Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x02b8, "Afterglow Prismatic Wired Controller", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0301, "Logic3 Controller", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0346, "Rock Candy Gamepad for Xbox One 2016", 0, XTYPE_XBOXONE },
{ 0x0e6f, 0x0401, "Logic3 Controller", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0413, "Afterglow AX.1 Gamepad for Xbox 360", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0x0501, "PDP Xbox 360 Controller", 0, XTYPE_XBOX360 },
{ 0x0e6f, 0xf900, "PDP Afterglow AX.1", 0, XTYPE_XBOX360 },
{ 0x0e8f, 0x0201, "SmartJoy Frag Xpad/PS2 adaptor", 0, XTYPE_XBOX },
{ 0x0e8f, 0x3008, "Generic xbox control (dealextreme)", 0, XTYPE_XBOX },
{ 0x0f0d, 0x000a, "Hori Co. DOA4 FightStick", 0, XTYPE_XBOX360 },
{ 0x0f0d, 0x000c, "Hori PadEX Turbo", 0, XTYPE_XBOX360 },
{ 0x0f0d, 0x000d, "Hori Fighting Stick EX2", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0f0d, 0x0016, "Hori Real Arcade Pro.EX", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0f0d, 0x001b, "Hori Real Arcade Pro VX", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0f0d, 0x0063, "Hori Real Arcade Pro Hayabusa (USA) Xbox One", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE },
{ 0x0f0d, 0x0067, "HORIPAD ONE", 0, XTYPE_XBOXONE },
{ 0x0f0d, 0x0078, "Hori Real Arcade Pro V Kai Xbox One", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE },
{ 0x0f0d, 0x00c5, "Hori Fighting Commander ONE", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE },
{ 0x0f0d, 0x00dc, "HORIPAD FPS for Nintendo Switch", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x0f30, 0x010b, "Philips Recoil", 0, XTYPE_XBOX },
{ 0x0f30, 0x0202, "Joytech Advanced Controller", 0, XTYPE_XBOX },
{ 0x0f30, 0x8888, "BigBen XBMiniPad Controller", 0, XTYPE_XBOX },
{ 0x102c, 0xff0c, "Joytech Wireless Advanced Controller", 0, XTYPE_XBOX },
{ 0x1038, 0x1430, "SteelSeries Stratus Duo", 0, XTYPE_XBOX360 },
{ 0x1038, 0x1431, "SteelSeries Stratus Duo", 0, XTYPE_XBOX360 },
{ 0x11c9, 0x55f0, "Nacon GC-100XF", 0, XTYPE_XBOX360 },
{ 0x1209, 0x2882, "Ardwiino Controller", 0, XTYPE_XBOX360 },
{ 0x12ab, 0x0004, "Honey Bee Xbox360 dancepad", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x12ab, 0x0301, "PDP AFTERGLOW AX.1", 0, XTYPE_XBOX360 },
{ 0x12ab, 0x0303, "Mortal Kombat Klassic FightStick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x12ab, 0x8809, "Xbox DDR dancepad", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX },
{ 0x1430, 0x4748, "RedOctane Guitar Hero X-plorer", 0, XTYPE_XBOX360 },
{ 0x1430, 0x8888, "TX6500+ Dance Pad (first generation)", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX },
{ 0x1430, 0xf801, "RedOctane Controller", 0, XTYPE_XBOX360 },
{ 0x146b, 0x0601, "BigBen Interactive XBOX 360 Controller", 0, XTYPE_XBOX360 },
{ 0x146b, 0x0604, "Bigben Interactive DAIJA Arcade Stick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1532, 0x0a00, "Razer Atrox Arcade Stick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOXONE },
{ 0x1532, 0x0a03, "Razer Wildcat", 0, XTYPE_XBOXONE },
{ 0x15e4, 0x3f00, "Power A Mini Pro Elite", 0, XTYPE_XBOX360 },
{ 0x15e4, 0x3f0a, "Xbox Airflo wired controller", 0, XTYPE_XBOX360 },
{ 0x15e4, 0x3f10, "Batarang Xbox 360 controller", 0, XTYPE_XBOX360 },
{ 0x162e, 0xbeef, "Joytech Neo-Se Take2", 0, XTYPE_XBOX360 },
{ 0x1689, 0xfd00, "Razer Onza Tournament Edition", 0, XTYPE_XBOX360 },
{ 0x1689, 0xfd01, "Razer Onza Classic Edition", 0, XTYPE_XBOX360 },
{ 0x1689, 0xfe00, "Razer Sabertooth", 0, XTYPE_XBOX360 },
{ 0x1949, 0x041a, "Amazon Game Controller", 0, XTYPE_XBOX360 },
{ 0x1bad, 0x0002, "Harmonix Rock Band Guitar", 0, XTYPE_XBOX360 },
{ 0x1bad, 0x0003, "Harmonix Rock Band Drumkit", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0x0130, "Ion Drum Rocker", MAP_DPAD_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf016, "Mad Catz Xbox 360 Controller", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf018, "Mad Catz Street Fighter IV SE Fighting Stick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf019, "Mad Catz Brawlstick for Xbox 360", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf021, "Mad Cats Ghost Recon FS GamePad", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf023, "MLG Pro Circuit Controller (Xbox)", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf025, "Mad Catz Call Of Duty", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf027, "Mad Catz FPS Pro", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf028, "Street Fighter IV FightPad", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf02e, "Mad Catz Fightpad", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf030, "Mad Catz Xbox 360 MC2 MicroCon Racing Wheel", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf036, "Mad Catz MicroCon GamePad Pro", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf038, "Street Fighter IV FightStick TE", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf039, "Mad Catz MvC2 TE", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf03a, "Mad Catz SFxT Fightstick Pro", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf03d, "Street Fighter IV Arcade Stick TE - Chun Li", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf03e, "Mad Catz MLG FightStick TE", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf03f, "Mad Catz FightStick SoulCaliber", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf042, "Mad Catz FightStick TES+", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf080, "Mad Catz FightStick TE2", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf501, "HoriPad EX2 Turbo", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf502, "Hori Real Arcade Pro.VX SA", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf503, "Hori Fighting Stick VX", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf504, "Hori Real Arcade Pro. EX", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf505, "Hori Fighting Stick EX2B", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xf506, "Hori Real Arcade Pro.EX Premium VLX", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf900, "Harmonix Xbox 360 Controller", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf901, "Gamestop Xbox 360 Controller", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf903, "Tron Xbox 360 controller", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf904, "PDP Versus Fighting Pad", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xf906, "MortalKombat FightStick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x1bad, 0xfa01, "MadCatz GamePad", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xfd00, "Razer Onza TE", 0, XTYPE_XBOX360 },
{ 0x1bad, 0xfd01, "Razer Onza", 0, XTYPE_XBOX360 },
{ 0x20d6, 0x2001, "BDA Xbox Series X Wired Controller", 0, XTYPE_XBOXONE },
{ 0x20d6, 0x2009, "PowerA Enhanced Wired Controller for Xbox Series X|S", 0, XTYPE_XBOXONE },
{ 0x20d6, 0x281f, "PowerA Wired Controller For Xbox 360", 0, XTYPE_XBOX360 },
{ 0x2e24, 0x0652, "Hyperkin Duke X-Box One pad", 0, XTYPE_XBOXONE },
{ 0x24c6, 0x5000, "Razer Atrox Arcade Stick", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x24c6, 0x5300, "PowerA MINI PROEX Controller", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5303, "Xbox Airflo wired controller", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x530a, "Xbox 360 Pro EX Controller", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x531a, "PowerA Pro Ex", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5397, "FUS1ON Tournament Controller", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x541a, "PowerA Xbox One Mini Wired Controller", 0, XTYPE_XBOXONE },
{ 0x24c6, 0x542a, "Xbox ONE spectra", 0, XTYPE_XBOXONE },
{ 0x24c6, 0x543a, "PowerA Xbox One wired controller", 0, XTYPE_XBOXONE },
{ 0x24c6, 0x5500, "Hori XBOX 360 EX 2 with Turbo", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5501, "Hori Real Arcade Pro VX-SA", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5502, "Hori Fighting Stick VX Alt", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x24c6, 0x5503, "Hori Fighting Edge", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x24c6, 0x5506, "Hori SOULCALIBUR V Stick", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5510, "Hori Fighting Commander ONE (Xbox 360/PC Mode)", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x24c6, 0x550d, "Hori GEM Xbox controller", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x550e, "Hori Real Arcade Pro V Kai 360", MAP_TRIGGERS_TO_BUTTONS, XTYPE_XBOX360 },
{ 0x24c6, 0x551a, "PowerA FUSION Pro Controller", 0, XTYPE_XBOXONE },
{ 0x24c6, 0x561a, "PowerA FUSION Controller", 0, XTYPE_XBOXONE },
{ 0x24c6, 0x5b00, "ThrustMaster Ferrari 458 Racing Wheel", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5b02, "Thrustmaster, Inc. GPX Controller", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5b03, "Thrustmaster Ferrari 458 Racing Wheel", 0, XTYPE_XBOX360 },
{ 0x24c6, 0x5d04, "Razer Sabertooth", 0, XTYPE_XBOX360 },
{ 0x24c6, 0xfafe, "Rock Candy Gamepad for Xbox 360", 0, XTYPE_XBOX360 },
{ 0x2563, 0x058d, "OneXPlayer Gamepad", 0, XTYPE_XBOX360 },
{ 0x2dc8, 0x2000, "8BitDo Pro 2 Wired Controller fox Xbox", 0, XTYPE_XBOXONE },
{ 0x2dc8, 0x3106, "8BitDo Pro 2 Wired Controller", 0, XTYPE_XBOX360 },
{ 0x31e3, 0x1100, "Wooting One", 0, XTYPE_XBOX360 },
{ 0x31e3, 0x1200, "Wooting Two", 0, XTYPE_XBOX360 },
{ 0x31e3, 0x1210, "Wooting Lekker", 0, XTYPE_XBOX360 },
{ 0x31e3, 0x1220, "Wooting Two HE", 0, XTYPE_XBOX360 },
{ 0x31e3, 0x1300, "Wooting 60HE (AVR)", 0, XTYPE_XBOX360 },
{ 0x31e3, 0x1310, "Wooting 60HE (ARM)", 0, XTYPE_XBOX360 },
{ 0x3285, 0x0607, "Nacon GC-100", 0, XTYPE_XBOX360 },
{ 0x3537, 0x1004, "GameSir T4 Kaleid", 0, XTYPE_XBOX360 },
{ 0x3767, 0x0101, "Fanatec Speedster 3 Forceshock Wheel", 0, XTYPE_XBOX },
{ 0xffff, 0xffff, "Chinese-made Xbox Controller", 0, XTYPE_XBOX },
{ 0x0000, 0x0000, "Generic X-Box pad", 0, XTYPE_UNKNOWN }
};
/* buttons shared with xbox and xbox360 */
static const signed short xpad_common_btn[] = {
BTN_A, BTN_B, BTN_X, BTN_Y, /* "analog" buttons */
BTN_START, BTN_SELECT, BTN_THUMBL, BTN_THUMBR, /* start/back/sticks */
-1 /* terminating entry */
};
/* original xbox controllers only */
static const signed short xpad_btn[] = {
BTN_C, BTN_Z, /* "analog" buttons */
-1 /* terminating entry */
};
/* used when dpad is mapped to buttons */
static const signed short xpad_btn_pad[] = {
BTN_TRIGGER_HAPPY1, BTN_TRIGGER_HAPPY2, /* d-pad left, right */
BTN_TRIGGER_HAPPY3, BTN_TRIGGER_HAPPY4, /* d-pad up, down */
-1 /* terminating entry */
};
/* used when triggers are mapped to buttons */
static const signed short xpad_btn_triggers[] = {
BTN_TL2, BTN_TR2, /* triggers left/right */
-1
};
static const signed short xpad360_btn[] = { /* buttons for x360 controller */
BTN_TL, BTN_TR, /* Button LB/RB */
BTN_MODE, /* The big X button */
-1
};
static const signed short xpad_abs[] = {
ABS_X, ABS_Y, /* left stick */
ABS_RX, ABS_RY, /* right stick */
-1 /* terminating entry */
};
/* used when dpad is mapped to axes */
static const signed short xpad_abs_pad[] = {
ABS_HAT0X, ABS_HAT0Y, /* d-pad axes */
-1 /* terminating entry */
};
/* used when triggers are mapped to axes */
static const signed short xpad_abs_triggers[] = {
ABS_Z, ABS_RZ, /* triggers left/right */
-1
};
/* used when the controller has extra paddle buttons */
static const signed short xpad_btn_paddles[] = {
BTN_TRIGGER_HAPPY5, BTN_TRIGGER_HAPPY6, /* paddle upper right, lower right */
BTN_TRIGGER_HAPPY7, BTN_TRIGGER_HAPPY8, /* paddle upper left, lower left */
-1 /* terminating entry */
};
/*
* Xbox 360 has a vendor-specific class, so we cannot match it with only
* USB_INTERFACE_INFO (also specifically refused by USB subsystem), so we
* match against vendor id as well. Wired Xbox 360 devices have protocol 1,
* wireless controllers have protocol 129.
*/
#define XPAD_XBOX360_VENDOR_PROTOCOL(vend, pr) \
.match_flags = USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_INT_INFO, \
.idVendor = (vend), \
.bInterfaceClass = USB_CLASS_VENDOR_SPEC, \
.bInterfaceSubClass = 93, \
.bInterfaceProtocol = (pr)
#define XPAD_XBOX360_VENDOR(vend) \
{ XPAD_XBOX360_VENDOR_PROTOCOL((vend), 1) }, \
{ XPAD_XBOX360_VENDOR_PROTOCOL((vend), 129) }
/* The Xbox One controller uses subclass 71 and protocol 208. */
#define XPAD_XBOXONE_VENDOR_PROTOCOL(vend, pr) \
.match_flags = USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_INT_INFO, \
.idVendor = (vend), \
.bInterfaceClass = USB_CLASS_VENDOR_SPEC, \
.bInterfaceSubClass = 71, \
.bInterfaceProtocol = (pr)
#define XPAD_XBOXONE_VENDOR(vend) \
{ XPAD_XBOXONE_VENDOR_PROTOCOL((vend), 208) }
static const struct usb_device_id xpad_table[] = {
{ USB_INTERFACE_INFO('X', 'B', 0) }, /* Xbox USB-IF not-approved class */
XPAD_XBOX360_VENDOR(0x0079), /* GPD Win 2 controller */
XPAD_XBOX360_VENDOR(0x03eb), /* Wooting Keyboards (Legacy) */
XPAD_XBOX360_VENDOR(0x044f), /* Thrustmaster Xbox 360 controllers */
XPAD_XBOX360_VENDOR(0x045e), /* Microsoft Xbox 360 controllers */
XPAD_XBOXONE_VENDOR(0x045e), /* Microsoft Xbox One controllers */
XPAD_XBOX360_VENDOR(0x046d), /* Logitech Xbox 360-style controllers */
XPAD_XBOX360_VENDOR(0x056e), /* Elecom JC-U3613M */
XPAD_XBOX360_VENDOR(0x06a3), /* Saitek P3600 */
XPAD_XBOX360_VENDOR(0x0738), /* Mad Catz Xbox 360 controllers */
{ USB_DEVICE(0x0738, 0x4540) }, /* Mad Catz Beat Pad */
XPAD_XBOXONE_VENDOR(0x0738), /* Mad Catz FightStick TE 2 */
XPAD_XBOX360_VENDOR(0x07ff), /* Mad Catz Gamepad */
XPAD_XBOX360_VENDOR(0x0c12), /* Zeroplus X-Box 360 controllers */
XPAD_XBOX360_VENDOR(0x0e6f), /* 0x0e6f Xbox 360 controllers */
XPAD_XBOXONE_VENDOR(0x0e6f), /* 0x0e6f Xbox One controllers */
XPAD_XBOX360_VENDOR(0x0f0d), /* Hori controllers */
XPAD_XBOXONE_VENDOR(0x0f0d), /* Hori controllers */
XPAD_XBOX360_VENDOR(0x1038), /* SteelSeries controllers */
XPAD_XBOXONE_VENDOR(0x10f5), /* Turtle Beach Controllers */
XPAD_XBOX360_VENDOR(0x11c9), /* Nacon GC100XF */
XPAD_XBOX360_VENDOR(0x1209), /* Ardwiino Controllers */
XPAD_XBOX360_VENDOR(0x12ab), /* Xbox 360 dance pads */
XPAD_XBOX360_VENDOR(0x1430), /* RedOctane Xbox 360 controllers */
XPAD_XBOX360_VENDOR(0x146b), /* Bigben Interactive controllers */
XPAD_XBOX360_VENDOR(0x1532), /* Razer Sabertooth */
XPAD_XBOXONE_VENDOR(0x1532), /* Razer Wildcat */
XPAD_XBOX360_VENDOR(0x15e4), /* Numark Xbox 360 controllers */
XPAD_XBOX360_VENDOR(0x162e), /* Joytech Xbox 360 controllers */
XPAD_XBOX360_VENDOR(0x1689), /* Razer Onza */
XPAD_XBOX360_VENDOR(0x1949), /* Amazon controllers */
XPAD_XBOX360_VENDOR(0x1bad), /* Harmonix Rock Band guitar and drums */
XPAD_XBOX360_VENDOR(0x20d6), /* PowerA controllers */
XPAD_XBOXONE_VENDOR(0x20d6), /* PowerA controllers */
XPAD_XBOX360_VENDOR(0x24c6), /* PowerA controllers */
XPAD_XBOXONE_VENDOR(0x24c6), /* PowerA controllers */
XPAD_XBOX360_VENDOR(0x2563), /* OneXPlayer Gamepad */
XPAD_XBOX360_VENDOR(0x260d), /* Dareu H101 */
XPAD_XBOX360_VENDOR(0x2c22), /* Qanba Controllers */
XPAD_XBOX360_VENDOR(0x2dc8), /* 8BitDo Pro 2 Wired Controller */
XPAD_XBOXONE_VENDOR(0x2dc8), /* 8BitDo Pro 2 Wired Controller for Xbox */
XPAD_XBOXONE_VENDOR(0x2e24), /* Hyperkin Duke Xbox One pad */
XPAD_XBOX360_VENDOR(0x2f24), /* GameSir controllers */
XPAD_XBOX360_VENDOR(0x31e3), /* Wooting Keyboards */
XPAD_XBOX360_VENDOR(0x3285), /* Nacon GC-100 */
XPAD_XBOX360_VENDOR(0x3537), /* GameSir Controllers */
XPAD_XBOXONE_VENDOR(0x3537), /* GameSir Controllers */
{ }
};
MODULE_DEVICE_TABLE(usb, xpad_table);
struct xboxone_init_packet {
u16 idVendor;
u16 idProduct;
const u8 *data;
u8 len;
};
#define XBOXONE_INIT_PKT(_vid, _pid, _data) \
{ \
.idVendor = (_vid), \
.idProduct = (_pid), \
.data = (_data), \
.len = ARRAY_SIZE(_data), \
}
/*
* starting with xbox one, the game input protocol is used
* magic numbers are taken from
* - https://github.com/xpadneo/gip-dissector/blob/main/src/gip-dissector.lua
* - https://github.com/medusalix/xone/blob/master/bus/protocol.c
*/
#define GIP_CMD_ACK 0x01
#define GIP_CMD_IDENTIFY 0x04
#define GIP_CMD_POWER 0x05
#define GIP_CMD_AUTHENTICATE 0x06
#define GIP_CMD_VIRTUAL_KEY 0x07
#define GIP_CMD_RUMBLE 0x09
#define GIP_CMD_LED 0x0a
#define GIP_CMD_FIRMWARE 0x0c
#define GIP_CMD_INPUT 0x20
#define GIP_SEQ0 0x00
#define GIP_OPT_ACK 0x10
#define GIP_OPT_INTERNAL 0x20
/*
* length of the command payload encoded with
* https://en.wikipedia.org/wiki/LEB128
* which is a no-op for N < 128
*/
#define GIP_PL_LEN(N) (N)
/*
* payload specific defines
*/
#define GIP_PWR_ON 0x00
#define GIP_LED_ON 0x01
#define GIP_MOTOR_R BIT(0)
#define GIP_MOTOR_L BIT(1)
#define GIP_MOTOR_RT BIT(2)
#define GIP_MOTOR_LT BIT(3)
#define GIP_MOTOR_ALL (GIP_MOTOR_R | GIP_MOTOR_L | GIP_MOTOR_RT | GIP_MOTOR_LT)
#define GIP_WIRED_INTF_DATA 0
#define GIP_WIRED_INTF_AUDIO 1
/*
* This packet is required for all Xbox One pads with 2015
* or later firmware installed (or present from the factory).
*/
static const u8 xboxone_power_on[] = {
GIP_CMD_POWER, GIP_OPT_INTERNAL, GIP_SEQ0, GIP_PL_LEN(1), GIP_PWR_ON
};
/*
* This packet is required for Xbox One S (0x045e:0x02ea)
* and Xbox One Elite Series 2 (0x045e:0x0b00) pads to
* initialize the controller that was previously used in
* Bluetooth mode.
*/
static const u8 xboxone_s_init[] = {
GIP_CMD_POWER, GIP_OPT_INTERNAL, GIP_SEQ0, 0x0f, 0x06
};
/*
* This packet is required to get additional input data
* from Xbox One Elite Series 2 (0x045e:0x0b00) pads.
* We mostly do this right now to get paddle data
*/
static const u8 extra_input_packet_init[] = {
0x4d, 0x10, 0x01, 0x02, 0x07, 0x00
};
/*
* This packet is required for the Titanfall 2 Xbox One pads
* (0x0e6f:0x0165) to finish initialization and for Hori pads
* (0x0f0d:0x0067) to make the analog sticks work.
*/
static const u8 xboxone_hori_ack_id[] = {
GIP_CMD_ACK, GIP_OPT_INTERNAL, GIP_SEQ0, GIP_PL_LEN(9),
0x00, GIP_CMD_IDENTIFY, GIP_OPT_INTERNAL, 0x3a, 0x00, 0x00, 0x00, 0x80, 0x00
};
/*
* This packet is required for most (all?) of the PDP pads to start
* sending input reports. These pads include: (0x0e6f:0x02ab),
* (0x0e6f:0x02a4), (0x0e6f:0x02a6).
*/
static const u8 xboxone_pdp_led_on[] = {
GIP_CMD_LED, GIP_OPT_INTERNAL, GIP_SEQ0, GIP_PL_LEN(3), 0x00, GIP_LED_ON, 0x14
};
/*
* This packet is required for most (all?) of the PDP pads to start
* sending input reports. These pads include: (0x0e6f:0x02ab),
* (0x0e6f:0x02a4), (0x0e6f:0x02a6).
*/
static const u8 xboxone_pdp_auth[] = {
GIP_CMD_AUTHENTICATE, GIP_OPT_INTERNAL, GIP_SEQ0, GIP_PL_LEN(2), 0x01, 0x00
};
/*
* A specific rumble packet is required for some PowerA pads to start
* sending input reports. One of those pads is (0x24c6:0x543a).
*/
static const u8 xboxone_rumblebegin_init[] = {
GIP_CMD_RUMBLE, 0x00, GIP_SEQ0, GIP_PL_LEN(9),
0x00, GIP_MOTOR_ALL, 0x00, 0x00, 0x1D, 0x1D, 0xFF, 0x00, 0x00
};
/*
* A rumble packet with zero FF intensity will immediately
* terminate the rumbling required to init PowerA pads.
* This should happen fast enough that the motors don't
* spin up to enough speed to actually vibrate the gamepad.
*/
static const u8 xboxone_rumbleend_init[] = {
GIP_CMD_RUMBLE, 0x00, GIP_SEQ0, GIP_PL_LEN(9),
0x00, GIP_MOTOR_ALL, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/*
* This specifies the selection of init packets that a gamepad
* will be sent on init *and* the order in which they will be
* sent. The correct sequence number will be added when the
* packet is going to be sent.
*/
static const struct xboxone_init_packet xboxone_init_packets[] = {
XBOXONE_INIT_PKT(0x0e6f, 0x0165, xboxone_hori_ack_id),
XBOXONE_INIT_PKT(0x0f0d, 0x0067, xboxone_hori_ack_id),
XBOXONE_INIT_PKT(0x0000, 0x0000, xboxone_power_on),
XBOXONE_INIT_PKT(0x045e, 0x02ea, xboxone_s_init),
XBOXONE_INIT_PKT(0x045e, 0x0b00, xboxone_s_init),
XBOXONE_INIT_PKT(0x045e, 0x0b00, extra_input_packet_init),
XBOXONE_INIT_PKT(0x0e6f, 0x0000, xboxone_pdp_led_on),
XBOXONE_INIT_PKT(0x0e6f, 0x0000, xboxone_pdp_auth),
XBOXONE_INIT_PKT(0x24c6, 0x541a, xboxone_rumblebegin_init),
XBOXONE_INIT_PKT(0x24c6, 0x542a, xboxone_rumblebegin_init),
XBOXONE_INIT_PKT(0x24c6, 0x543a, xboxone_rumblebegin_init),
XBOXONE_INIT_PKT(0x24c6, 0x541a, xboxone_rumbleend_init),
XBOXONE_INIT_PKT(0x24c6, 0x542a, xboxone_rumbleend_init),
XBOXONE_INIT_PKT(0x24c6, 0x543a, xboxone_rumbleend_init),
};
struct xpad_output_packet {
u8 data[XPAD_PKT_LEN];
u8 len;
bool pending;
};
#define XPAD_OUT_CMD_IDX 0
#define XPAD_OUT_FF_IDX 1
#define XPAD_OUT_LED_IDX (1 + IS_ENABLED(CONFIG_JOYSTICK_XPAD_FF))
#define XPAD_NUM_OUT_PACKETS (1 + \
IS_ENABLED(CONFIG_JOYSTICK_XPAD_FF) + \
IS_ENABLED(CONFIG_JOYSTICK_XPAD_LEDS))
struct usb_xpad {
struct input_dev *dev; /* input device interface */
struct input_dev __rcu *x360w_dev;
struct usb_device *udev; /* usb device */
struct usb_interface *intf; /* usb interface */
bool pad_present;
bool input_created;
struct urb *irq_in; /* urb for interrupt in report */
unsigned char *idata; /* input data */
dma_addr_t idata_dma;
struct urb *irq_out; /* urb for interrupt out report */
struct usb_anchor irq_out_anchor;
bool irq_out_active; /* we must not use an active URB */
u8 odata_serial; /* serial number for xbox one protocol */
unsigned char *odata; /* output data */
dma_addr_t odata_dma;
spinlock_t odata_lock;
struct xpad_output_packet out_packets[XPAD_NUM_OUT_PACKETS];
int last_out_packet;
int init_seq;
#if defined(CONFIG_JOYSTICK_XPAD_LEDS)
struct xpad_led *led;
#endif
char phys[64]; /* physical device path */
int mapping; /* map d-pad to buttons or to axes */
int xtype; /* type of xbox device */
int packet_type; /* type of the extended packet */
int pad_nr; /* the order x360 pads were attached */
const char *name; /* name of the device */
struct work_struct work; /* init/remove device from callback */
time64_t mode_btn_down_ts;
};
static int xpad_init_input(struct usb_xpad *xpad);
static void xpad_deinit_input(struct usb_xpad *xpad);
static void xpadone_ack_mode_report(struct usb_xpad *xpad, u8 seq_num);
static void xpad360w_poweroff_controller(struct usb_xpad *xpad);
/*
* xpad_process_packet
*
* Completes a request by converting the data into events for the
* input subsystem.
*
* The used report descriptor was taken from ITO Takayuki's website:
* http://euc.jp/periphs/xbox-controller.ja.html
*/
static void xpad_process_packet(struct usb_xpad *xpad, u16 cmd, unsigned char *data)
{
struct input_dev *dev = xpad->dev;
if (!(xpad->mapping & MAP_STICKS_TO_NULL)) {
/* left stick */
input_report_abs(dev, ABS_X,
(__s16) le16_to_cpup((__le16 *)(data + 12)));
input_report_abs(dev, ABS_Y,
~(__s16) le16_to_cpup((__le16 *)(data + 14)));
/* right stick */
input_report_abs(dev, ABS_RX,
(__s16) le16_to_cpup((__le16 *)(data + 16)));
input_report_abs(dev, ABS_RY,
~(__s16) le16_to_cpup((__le16 *)(data + 18)));
}
/* triggers left/right */
if (xpad->mapping & MAP_TRIGGERS_TO_BUTTONS) {
input_report_key(dev, BTN_TL2, data[10]);
input_report_key(dev, BTN_TR2, data[11]);
} else {
input_report_abs(dev, ABS_Z, data[10]);
input_report_abs(dev, ABS_RZ, data[11]);
}
/* digital pad */
if (xpad->mapping & MAP_DPAD_TO_BUTTONS) {
/* dpad as buttons (left, right, up, down) */
input_report_key(dev, BTN_TRIGGER_HAPPY1, data[2] & BIT(2));
input_report_key(dev, BTN_TRIGGER_HAPPY2, data[2] & BIT(3));
input_report_key(dev, BTN_TRIGGER_HAPPY3, data[2] & BIT(0));
input_report_key(dev, BTN_TRIGGER_HAPPY4, data[2] & BIT(1));
} else {
input_report_abs(dev, ABS_HAT0X,
!!(data[2] & 0x08) - !!(data[2] & 0x04));
input_report_abs(dev, ABS_HAT0Y,
!!(data[2] & 0x02) - !!(data[2] & 0x01));
}
/* start/back buttons and stick press left/right */
input_report_key(dev, BTN_START, data[2] & BIT(4));
input_report_key(dev, BTN_SELECT, data[2] & BIT(5));
input_report_key(dev, BTN_THUMBL, data[2] & BIT(6));
input_report_key(dev, BTN_THUMBR, data[2] & BIT(7));
/* "analog" buttons A, B, X, Y */
input_report_key(dev, BTN_A, data[4]);
input_report_key(dev, BTN_B, data[5]);
input_report_key(dev, BTN_X, data[6]);
input_report_key(dev, BTN_Y, data[7]);
/* "analog" buttons black, white */
input_report_key(dev, BTN_C, data[8]);
input_report_key(dev, BTN_Z, data[9]);
input_sync(dev);
}
/*
* xpad360_process_packet
*
* Completes a request by converting the data into events for the
* input subsystem. It is version for xbox 360 controller
*
* The used report descriptor was taken from:
* http://www.free60.org/wiki/Gamepad
*/
static void xpad360_process_packet(struct usb_xpad *xpad, struct input_dev *dev,
u16 cmd, unsigned char *data)
{
/* valid pad data */
if (data[0] != 0x00)
return;
/* digital pad */
if (xpad->mapping & MAP_DPAD_TO_BUTTONS) {
/* dpad as buttons (left, right, up, down) */
input_report_key(dev, BTN_TRIGGER_HAPPY1, data[2] & BIT(2));
input_report_key(dev, BTN_TRIGGER_HAPPY2, data[2] & BIT(3));
input_report_key(dev, BTN_TRIGGER_HAPPY3, data[2] & BIT(0));
input_report_key(dev, BTN_TRIGGER_HAPPY4, data[2] & BIT(1));
}
/*
* This should be a simple else block. However historically
* xbox360w has mapped DPAD to buttons while xbox360 did not. This
* made no sense, but now we can not just switch back and have to
* support both behaviors.
*/
if (!(xpad->mapping & MAP_DPAD_TO_BUTTONS) ||
xpad->xtype == XTYPE_XBOX360W) {
input_report_abs(dev, ABS_HAT0X,
!!(data[2] & 0x08) - !!(data[2] & 0x04));
input_report_abs(dev, ABS_HAT0Y,
!!(data[2] & 0x02) - !!(data[2] & 0x01));
}
/* start/back buttons */
input_report_key(dev, BTN_START, data[2] & BIT(4));
input_report_key(dev, BTN_SELECT, data[2] & BIT(5));
/* stick press left/right */
input_report_key(dev, BTN_THUMBL, data[2] & BIT(6));
input_report_key(dev, BTN_THUMBR, data[2] & BIT(7));
/* buttons A,B,X,Y,TL,TR and MODE */
input_report_key(dev, BTN_A, data[3] & BIT(4));
input_report_key(dev, BTN_B, data[3] & BIT(5));
input_report_key(dev, BTN_X, data[3] & BIT(6));
input_report_key(dev, BTN_Y, data[3] & BIT(7));
input_report_key(dev, BTN_TL, data[3] & BIT(0));
input_report_key(dev, BTN_TR, data[3] & BIT(1));
input_report_key(dev, BTN_MODE, data[3] & BIT(2));
if (!(xpad->mapping & MAP_STICKS_TO_NULL)) {
/* left stick */
input_report_abs(dev, ABS_X,
(__s16) le16_to_cpup((__le16 *)(data + 6)));
input_report_abs(dev, ABS_Y,
~(__s16) le16_to_cpup((__le16 *)(data + 8)));
/* right stick */
input_report_abs(dev, ABS_RX,
(__s16) le16_to_cpup((__le16 *)(data + 10)));
input_report_abs(dev, ABS_RY,
~(__s16) le16_to_cpup((__le16 *)(data + 12)));
}
/* triggers left/right */
if (xpad->mapping & MAP_TRIGGERS_TO_BUTTONS) {
input_report_key(dev, BTN_TL2, data[4]);
input_report_key(dev, BTN_TR2, data[5]);
} else {
input_report_abs(dev, ABS_Z, data[4]);
input_report_abs(dev, ABS_RZ, data[5]);
}
input_sync(dev);
/* XBOX360W controllers can't be turned off without driver assistance */
if (xpad->xtype == XTYPE_XBOX360W) {
if (xpad->mode_btn_down_ts > 0 && xpad->pad_present &&
((ktime_get_seconds() - xpad->mode_btn_down_ts) >=
XPAD360W_POWEROFF_TIMEOUT)) {
xpad360w_poweroff_controller(xpad);
xpad->mode_btn_down_ts = 0;
return;
}
/* mode button down/up */
if (data[3] & BIT(2))
xpad->mode_btn_down_ts = ktime_get_seconds();
else
xpad->mode_btn_down_ts = 0;
}
}
static void xpad_presence_work(struct work_struct *work)
{
struct usb_xpad *xpad = container_of(work, struct usb_xpad, work);
int error;
if (xpad->pad_present) {
error = xpad_init_input(xpad);
if (error) {
/* complain only, not much else we can do here */
dev_err(&xpad->dev->dev,
"unable to init device: %d\n", error);
} else {
rcu_assign_pointer(xpad->x360w_dev, xpad->dev);
}
} else {
RCU_INIT_POINTER(xpad->x360w_dev, NULL);
synchronize_rcu();
/*
* Now that we are sure xpad360w_process_packet is not
* using input device we can get rid of it.
*/
xpad_deinit_input(xpad);
}
}
/*
* xpad360w_process_packet
*
* Completes a request by converting the data into events for the
* input subsystem. It is version for xbox 360 wireless controller.
*
* Byte.Bit
* 00.1 - Status change: The controller or headset has connected/disconnected
* Bits 01.7 and 01.6 are valid
* 01.7 - Controller present
* 01.6 - Headset present
* 01.1 - Pad state (Bytes 4+) valid
*
*/
static void xpad360w_process_packet(struct usb_xpad *xpad, u16 cmd, unsigned char *data)
{
struct input_dev *dev;
bool present;
/* Presence change */
if (data[0] & 0x08) {
present = (data[1] & 0x80) != 0;
if (xpad->pad_present != present) {
xpad->pad_present = present;
schedule_work(&xpad->work);
}
}
/* Valid pad data */
if (data[1] != 0x1)
return;
rcu_read_lock();
dev = rcu_dereference(xpad->x360w_dev);
if (dev)
xpad360_process_packet(xpad, dev, cmd, &data[4]);
rcu_read_unlock();
}
/*
* xpadone_process_packet
*
* Completes a request by converting the data into events for the
* input subsystem. This version is for the Xbox One controller.
*
* The report format was gleaned from
* https://github.com/kylelemons/xbox/blob/master/xbox.go
*/
static void xpadone_process_packet(struct usb_xpad *xpad, u16 cmd, unsigned char *data)
{
struct input_dev *dev = xpad->dev;
bool do_sync = false;
/* the xbox button has its own special report */
if (data[0] == GIP_CMD_VIRTUAL_KEY) {
/*
* The Xbox One S controller requires these reports to be
* acked otherwise it continues sending them forever and
* won't report further mode button events.
*/
if (data[1] == (GIP_OPT_ACK | GIP_OPT_INTERNAL))
xpadone_ack_mode_report(xpad, data[2]);
input_report_key(dev, BTN_MODE, data[4] & GENMASK(1, 0));
input_sync(dev);
do_sync = true;
} else if (data[0] == GIP_CMD_FIRMWARE) {
/* Some packet formats force us to use this separate to poll paddle inputs */
if (xpad->packet_type == PKT_XBE2_FW_5_11) {
/* Mute paddles if controller is in a custom profile slot
* Checked by looking at the active profile slot to
* verify it's the default slot
*/
if (data[19] != 0)
data[18] = 0;
/* Elite Series 2 split packet paddle bits */
input_report_key(dev, BTN_TRIGGER_HAPPY5, data[18] & BIT(0));
input_report_key(dev, BTN_TRIGGER_HAPPY6, data[18] & BIT(1));
input_report_key(dev, BTN_TRIGGER_HAPPY7, data[18] & BIT(2));
input_report_key(dev, BTN_TRIGGER_HAPPY8, data[18] & BIT(3));
do_sync = true;
}
} else if (data[0] == GIP_CMD_INPUT) { /* The main valid packet type for inputs */
/* menu/view buttons */
input_report_key(dev, BTN_START, data[4] & BIT(2));
input_report_key(dev, BTN_SELECT, data[4] & BIT(3));
if (xpad->mapping & MAP_SELECT_BUTTON)
input_report_key(dev, KEY_RECORD, data[22] & BIT(0));
/* buttons A,B,X,Y */
input_report_key(dev, BTN_A, data[4] & BIT(4));
input_report_key(dev, BTN_B, data[4] & BIT(5));
input_report_key(dev, BTN_X, data[4] & BIT(6));
input_report_key(dev, BTN_Y, data[4] & BIT(7));
/* digital pad */
if (xpad->mapping & MAP_DPAD_TO_BUTTONS) {
/* dpad as buttons (left, right, up, down) */
input_report_key(dev, BTN_TRIGGER_HAPPY1, data[5] & BIT(2));
input_report_key(dev, BTN_TRIGGER_HAPPY2, data[5] & BIT(3));
input_report_key(dev, BTN_TRIGGER_HAPPY3, data[5] & BIT(0));
input_report_key(dev, BTN_TRIGGER_HAPPY4, data[5] & BIT(1));
} else {
input_report_abs(dev, ABS_HAT0X,
!!(data[5] & 0x08) - !!(data[5] & 0x04));
input_report_abs(dev, ABS_HAT0Y,
!!(data[5] & 0x02) - !!(data[5] & 0x01));
}
/* TL/TR */
input_report_key(dev, BTN_TL, data[5] & BIT(4));
input_report_key(dev, BTN_TR, data[5] & BIT(5));
/* stick press left/right */
input_report_key(dev, BTN_THUMBL, data[5] & BIT(6));
input_report_key(dev, BTN_THUMBR, data[5] & BIT(7));
if (!(xpad->mapping & MAP_STICKS_TO_NULL)) {
/* left stick */
input_report_abs(dev, ABS_X,
(__s16) le16_to_cpup((__le16 *)(data + 10)));
input_report_abs(dev, ABS_Y,
~(__s16) le16_to_cpup((__le16 *)(data + 12)));
/* right stick */
input_report_abs(dev, ABS_RX,
(__s16) le16_to_cpup((__le16 *)(data + 14)));
input_report_abs(dev, ABS_RY,
~(__s16) le16_to_cpup((__le16 *)(data + 16)));
}
/* triggers left/right */
if (xpad->mapping & MAP_TRIGGERS_TO_BUTTONS) {
input_report_key(dev, BTN_TL2,
(__u16) le16_to_cpup((__le16 *)(data + 6)));
input_report_key(dev, BTN_TR2,
(__u16) le16_to_cpup((__le16 *)(data + 8)));
} else {
input_report_abs(dev, ABS_Z,
(__u16) le16_to_cpup((__le16 *)(data + 6)));
input_report_abs(dev, ABS_RZ,
(__u16) le16_to_cpup((__le16 *)(data + 8)));
}
/* Profile button has a value of 0-3, so it is reported as an axis */
if (xpad->mapping & MAP_PROFILE_BUTTON)
input_report_abs(dev, ABS_PROFILE, data[34]);
/* paddle handling */
/* based on SDL's SDL_hidapi_xboxone.c */
if (xpad->mapping & MAP_PADDLES) {
if (xpad->packet_type == PKT_XBE1) {
/* Mute paddles if controller has a custom mapping applied.
* Checked by comparing the current mapping
* config against the factory mapping config
*/
if (memcmp(&data[4], &data[18], 2) != 0)
data[32] = 0;
/* OG Elite Series Controller paddle bits */
input_report_key(dev, BTN_TRIGGER_HAPPY5, data[32] & BIT(1));
input_report_key(dev, BTN_TRIGGER_HAPPY6, data[32] & BIT(3));
input_report_key(dev, BTN_TRIGGER_HAPPY7, data[32] & BIT(0));
input_report_key(dev, BTN_TRIGGER_HAPPY8, data[32] & BIT(2));
} else if (xpad->packet_type == PKT_XBE2_FW_OLD) {
/* Mute paddles if controller has a custom mapping applied.
* Checked by comparing the current mapping
* config against the factory mapping config
*/
if (data[19] != 0)
data[18] = 0;
/* Elite Series 2 4.x firmware paddle bits */
input_report_key(dev, BTN_TRIGGER_HAPPY5, data[18] & BIT(0));
input_report_key(dev, BTN_TRIGGER_HAPPY6, data[18] & BIT(1));
input_report_key(dev, BTN_TRIGGER_HAPPY7, data[18] & BIT(2));
input_report_key(dev, BTN_TRIGGER_HAPPY8, data[18] & BIT(3));
} else if (xpad->packet_type == PKT_XBE2_FW_5_EARLY) {
/* Mute paddles if controller has a custom mapping applied.
* Checked by comparing the current mapping
* config against the factory mapping config
*/
if (data[23] != 0)
data[22] = 0;
/* Elite Series 2 5.x firmware paddle bits
* (before the packet was split)
*/
input_report_key(dev, BTN_TRIGGER_HAPPY5, data[22] & BIT(0));
input_report_key(dev, BTN_TRIGGER_HAPPY6, data[22] & BIT(1));
input_report_key(dev, BTN_TRIGGER_HAPPY7, data[22] & BIT(2));
input_report_key(dev, BTN_TRIGGER_HAPPY8, data[22] & BIT(3));
}
}
do_sync = true;
}
if (do_sync)
input_sync(dev);
}
static void xpad_irq_in(struct urb *urb)
{
struct usb_xpad *xpad = urb->context;
struct device *dev = &xpad->intf->dev;
int retval, status;
status = urb->status;
switch (status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(dev, "%s - urb shutting down with status: %d\n",
__func__, status);
return;
default:
dev_dbg(dev, "%s - nonzero urb status received: %d\n",
__func__, status);
goto exit;
}
switch (xpad->xtype) {
case XTYPE_XBOX360:
xpad360_process_packet(xpad, xpad->dev, 0, xpad->idata);
break;
case XTYPE_XBOX360W:
xpad360w_process_packet(xpad, 0, xpad->idata);
break;
case XTYPE_XBOXONE:
xpadone_process_packet(xpad, 0, xpad->idata);
break;
default:
xpad_process_packet(xpad, 0, xpad->idata);
}
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
dev_err(dev, "%s - usb_submit_urb failed with result %d\n",
__func__, retval);
}
/* Callers must hold xpad->odata_lock spinlock */
static bool xpad_prepare_next_init_packet(struct usb_xpad *xpad)
{
const struct xboxone_init_packet *init_packet;
if (xpad->xtype != XTYPE_XBOXONE)
return false;
/* Perform initialization sequence for Xbox One pads that require it */
while (xpad->init_seq < ARRAY_SIZE(xboxone_init_packets)) {
init_packet = &xboxone_init_packets[xpad->init_seq++];
if (init_packet->idVendor != 0 &&
init_packet->idVendor != xpad->dev->id.vendor)
continue;
if (init_packet->idProduct != 0 &&
init_packet->idProduct != xpad->dev->id.product)
continue;
/* This packet applies to our device, so prepare to send it */
memcpy(xpad->odata, init_packet->data, init_packet->len);
xpad->irq_out->transfer_buffer_length = init_packet->len;
/* Update packet with current sequence number */
xpad->odata[2] = xpad->odata_serial++;
return true;
}
return false;
}
/* Callers must hold xpad->odata_lock spinlock */
static bool xpad_prepare_next_out_packet(struct usb_xpad *xpad)
{
struct xpad_output_packet *pkt, *packet = NULL;
int i;
/* We may have init packets to send before we can send user commands */
if (xpad_prepare_next_init_packet(xpad))
return true;
for (i = 0; i < XPAD_NUM_OUT_PACKETS; i++) {
if (++xpad->last_out_packet >= XPAD_NUM_OUT_PACKETS)
xpad->last_out_packet = 0;
pkt = &xpad->out_packets[xpad->last_out_packet];
if (pkt->pending) {
dev_dbg(&xpad->intf->dev,
"%s - found pending output packet %d\n",
__func__, xpad->last_out_packet);
packet = pkt;
break;
}
}
if (packet) {
memcpy(xpad->odata, packet->data, packet->len);
xpad->irq_out->transfer_buffer_length = packet->len;
packet->pending = false;
return true;
}
return false;
}
/* Callers must hold xpad->odata_lock spinlock */
static int xpad_try_sending_next_out_packet(struct usb_xpad *xpad)
{
int error;
if (!xpad->irq_out_active && xpad_prepare_next_out_packet(xpad)) {
usb_anchor_urb(xpad->irq_out, &xpad->irq_out_anchor);
error = usb_submit_urb(xpad->irq_out, GFP_ATOMIC);
if (error) {
dev_err(&xpad->intf->dev,
"%s - usb_submit_urb failed with result %d\n",
__func__, error);
usb_unanchor_urb(xpad->irq_out);
return -EIO;
}
xpad->irq_out_active = true;
}
return 0;
}
static void xpad_irq_out(struct urb *urb)
{
struct usb_xpad *xpad = urb->context;
struct device *dev = &xpad->intf->dev;
int status = urb->status;
int error;
unsigned long flags;
spin_lock_irqsave(&xpad->odata_lock, flags);
switch (status) {
case 0:
/* success */
xpad->irq_out_active = xpad_prepare_next_out_packet(xpad);
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(dev, "%s - urb shutting down with status: %d\n",
__func__, status);
xpad->irq_out_active = false;
break;
default:
dev_dbg(dev, "%s - nonzero urb status received: %d\n",
__func__, status);
break;
}
if (xpad->irq_out_active) {
usb_anchor_urb(urb, &xpad->irq_out_anchor);
error = usb_submit_urb(urb, GFP_ATOMIC);
if (error) {
dev_err(dev,
"%s - usb_submit_urb failed with result %d\n",
__func__, error);
usb_unanchor_urb(urb);
xpad->irq_out_active = false;
}
}
spin_unlock_irqrestore(&xpad->odata_lock, flags);
}
static int xpad_init_output(struct usb_interface *intf, struct usb_xpad *xpad,
struct usb_endpoint_descriptor *ep_irq_out)
{
int error;
if (xpad->xtype == XTYPE_UNKNOWN)
return 0;
init_usb_anchor(&xpad->irq_out_anchor);
xpad->odata = usb_alloc_coherent(xpad->udev, XPAD_PKT_LEN,
GFP_KERNEL, &xpad->odata_dma);
if (!xpad->odata)
return -ENOMEM;
spin_lock_init(&xpad->odata_lock);
xpad->irq_out = usb_alloc_urb(0, GFP_KERNEL);
if (!xpad->irq_out) {
error = -ENOMEM;
goto err_free_coherent;
}
usb_fill_int_urb(xpad->irq_out, xpad->udev,
usb_sndintpipe(xpad->udev, ep_irq_out->bEndpointAddress),
xpad->odata, XPAD_PKT_LEN,
xpad_irq_out, xpad, ep_irq_out->bInterval);
xpad->irq_out->transfer_dma = xpad->odata_dma;
xpad->irq_out->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
return 0;
err_free_coherent:
usb_free_coherent(xpad->udev, XPAD_PKT_LEN, xpad->odata, xpad->odata_dma);
return error;
}
static void xpad_stop_output(struct usb_xpad *xpad)
{
if (xpad->xtype != XTYPE_UNKNOWN) {
if (!usb_wait_anchor_empty_timeout(&xpad->irq_out_anchor,
5000)) {
dev_warn(&xpad->intf->dev,
"timed out waiting for output URB to complete, killing\n");
usb_kill_anchored_urbs(&xpad->irq_out_anchor);
}
}
}
static void xpad_deinit_output(struct usb_xpad *xpad)
{
if (xpad->xtype != XTYPE_UNKNOWN) {
usb_free_urb(xpad->irq_out);
usb_free_coherent(xpad->udev, XPAD_PKT_LEN,
xpad->odata, xpad->odata_dma);
}
}
static int xpad_inquiry_pad_presence(struct usb_xpad *xpad)
{
struct xpad_output_packet *packet =
&xpad->out_packets[XPAD_OUT_CMD_IDX];
unsigned long flags;
int retval;
spin_lock_irqsave(&xpad->odata_lock, flags);
packet->data[0] = 0x08;
packet->data[1] = 0x00;
packet->data[2] = 0x0F;
packet->data[3] = 0xC0;
packet->data[4] = 0x00;
packet->data[5] = 0x00;
packet->data[6] = 0x00;
packet->data[7] = 0x00;
packet->data[8] = 0x00;
packet->data[9] = 0x00;
packet->data[10] = 0x00;
packet->data[11] = 0x00;
packet->len = 12;
packet->pending = true;
/* Reset the sequence so we send out presence first */
xpad->last_out_packet = -1;
retval = xpad_try_sending_next_out_packet(xpad);
spin_unlock_irqrestore(&xpad->odata_lock, flags);
return retval;
}
static int xpad_start_xbox_one(struct usb_xpad *xpad)
{
unsigned long flags;
int retval;
if (usb_ifnum_to_if(xpad->udev, GIP_WIRED_INTF_AUDIO)) {
/*
* Explicitly disable the audio interface. This is needed
* for some controllers, such as the PowerA Enhanced Wired
* Controller for Series X|S (0x20d6:0x200e) to report the
* guide button.
*/
retval = usb_set_interface(xpad->udev,
GIP_WIRED_INTF_AUDIO, 0);
if (retval)
dev_warn(&xpad->dev->dev,
"unable to disable audio interface: %d\n",
retval);
}
spin_lock_irqsave(&xpad->odata_lock, flags);
/*
* Begin the init sequence by attempting to send a packet.
* We will cycle through the init packet sequence before
* sending any packets from the output ring.
*/
xpad->init_seq = 0;
retval = xpad_try_sending_next_out_packet(xpad);
spin_unlock_irqrestore(&xpad->odata_lock, flags);
return retval;
}
static void xpadone_ack_mode_report(struct usb_xpad *xpad, u8 seq_num)
{
unsigned long flags;
struct xpad_output_packet *packet =
&xpad->out_packets[XPAD_OUT_CMD_IDX];
static const u8 mode_report_ack[] = {
GIP_CMD_ACK, GIP_OPT_INTERNAL, GIP_SEQ0, GIP_PL_LEN(9),
0x00, GIP_CMD_VIRTUAL_KEY, GIP_OPT_INTERNAL, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00
};
spin_lock_irqsave(&xpad->odata_lock, flags);
packet->len = sizeof(mode_report_ack);
memcpy(packet->data, mode_report_ack, packet->len);
packet->data[2] = seq_num;
packet->pending = true;
/* Reset the sequence so we send out the ack now */
xpad->last_out_packet = -1;
xpad_try_sending_next_out_packet(xpad);
spin_unlock_irqrestore(&xpad->odata_lock, flags);
}
#ifdef CONFIG_JOYSTICK_XPAD_FF
static int xpad_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
{
struct usb_xpad *xpad = input_get_drvdata(dev);
struct xpad_output_packet *packet = &xpad->out_packets[XPAD_OUT_FF_IDX];
__u16 strong;
__u16 weak;
int retval;
unsigned long flags;
if (effect->type != FF_RUMBLE)
return 0;
strong = effect->u.rumble.strong_magnitude;
weak = effect->u.rumble.weak_magnitude;
spin_lock_irqsave(&xpad->odata_lock, flags);
switch (xpad->xtype) {
case XTYPE_XBOX:
packet->data[0] = 0x00;
packet->data[1] = 0x06;
packet->data[2] = 0x00;
packet->data[3] = strong / 256; /* left actuator */
packet->data[4] = 0x00;
packet->data[5] = weak / 256; /* right actuator */
packet->len = 6;
packet->pending = true;
break;
case XTYPE_XBOX360:
packet->data[0] = 0x00;
packet->data[1] = 0x08;
packet->data[2] = 0x00;
packet->data[3] = strong / 256; /* left actuator? */
packet->data[4] = weak / 256; /* right actuator? */
packet->data[5] = 0x00;
packet->data[6] = 0x00;
packet->data[7] = 0x00;
packet->len = 8;
packet->pending = true;
break;
case XTYPE_XBOX360W:
packet->data[0] = 0x00;
packet->data[1] = 0x01;
packet->data[2] = 0x0F;
packet->data[3] = 0xC0;
packet->data[4] = 0x00;
packet->data[5] = strong / 256;
packet->data[6] = weak / 256;
packet->data[7] = 0x00;
packet->data[8] = 0x00;
packet->data[9] = 0x00;
packet->data[10] = 0x00;
packet->data[11] = 0x00;
packet->len = 12;
packet->pending = true;
break;
case XTYPE_XBOXONE:
packet->data[0] = GIP_CMD_RUMBLE; /* activate rumble */
packet->data[1] = 0x00;
packet->data[2] = xpad->odata_serial++;
packet->data[3] = GIP_PL_LEN(9);
packet->data[4] = 0x00;
packet->data[5] = GIP_MOTOR_ALL;
packet->data[6] = 0x00; /* left trigger */
packet->data[7] = 0x00; /* right trigger */
packet->data[8] = strong / 512; /* left actuator */
packet->data[9] = weak / 512; /* right actuator */
packet->data[10] = 0xFF; /* on period */
packet->data[11] = 0x00; /* off period */
packet->data[12] = 0xFF; /* repeat count */
packet->len = 13;
packet->pending = true;
break;
default:
dev_dbg(&xpad->dev->dev,
"%s - rumble command sent to unsupported xpad type: %d\n",
__func__, xpad->xtype);
retval = -EINVAL;
goto out;
}
retval = xpad_try_sending_next_out_packet(xpad);
out:
spin_unlock_irqrestore(&xpad->odata_lock, flags);
return retval;
}
static int xpad_init_ff(struct usb_xpad *xpad)
{
if (xpad->xtype == XTYPE_UNKNOWN)
return 0;
input_set_capability(xpad->dev, EV_FF, FF_RUMBLE);
return input_ff_create_memless(xpad->dev, NULL, xpad_play_effect);
}
#else
static int xpad_init_ff(struct usb_xpad *xpad) { return 0; }
#endif
#if defined(CONFIG_JOYSTICK_XPAD_LEDS)
#include <linux/leds.h>
#include <linux/idr.h>
static DEFINE_IDA(xpad_pad_seq);
struct xpad_led {
char name[16];
struct led_classdev led_cdev;
struct usb_xpad *xpad;
};
/*
* set the LEDs on Xbox 360 / Wireless Controllers
* @param command
* 0: off
* 1: all blink, then previous setting
* 2: 1/top-left blink, then on
* 3: 2/top-right blink, then on
* 4: 3/bottom-left blink, then on
* 5: 4/bottom-right blink, then on
* 6: 1/top-left on
* 7: 2/top-right on
* 8: 3/bottom-left on
* 9: 4/bottom-right on
* 10: rotate
* 11: blink, based on previous setting
* 12: slow blink, based on previous setting
* 13: rotate with two lights
* 14: persistent slow all blink
* 15: blink once, then previous setting
*/
static void xpad_send_led_command(struct usb_xpad *xpad, int command)
{
struct xpad_output_packet *packet =
&xpad->out_packets[XPAD_OUT_LED_IDX];
unsigned long flags;
command %= 16;
spin_lock_irqsave(&xpad->odata_lock, flags);
switch (xpad->xtype) {
case XTYPE_XBOX360:
packet->data[0] = 0x01;
packet->data[1] = 0x03;
packet->data[2] = command;
packet->len = 3;
packet->pending = true;
break;
case XTYPE_XBOX360W:
packet->data[0] = 0x00;
packet->data[1] = 0x00;
packet->data[2] = 0x08;
packet->data[3] = 0x40 + command;
packet->data[4] = 0x00;
packet->data[5] = 0x00;
packet->data[6] = 0x00;
packet->data[7] = 0x00;
packet->data[8] = 0x00;
packet->data[9] = 0x00;
packet->data[10] = 0x00;
packet->data[11] = 0x00;
packet->len = 12;
packet->pending = true;
break;
}
xpad_try_sending_next_out_packet(xpad);
spin_unlock_irqrestore(&xpad->odata_lock, flags);
}
/*
* Light up the segment corresponding to the pad number on
* Xbox 360 Controllers.
*/
static void xpad_identify_controller(struct usb_xpad *xpad)
{
led_set_brightness(&xpad->led->led_cdev, (xpad->pad_nr % 4) + 2);
}
static void xpad_led_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct xpad_led *xpad_led = container_of(led_cdev,
struct xpad_led, led_cdev);
xpad_send_led_command(xpad_led->xpad, value);
}
static int xpad_led_probe(struct usb_xpad *xpad)
{
struct xpad_led *led;
struct led_classdev *led_cdev;
int error;
if (xpad->xtype != XTYPE_XBOX360 && xpad->xtype != XTYPE_XBOX360W)
return 0;
xpad->led = led = kzalloc(sizeof(struct xpad_led), GFP_KERNEL);
if (!led)
return -ENOMEM;
xpad->pad_nr = ida_simple_get(&xpad_pad_seq, 0, 0, GFP_KERNEL);
if (xpad->pad_nr < 0) {
error = xpad->pad_nr;
goto err_free_mem;
}
snprintf(led->name, sizeof(led->name), "xpad%d", xpad->pad_nr);
led->xpad = xpad;
led_cdev = &led->led_cdev;
led_cdev->name = led->name;
led_cdev->brightness_set = xpad_led_set;
led_cdev->flags = LED_CORE_SUSPENDRESUME;
error = led_classdev_register(&xpad->udev->dev, led_cdev);
if (error)
goto err_free_id;
xpad_identify_controller(xpad);
return 0;
err_free_id:
ida_simple_remove(&xpad_pad_seq, xpad->pad_nr);
err_free_mem:
kfree(led);
xpad->led = NULL;
return error;
}
static void xpad_led_disconnect(struct usb_xpad *xpad)
{
struct xpad_led *xpad_led = xpad->led;
if (xpad_led) {
led_classdev_unregister(&xpad_led->led_cdev);
ida_simple_remove(&xpad_pad_seq, xpad->pad_nr);
kfree(xpad_led);
}
}
#else
static int xpad_led_probe(struct usb_xpad *xpad) { return 0; }
static void xpad_led_disconnect(struct usb_xpad *xpad) { }
#endif
static int xpad_start_input(struct usb_xpad *xpad)
{
int error;
if (usb_submit_urb(xpad->irq_in, GFP_KERNEL))
return -EIO;
if (xpad->xtype == XTYPE_XBOXONE) {
error = xpad_start_xbox_one(xpad);
if (error) {
usb_kill_urb(xpad->irq_in);
return error;
}
}
if (xpad->xtype == XTYPE_XBOX360) {
/*
* Some third-party controllers Xbox 360-style controllers
* require this message to finish initialization.
*/
u8 dummy[20];
error = usb_control_msg_recv(xpad->udev, 0,
/* bRequest */ 0x01,
/* bmRequestType */
USB_TYPE_VENDOR | USB_DIR_IN |
USB_RECIP_INTERFACE,
/* wValue */ 0x100,
/* wIndex */ 0x00,
dummy, sizeof(dummy),
25, GFP_KERNEL);
if (error)
dev_warn(&xpad->dev->dev,
"unable to receive magic message: %d\n",
error);
}
return 0;
}
static void xpad_stop_input(struct usb_xpad *xpad)
{
usb_kill_urb(xpad->irq_in);
}
static void xpad360w_poweroff_controller(struct usb_xpad *xpad)
{
unsigned long flags;
struct xpad_output_packet *packet =
&xpad->out_packets[XPAD_OUT_CMD_IDX];
spin_lock_irqsave(&xpad->odata_lock, flags);
packet->data[0] = 0x00;
packet->data[1] = 0x00;
packet->data[2] = 0x08;
packet->data[3] = 0xC0;
packet->data[4] = 0x00;
packet->data[5] = 0x00;
packet->data[6] = 0x00;
packet->data[7] = 0x00;
packet->data[8] = 0x00;
packet->data[9] = 0x00;
packet->data[10] = 0x00;
packet->data[11] = 0x00;
packet->len = 12;
packet->pending = true;
/* Reset the sequence so we send out poweroff now */
xpad->last_out_packet = -1;
xpad_try_sending_next_out_packet(xpad);
spin_unlock_irqrestore(&xpad->odata_lock, flags);
}
static int xpad360w_start_input(struct usb_xpad *xpad)
{
int error;
error = usb_submit_urb(xpad->irq_in, GFP_KERNEL);
if (error)
return -EIO;
/*
* Send presence packet.
* This will force the controller to resend connection packets.
* This is useful in the case we activate the module after the
* adapter has been plugged in, as it won't automatically
* send us info about the controllers.
*/
error = xpad_inquiry_pad_presence(xpad);
if (error) {
usb_kill_urb(xpad->irq_in);
return error;
}
return 0;
}
static void xpad360w_stop_input(struct usb_xpad *xpad)
{
usb_kill_urb(xpad->irq_in);
/* Make sure we are done with presence work if it was scheduled */
flush_work(&xpad->work);
}
static int xpad_open(struct input_dev *dev)
{
struct usb_xpad *xpad = input_get_drvdata(dev);
return xpad_start_input(xpad);
}
static void xpad_close(struct input_dev *dev)
{
struct usb_xpad *xpad = input_get_drvdata(dev);
xpad_stop_input(xpad);
}
static void xpad_set_up_abs(struct input_dev *input_dev, signed short abs)
{
struct usb_xpad *xpad = input_get_drvdata(input_dev);
switch (abs) {
case ABS_X:
case ABS_Y:
case ABS_RX:
case ABS_RY: /* the two sticks */
input_set_abs_params(input_dev, abs, -32768, 32767, 16, 128);
break;
case ABS_Z:
case ABS_RZ: /* the triggers (if mapped to axes) */
if (xpad->xtype == XTYPE_XBOXONE)
input_set_abs_params(input_dev, abs, 0, 1023, 0, 0);
else
input_set_abs_params(input_dev, abs, 0, 255, 0, 0);
break;
case ABS_HAT0X:
case ABS_HAT0Y: /* the d-pad (only if dpad is mapped to axes */
input_set_abs_params(input_dev, abs, -1, 1, 0, 0);
break;
case ABS_PROFILE: /* 4 value profile button (such as on XAC) */
input_set_abs_params(input_dev, abs, 0, 4, 0, 0);
break;
default:
input_set_abs_params(input_dev, abs, 0, 0, 0, 0);
break;
}
}
static void xpad_deinit_input(struct usb_xpad *xpad)
{
if (xpad->input_created) {
xpad->input_created = false;
xpad_led_disconnect(xpad);
input_unregister_device(xpad->dev);
}
}
static int xpad_init_input(struct usb_xpad *xpad)
{
struct input_dev *input_dev;
int i, error;
input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
xpad->dev = input_dev;
input_dev->name = xpad->name;
input_dev->phys = xpad->phys;
usb_to_input_id(xpad->udev, &input_dev->id);
if (xpad->xtype == XTYPE_XBOX360W) {
/* x360w controllers and the receiver have different ids */
input_dev->id.product = 0x02a1;
}
input_dev->dev.parent = &xpad->intf->dev;
input_set_drvdata(input_dev, xpad);
if (xpad->xtype != XTYPE_XBOX360W) {
input_dev->open = xpad_open;
input_dev->close = xpad_close;
}
if (!(xpad->mapping & MAP_STICKS_TO_NULL)) {
/* set up axes */
for (i = 0; xpad_abs[i] >= 0; i++)
xpad_set_up_abs(input_dev, xpad_abs[i]);
}
/* set up standard buttons */
for (i = 0; xpad_common_btn[i] >= 0; i++)
input_set_capability(input_dev, EV_KEY, xpad_common_btn[i]);
/* set up model-specific ones */
if (xpad->xtype == XTYPE_XBOX360 || xpad->xtype == XTYPE_XBOX360W ||
xpad->xtype == XTYPE_XBOXONE) {
for (i = 0; xpad360_btn[i] >= 0; i++)
input_set_capability(input_dev, EV_KEY, xpad360_btn[i]);
if (xpad->mapping & MAP_SELECT_BUTTON)
input_set_capability(input_dev, EV_KEY, KEY_RECORD);
} else {
for (i = 0; xpad_btn[i] >= 0; i++)
input_set_capability(input_dev, EV_KEY, xpad_btn[i]);
}
if (xpad->mapping & MAP_DPAD_TO_BUTTONS) {
for (i = 0; xpad_btn_pad[i] >= 0; i++)
input_set_capability(input_dev, EV_KEY,
xpad_btn_pad[i]);
}
/* set up paddles if the controller has them */
if (xpad->mapping & MAP_PADDLES) {
for (i = 0; xpad_btn_paddles[i] >= 0; i++)
input_set_capability(input_dev, EV_KEY, xpad_btn_paddles[i]);
}
/*
* This should be a simple else block. However historically
* xbox360w has mapped DPAD to buttons while xbox360 did not. This
* made no sense, but now we can not just switch back and have to
* support both behaviors.
*/
if (!(xpad->mapping & MAP_DPAD_TO_BUTTONS) ||
xpad->xtype == XTYPE_XBOX360W) {
for (i = 0; xpad_abs_pad[i] >= 0; i++)
xpad_set_up_abs(input_dev, xpad_abs_pad[i]);
}
if (xpad->mapping & MAP_TRIGGERS_TO_BUTTONS) {
for (i = 0; xpad_btn_triggers[i] >= 0; i++)
input_set_capability(input_dev, EV_KEY,
xpad_btn_triggers[i]);
} else {
for (i = 0; xpad_abs_triggers[i] >= 0; i++)
xpad_set_up_abs(input_dev, xpad_abs_triggers[i]);
}
/* setup profile button as an axis with 4 possible values */
if (xpad->mapping & MAP_PROFILE_BUTTON)
xpad_set_up_abs(input_dev, ABS_PROFILE);
error = xpad_init_ff(xpad);
if (error)
goto err_free_input;
error = xpad_led_probe(xpad);
if (error)
goto err_destroy_ff;
error = input_register_device(xpad->dev);
if (error)
goto err_disconnect_led;
xpad->input_created = true;
return 0;
err_disconnect_led:
xpad_led_disconnect(xpad);
err_destroy_ff:
input_ff_destroy(input_dev);
err_free_input:
input_free_device(input_dev);
return error;
}
static int xpad_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct usb_xpad *xpad;
struct usb_endpoint_descriptor *ep_irq_in, *ep_irq_out;
int i, error;
if (intf->cur_altsetting->desc.bNumEndpoints != 2)
return -ENODEV;
for (i = 0; xpad_device[i].idVendor; i++) {
if ((le16_to_cpu(udev->descriptor.idVendor) == xpad_device[i].idVendor) &&
(le16_to_cpu(udev->descriptor.idProduct) == xpad_device[i].idProduct))
break;
}
xpad = kzalloc(sizeof(struct usb_xpad), GFP_KERNEL);
if (!xpad)
return -ENOMEM;
usb_make_path(udev, xpad->phys, sizeof(xpad->phys));
strlcat(xpad->phys, "/input0", sizeof(xpad->phys));
xpad->idata = usb_alloc_coherent(udev, XPAD_PKT_LEN,
GFP_KERNEL, &xpad->idata_dma);
if (!xpad->idata) {
error = -ENOMEM;
goto err_free_mem;
}
xpad->irq_in = usb_alloc_urb(0, GFP_KERNEL);
if (!xpad->irq_in) {
error = -ENOMEM;
goto err_free_idata;
}
xpad->udev = udev;
xpad->intf = intf;
xpad->mapping = xpad_device[i].mapping;
xpad->xtype = xpad_device[i].xtype;
xpad->name = xpad_device[i].name;
xpad->packet_type = PKT_XB;
INIT_WORK(&xpad->work, xpad_presence_work);
if (xpad->xtype == XTYPE_UNKNOWN) {
if (intf->cur_altsetting->desc.bInterfaceClass == USB_CLASS_VENDOR_SPEC) {
if (intf->cur_altsetting->desc.bInterfaceProtocol == 129)
xpad->xtype = XTYPE_XBOX360W;
else if (intf->cur_altsetting->desc.bInterfaceProtocol == 208)
xpad->xtype = XTYPE_XBOXONE;
else
xpad->xtype = XTYPE_XBOX360;
} else {
xpad->xtype = XTYPE_XBOX;
}
if (dpad_to_buttons)
xpad->mapping |= MAP_DPAD_TO_BUTTONS;
if (triggers_to_buttons)
xpad->mapping |= MAP_TRIGGERS_TO_BUTTONS;
if (sticks_to_null)
xpad->mapping |= MAP_STICKS_TO_NULL;
}
if (xpad->xtype == XTYPE_XBOXONE &&
intf->cur_altsetting->desc.bInterfaceNumber != GIP_WIRED_INTF_DATA) {
/*
* The Xbox One controller lists three interfaces all with the
* same interface class, subclass and protocol. Differentiate by
* interface number.
*/
error = -ENODEV;
goto err_free_in_urb;
}
ep_irq_in = ep_irq_out = NULL;
for (i = 0; i < 2; i++) {
struct usb_endpoint_descriptor *ep =
&intf->cur_altsetting->endpoint[i].desc;
if (usb_endpoint_xfer_int(ep)) {
if (usb_endpoint_dir_in(ep))
ep_irq_in = ep;
else
ep_irq_out = ep;
}
}
if (!ep_irq_in || !ep_irq_out) {
error = -ENODEV;
goto err_free_in_urb;
}
error = xpad_init_output(intf, xpad, ep_irq_out);
if (error)
goto err_free_in_urb;
usb_fill_int_urb(xpad->irq_in, udev,
usb_rcvintpipe(udev, ep_irq_in->bEndpointAddress),
xpad->idata, XPAD_PKT_LEN, xpad_irq_in,
xpad, ep_irq_in->bInterval);
xpad->irq_in->transfer_dma = xpad->idata_dma;
xpad->irq_in->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
usb_set_intfdata(intf, xpad);
/* Packet type detection */
if (le16_to_cpu(udev->descriptor.idVendor) == 0x045e) { /* Microsoft controllers */
if (le16_to_cpu(udev->descriptor.idProduct) == 0x02e3) {
/* The original elite controller always uses the oldest
* type of extended packet
*/
xpad->packet_type = PKT_XBE1;
} else if (le16_to_cpu(udev->descriptor.idProduct) == 0x0b00) {
/* The elite 2 controller has seen multiple packet
* revisions. These are tied to specific firmware
* versions
*/
if (le16_to_cpu(udev->descriptor.bcdDevice) < 0x0500) {
/* This is the format that the Elite 2 used
* prior to the BLE update
*/
xpad->packet_type = PKT_XBE2_FW_OLD;
} else if (le16_to_cpu(udev->descriptor.bcdDevice) <
0x050b) {
/* This is the format that the Elite 2 used
* prior to the update that split the packet
*/
xpad->packet_type = PKT_XBE2_FW_5_EARLY;
} else {
/* The split packet format that was introduced
* in firmware v5.11
*/
xpad->packet_type = PKT_XBE2_FW_5_11;
}
}
}
if (xpad->xtype == XTYPE_XBOX360W) {
/*
* Submit the int URB immediately rather than waiting for open
* because we get status messages from the device whether
* or not any controllers are attached. In fact, it's
* exactly the message that a controller has arrived that
* we're waiting for.
*/
error = xpad360w_start_input(xpad);
if (error)
goto err_deinit_output;
/*
* Wireless controllers require RESET_RESUME to work properly
* after suspend. Ideally this quirk should be in usb core
* quirk list, but we have too many vendors producing these
* controllers and we'd need to maintain 2 identical lists
* here in this driver and in usb core.
*/
udev->quirks |= USB_QUIRK_RESET_RESUME;
} else {
error = xpad_init_input(xpad);
if (error)
goto err_deinit_output;
}
return 0;
err_deinit_output:
xpad_deinit_output(xpad);
err_free_in_urb:
usb_free_urb(xpad->irq_in);
err_free_idata:
usb_free_coherent(udev, XPAD_PKT_LEN, xpad->idata, xpad->idata_dma);
err_free_mem:
kfree(xpad);
return error;
}
static void xpad_disconnect(struct usb_interface *intf)
{
struct usb_xpad *xpad = usb_get_intfdata(intf);
if (xpad->xtype == XTYPE_XBOX360W)
xpad360w_stop_input(xpad);
xpad_deinit_input(xpad);
/*
* Now that both input device and LED device are gone we can
* stop output URB.
*/
xpad_stop_output(xpad);
xpad_deinit_output(xpad);
usb_free_urb(xpad->irq_in);
usb_free_coherent(xpad->udev, XPAD_PKT_LEN,
xpad->idata, xpad->idata_dma);
kfree(xpad);
usb_set_intfdata(intf, NULL);
}
static int xpad_suspend(struct usb_interface *intf, pm_message_t message)
{
struct usb_xpad *xpad = usb_get_intfdata(intf);
struct input_dev *input = xpad->dev;
if (xpad->xtype == XTYPE_XBOX360W) {
/*
* Wireless controllers always listen to input so
* they are notified when controller shows up
* or goes away.
*/
xpad360w_stop_input(xpad);
/*
* The wireless adapter is going off now, so the
* gamepads are going to become disconnected.
* Unless explicitly disabled, power them down
* so they don't just sit there flashing.
*/
if (auto_poweroff && xpad->pad_present)
xpad360w_poweroff_controller(xpad);
} else {
mutex_lock(&input->mutex);
if (input_device_enabled(input))
xpad_stop_input(xpad);
mutex_unlock(&input->mutex);
}
xpad_stop_output(xpad);
return 0;
}
static int xpad_resume(struct usb_interface *intf)
{
struct usb_xpad *xpad = usb_get_intfdata(intf);
struct input_dev *input = xpad->dev;
int retval = 0;
if (xpad->xtype == XTYPE_XBOX360W) {
retval = xpad360w_start_input(xpad);
} else {
mutex_lock(&input->mutex);
if (input_device_enabled(input)) {
retval = xpad_start_input(xpad);
} else if (xpad->xtype == XTYPE_XBOXONE) {
/*
* Even if there are no users, we'll send Xbox One pads
* the startup sequence so they don't sit there and
* blink until somebody opens the input device again.
*/
retval = xpad_start_xbox_one(xpad);
}
mutex_unlock(&input->mutex);
}
return retval;
}
static struct usb_driver xpad_driver = {
.name = "xpad",
.probe = xpad_probe,
.disconnect = xpad_disconnect,
.suspend = xpad_suspend,
.resume = xpad_resume,
.id_table = xpad_table,
};
module_usb_driver(xpad_driver);
MODULE_AUTHOR("Marko Friedemann <[email protected]>");
MODULE_DESCRIPTION("Xbox pad driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/joystick/xpad.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Raspberry Pi Sense HAT joystick driver
* http://raspberrypi.org
*
* Copyright (C) 2015 Raspberry Pi
* Copyright (C) 2021 Charles Mirabile, Mwesigwa Guma, Joel Savitz
*
* Original Author: Serge Schneider
* Revised for upstream Linux by: Charles Mirabile, Mwesigwa Guma, Joel Savitz
*/
#include <linux/module.h>
#include <linux/input.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/property.h>
#define JOYSTICK_SMB_REG 0xf2
struct sensehat_joystick {
struct platform_device *pdev;
struct input_dev *keys_dev;
unsigned long prev_states;
struct regmap *regmap;
};
static const unsigned int keymap[] = {
BTN_DPAD_DOWN, BTN_DPAD_RIGHT, BTN_DPAD_UP, BTN_SELECT, BTN_DPAD_LEFT,
};
static irqreturn_t sensehat_joystick_report(int irq, void *cookie)
{
struct sensehat_joystick *sensehat_joystick = cookie;
unsigned long curr_states, changes;
unsigned int keys;
int error;
int i;
error = regmap_read(sensehat_joystick->regmap, JOYSTICK_SMB_REG, &keys);
if (error < 0) {
dev_err(&sensehat_joystick->pdev->dev,
"Failed to read joystick state: %d", error);
return IRQ_NONE;
}
curr_states = keys;
bitmap_xor(&changes, &curr_states, &sensehat_joystick->prev_states,
ARRAY_SIZE(keymap));
for_each_set_bit(i, &changes, ARRAY_SIZE(keymap))
input_report_key(sensehat_joystick->keys_dev, keymap[i],
curr_states & BIT(i));
input_sync(sensehat_joystick->keys_dev);
sensehat_joystick->prev_states = keys;
return IRQ_HANDLED;
}
static int sensehat_joystick_probe(struct platform_device *pdev)
{
struct sensehat_joystick *sensehat_joystick;
int error, i, irq;
sensehat_joystick = devm_kzalloc(&pdev->dev, sizeof(*sensehat_joystick),
GFP_KERNEL);
if (!sensehat_joystick)
return -ENOMEM;
sensehat_joystick->pdev = pdev;
sensehat_joystick->regmap = dev_get_regmap(pdev->dev.parent, NULL);
if (!sensehat_joystick->regmap) {
dev_err(&pdev->dev, "unable to get sensehat regmap");
return -ENODEV;
}
sensehat_joystick->keys_dev = devm_input_allocate_device(&pdev->dev);
if (!sensehat_joystick->keys_dev) {
dev_err(&pdev->dev, "Could not allocate input device");
return -ENOMEM;
}
sensehat_joystick->keys_dev->name = "Raspberry Pi Sense HAT Joystick";
sensehat_joystick->keys_dev->phys = "sensehat-joystick/input0";
sensehat_joystick->keys_dev->id.bustype = BUS_I2C;
__set_bit(EV_KEY, sensehat_joystick->keys_dev->evbit);
__set_bit(EV_REP, sensehat_joystick->keys_dev->evbit);
for (i = 0; i < ARRAY_SIZE(keymap); i++)
__set_bit(keymap[i], sensehat_joystick->keys_dev->keybit);
error = input_register_device(sensehat_joystick->keys_dev);
if (error) {
dev_err(&pdev->dev, "Could not register input device");
return error;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
error = devm_request_threaded_irq(&pdev->dev, irq,
NULL, sensehat_joystick_report,
IRQF_ONESHOT, "keys",
sensehat_joystick);
if (error) {
dev_err(&pdev->dev, "IRQ request failed");
return error;
}
return 0;
}
static const struct of_device_id sensehat_joystick_device_id[] = {
{ .compatible = "raspberrypi,sensehat-joystick" },
{},
};
MODULE_DEVICE_TABLE(of, sensehat_joystick_device_id);
static struct platform_driver sensehat_joystick_driver = {
.probe = sensehat_joystick_probe,
.driver = {
.name = "sensehat-joystick",
.of_match_table = sensehat_joystick_device_id,
},
};
module_platform_driver(sensehat_joystick_driver);
MODULE_DESCRIPTION("Raspberry Pi Sense HAT joystick driver");
MODULE_AUTHOR("Charles Mirabile <[email protected]>");
MODULE_AUTHOR("Serge Schneider <[email protected]>");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/joystick/sensehat-joystick.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2010, 2011 Fabien Marteau <[email protected]>
* Sponsored by ARMadeus Systems
*
* Driver for Austria Microsystems joysticks AS5011
*
* TODO:
* - Power on the chip when open() and power down when close()
* - Manage power mode
*/
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/input/as5011.h>
#include <linux/slab.h>
#include <linux/module.h>
#define DRIVER_DESC "Driver for Austria Microsystems AS5011 joystick"
#define MODULE_DEVICE_ALIAS "as5011"
MODULE_AUTHOR("Fabien Marteau <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/* registers */
#define AS5011_CTRL1 0x76
#define AS5011_CTRL2 0x75
#define AS5011_XP 0x43
#define AS5011_XN 0x44
#define AS5011_YP 0x53
#define AS5011_YN 0x54
#define AS5011_X_REG 0x41
#define AS5011_Y_REG 0x42
#define AS5011_X_RES_INT 0x51
#define AS5011_Y_RES_INT 0x52
/* CTRL1 bits */
#define AS5011_CTRL1_LP_PULSED 0x80
#define AS5011_CTRL1_LP_ACTIVE 0x40
#define AS5011_CTRL1_LP_CONTINUE 0x20
#define AS5011_CTRL1_INT_WUP_EN 0x10
#define AS5011_CTRL1_INT_ACT_EN 0x08
#define AS5011_CTRL1_EXT_CLK_EN 0x04
#define AS5011_CTRL1_SOFT_RST 0x02
#define AS5011_CTRL1_DATA_VALID 0x01
/* CTRL2 bits */
#define AS5011_CTRL2_EXT_SAMPLE_EN 0x08
#define AS5011_CTRL2_RC_BIAS_ON 0x04
#define AS5011_CTRL2_INV_SPINNING 0x02
#define AS5011_MAX_AXIS 80
#define AS5011_MIN_AXIS (-80)
#define AS5011_FUZZ 8
#define AS5011_FLAT 40
struct as5011_device {
struct input_dev *input_dev;
struct i2c_client *i2c_client;
unsigned int button_gpio;
unsigned int button_irq;
unsigned int axis_irq;
};
static int as5011_i2c_write(struct i2c_client *client,
uint8_t aregaddr,
uint8_t avalue)
{
uint8_t data[2] = { aregaddr, avalue };
struct i2c_msg msg = {
.addr = client->addr,
.flags = I2C_M_IGNORE_NAK,
.len = 2,
.buf = (uint8_t *)data
};
int error;
error = i2c_transfer(client->adapter, &msg, 1);
return error < 0 ? error : 0;
}
static int as5011_i2c_read(struct i2c_client *client,
uint8_t aregaddr, signed char *value)
{
uint8_t data[2] = { aregaddr };
struct i2c_msg msg_set[2] = {
{
.addr = client->addr,
.flags = I2C_M_REV_DIR_ADDR,
.len = 1,
.buf = (uint8_t *)data
},
{
.addr = client->addr,
.flags = I2C_M_RD | I2C_M_NOSTART,
.len = 1,
.buf = (uint8_t *)data
}
};
int error;
error = i2c_transfer(client->adapter, msg_set, 2);
if (error < 0)
return error;
*value = data[0] & 0x80 ? -1 * (1 + ~data[0]) : data[0];
return 0;
}
static irqreturn_t as5011_button_interrupt(int irq, void *dev_id)
{
struct as5011_device *as5011 = dev_id;
int val = gpio_get_value_cansleep(as5011->button_gpio);
input_report_key(as5011->input_dev, BTN_JOYSTICK, !val);
input_sync(as5011->input_dev);
return IRQ_HANDLED;
}
static irqreturn_t as5011_axis_interrupt(int irq, void *dev_id)
{
struct as5011_device *as5011 = dev_id;
int error;
signed char x, y;
error = as5011_i2c_read(as5011->i2c_client, AS5011_X_RES_INT, &x);
if (error < 0)
goto out;
error = as5011_i2c_read(as5011->i2c_client, AS5011_Y_RES_INT, &y);
if (error < 0)
goto out;
input_report_abs(as5011->input_dev, ABS_X, x);
input_report_abs(as5011->input_dev, ABS_Y, y);
input_sync(as5011->input_dev);
out:
return IRQ_HANDLED;
}
static int as5011_configure_chip(struct as5011_device *as5011,
const struct as5011_platform_data *plat_dat)
{
struct i2c_client *client = as5011->i2c_client;
int error;
signed char value;
/* chip soft reset */
error = as5011_i2c_write(client, AS5011_CTRL1,
AS5011_CTRL1_SOFT_RST);
if (error < 0) {
dev_err(&client->dev, "Soft reset failed\n");
return error;
}
mdelay(10);
error = as5011_i2c_write(client, AS5011_CTRL1,
AS5011_CTRL1_LP_PULSED |
AS5011_CTRL1_LP_ACTIVE |
AS5011_CTRL1_INT_ACT_EN);
if (error < 0) {
dev_err(&client->dev, "Power config failed\n");
return error;
}
error = as5011_i2c_write(client, AS5011_CTRL2,
AS5011_CTRL2_INV_SPINNING);
if (error < 0) {
dev_err(&client->dev, "Can't invert spinning\n");
return error;
}
/* write threshold */
error = as5011_i2c_write(client, AS5011_XP, plat_dat->xp);
if (error < 0) {
dev_err(&client->dev, "Can't write threshold\n");
return error;
}
error = as5011_i2c_write(client, AS5011_XN, plat_dat->xn);
if (error < 0) {
dev_err(&client->dev, "Can't write threshold\n");
return error;
}
error = as5011_i2c_write(client, AS5011_YP, plat_dat->yp);
if (error < 0) {
dev_err(&client->dev, "Can't write threshold\n");
return error;
}
error = as5011_i2c_write(client, AS5011_YN, plat_dat->yn);
if (error < 0) {
dev_err(&client->dev, "Can't write threshold\n");
return error;
}
/* to free irq gpio in chip */
error = as5011_i2c_read(client, AS5011_X_RES_INT, &value);
if (error < 0) {
dev_err(&client->dev, "Can't read i2c X resolution value\n");
return error;
}
return 0;
}
static int as5011_probe(struct i2c_client *client)
{
const struct as5011_platform_data *plat_data;
struct as5011_device *as5011;
struct input_dev *input_dev;
int irq;
int error;
plat_data = dev_get_platdata(&client->dev);
if (!plat_data)
return -EINVAL;
if (!plat_data->axis_irq) {
dev_err(&client->dev, "No axis IRQ?\n");
return -EINVAL;
}
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_NOSTART |
I2C_FUNC_PROTOCOL_MANGLING)) {
dev_err(&client->dev,
"need i2c bus that supports protocol mangling\n");
return -ENODEV;
}
as5011 = kmalloc(sizeof(struct as5011_device), GFP_KERNEL);
input_dev = input_allocate_device();
if (!as5011 || !input_dev) {
dev_err(&client->dev,
"Can't allocate memory for device structure\n");
error = -ENOMEM;
goto err_free_mem;
}
as5011->i2c_client = client;
as5011->input_dev = input_dev;
as5011->button_gpio = plat_data->button_gpio;
as5011->axis_irq = plat_data->axis_irq;
input_dev->name = "Austria Microsystem as5011 joystick";
input_dev->id.bustype = BUS_I2C;
input_dev->dev.parent = &client->dev;
input_set_capability(input_dev, EV_KEY, BTN_JOYSTICK);
input_set_abs_params(input_dev, ABS_X,
AS5011_MIN_AXIS, AS5011_MAX_AXIS, AS5011_FUZZ, AS5011_FLAT);
input_set_abs_params(as5011->input_dev, ABS_Y,
AS5011_MIN_AXIS, AS5011_MAX_AXIS, AS5011_FUZZ, AS5011_FLAT);
error = gpio_request(as5011->button_gpio, "AS5011 button");
if (error < 0) {
dev_err(&client->dev, "Failed to request button gpio\n");
goto err_free_mem;
}
irq = gpio_to_irq(as5011->button_gpio);
if (irq < 0) {
dev_err(&client->dev,
"Failed to get irq number for button gpio\n");
error = irq;
goto err_free_button_gpio;
}
as5011->button_irq = irq;
error = request_threaded_irq(as5011->button_irq,
NULL, as5011_button_interrupt,
IRQF_TRIGGER_RISING |
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
"as5011_button", as5011);
if (error < 0) {
dev_err(&client->dev,
"Can't allocate button irq %d\n", as5011->button_irq);
goto err_free_button_gpio;
}
error = as5011_configure_chip(as5011, plat_data);
if (error)
goto err_free_button_irq;
error = request_threaded_irq(as5011->axis_irq, NULL,
as5011_axis_interrupt,
plat_data->axis_irqflags | IRQF_ONESHOT,
"as5011_joystick", as5011);
if (error) {
dev_err(&client->dev,
"Can't allocate axis irq %d\n", plat_data->axis_irq);
goto err_free_button_irq;
}
error = input_register_device(as5011->input_dev);
if (error) {
dev_err(&client->dev, "Failed to register input device\n");
goto err_free_axis_irq;
}
i2c_set_clientdata(client, as5011);
return 0;
err_free_axis_irq:
free_irq(as5011->axis_irq, as5011);
err_free_button_irq:
free_irq(as5011->button_irq, as5011);
err_free_button_gpio:
gpio_free(as5011->button_gpio);
err_free_mem:
input_free_device(input_dev);
kfree(as5011);
return error;
}
static void as5011_remove(struct i2c_client *client)
{
struct as5011_device *as5011 = i2c_get_clientdata(client);
free_irq(as5011->axis_irq, as5011);
free_irq(as5011->button_irq, as5011);
gpio_free(as5011->button_gpio);
input_unregister_device(as5011->input_dev);
kfree(as5011);
}
static const struct i2c_device_id as5011_id[] = {
{ MODULE_DEVICE_ALIAS, 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, as5011_id);
static struct i2c_driver as5011_driver = {
.driver = {
.name = "as5011",
},
.probe = as5011_probe,
.remove = as5011_remove,
.id_table = as5011_id,
};
module_i2c_driver(as5011_driver);
|
linux-master
|
drivers/input/joystick/as5011.c
|
// SPDX-License-Identifier: GPL-2.0
/*
* FS-iA6B iBus RC receiver driver
*
* This driver provides all 14 channels of the FlySky FS-ia6B RC receiver
* as analog values.
*
* Additionally, the channels can be converted to discrete switch values.
* By default, it is configured for the offical FS-i6 remote control.
* If you use a different hardware configuration, you can configure it
* using the `switch_config` parameter.
*/
#include <linux/device.h>
#include <linux/input.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/serio.h>
#include <linux/slab.h>
#include <linux/types.h>
#define DRIVER_DESC "FS-iA6B iBus RC receiver"
MODULE_AUTHOR("Markus Koch <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define IBUS_SERVO_COUNT 14
static char *switch_config = "00000022320000";
module_param(switch_config, charp, 0444);
MODULE_PARM_DESC(switch_config,
"Amount of switch positions per channel (14 characters, 0-3)");
static int fsia6b_axes[IBUS_SERVO_COUNT] = {
ABS_X, ABS_Y,
ABS_Z, ABS_RX,
ABS_RY, ABS_RZ,
ABS_HAT0X, ABS_HAT0Y,
ABS_HAT1X, ABS_HAT1Y,
ABS_HAT2X, ABS_HAT2Y,
ABS_HAT3X, ABS_HAT3Y
};
enum ibus_state { SYNC, COLLECT, PROCESS };
struct ibus_packet {
enum ibus_state state;
int offset;
u16 ibuf;
u16 channel[IBUS_SERVO_COUNT];
};
struct fsia6b {
struct input_dev *dev;
struct ibus_packet packet;
char phys[32];
};
static irqreturn_t fsia6b_serio_irq(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct fsia6b *fsia6b = serio_get_drvdata(serio);
int i;
int sw_state;
int sw_id = BTN_0;
fsia6b->packet.ibuf = (data << 8) | ((fsia6b->packet.ibuf >> 8) & 0xFF);
switch (fsia6b->packet.state) {
case SYNC:
if (fsia6b->packet.ibuf == 0x4020)
fsia6b->packet.state = COLLECT;
break;
case COLLECT:
fsia6b->packet.state = PROCESS;
break;
case PROCESS:
fsia6b->packet.channel[fsia6b->packet.offset] =
fsia6b->packet.ibuf;
fsia6b->packet.offset++;
if (fsia6b->packet.offset == IBUS_SERVO_COUNT) {
fsia6b->packet.offset = 0;
fsia6b->packet.state = SYNC;
for (i = 0; i < IBUS_SERVO_COUNT; ++i) {
input_report_abs(fsia6b->dev, fsia6b_axes[i],
fsia6b->packet.channel[i]);
sw_state = 0;
if (fsia6b->packet.channel[i] > 1900)
sw_state = 1;
else if (fsia6b->packet.channel[i] < 1100)
sw_state = 2;
switch (switch_config[i]) {
case '3':
input_report_key(fsia6b->dev,
sw_id++,
sw_state == 0);
fallthrough;
case '2':
input_report_key(fsia6b->dev,
sw_id++,
sw_state == 1);
fallthrough;
case '1':
input_report_key(fsia6b->dev,
sw_id++,
sw_state == 2);
}
}
input_sync(fsia6b->dev);
} else {
fsia6b->packet.state = COLLECT;
}
break;
}
return IRQ_HANDLED;
}
static int fsia6b_serio_connect(struct serio *serio, struct serio_driver *drv)
{
struct fsia6b *fsia6b;
struct input_dev *input_dev;
int err;
int i, j;
int sw_id = 0;
fsia6b = kzalloc(sizeof(*fsia6b), GFP_KERNEL);
if (!fsia6b)
return -ENOMEM;
fsia6b->packet.ibuf = 0;
fsia6b->packet.offset = 0;
fsia6b->packet.state = SYNC;
serio_set_drvdata(serio, fsia6b);
input_dev = input_allocate_device();
if (!input_dev) {
err = -ENOMEM;
goto fail1;
}
fsia6b->dev = input_dev;
snprintf(fsia6b->phys, sizeof(fsia6b->phys), "%s/input0", serio->phys);
input_dev->name = DRIVER_DESC;
input_dev->phys = fsia6b->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_FSIA6B;
input_dev->id.product = serio->id.id;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
for (i = 0; i < IBUS_SERVO_COUNT; i++)
input_set_abs_params(input_dev, fsia6b_axes[i],
1000, 2000, 2, 2);
/* Register switch configuration */
for (i = 0; i < IBUS_SERVO_COUNT; i++) {
if (switch_config[i] < '0' || switch_config[i] > '3') {
dev_err(&fsia6b->dev->dev,
"Invalid switch configuration supplied for fsia6b.\n");
err = -EINVAL;
goto fail2;
}
for (j = '1'; j <= switch_config[i]; j++) {
input_set_capability(input_dev, EV_KEY, BTN_0 + sw_id);
sw_id++;
}
}
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(fsia6b->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: input_free_device(input_dev);
fail1: serio_set_drvdata(serio, NULL);
kfree(fsia6b);
return err;
}
static void fsia6b_serio_disconnect(struct serio *serio)
{
struct fsia6b *fsia6b = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(fsia6b->dev);
kfree(fsia6b);
}
static const struct serio_device_id fsia6b_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_FSIA6B,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, fsia6b_serio_ids);
static struct serio_driver fsia6b_serio_drv = {
.driver = {
.name = "fsia6b"
},
.description = DRIVER_DESC,
.id_table = fsia6b_serio_ids,
.interrupt = fsia6b_serio_irq,
.connect = fsia6b_serio_connect,
.disconnect = fsia6b_serio_disconnect
};
module_serio_driver(fsia6b_serio_drv)
|
linux-master
|
drivers/input/joystick/fsia6b.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1996-2001 Vojtech Pavlik
*/
/*
* Analog joystick and gamepad driver for Linux
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/gameport.h>
#include <linux/jiffies.h>
#include <linux/seq_buf.h>
#include <linux/timex.h>
#include <linux/timekeeping.h>
#define DRIVER_DESC "Analog joystick and gamepad driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Option parsing.
*/
#define ANALOG_PORTS 16
static char *js[ANALOG_PORTS];
static unsigned int js_nargs;
static int analog_options[ANALOG_PORTS];
module_param_array_named(map, js, charp, &js_nargs, 0);
MODULE_PARM_DESC(map, "Describes analog joysticks type/capabilities");
/*
* Times, feature definitions.
*/
#define ANALOG_RUDDER 0x00004
#define ANALOG_THROTTLE 0x00008
#define ANALOG_AXES_STD 0x0000f
#define ANALOG_BTNS_STD 0x000f0
#define ANALOG_BTNS_CHF 0x00100
#define ANALOG_HAT1_CHF 0x00200
#define ANALOG_HAT2_CHF 0x00400
#define ANALOG_HAT_FCS 0x00800
#define ANALOG_HATS_ALL 0x00e00
#define ANALOG_BTN_TL 0x01000
#define ANALOG_BTN_TR 0x02000
#define ANALOG_BTN_TL2 0x04000
#define ANALOG_BTN_TR2 0x08000
#define ANALOG_BTNS_TLR 0x03000
#define ANALOG_BTNS_TLR2 0x0c000
#define ANALOG_BTNS_GAMEPAD 0x0f000
#define ANALOG_HBTN_CHF 0x10000
#define ANALOG_ANY_CHF 0x10700
#define ANALOG_SAITEK 0x20000
#define ANALOG_EXTENSIONS 0x7ff00
#define ANALOG_GAMEPAD 0x80000
#define ANALOG_MAX_TIME 3 /* 3 ms */
#define ANALOG_LOOP_TIME 2000 /* 2 * loop */
#define ANALOG_SAITEK_DELAY 200 /* 200 us */
#define ANALOG_SAITEK_TIME 2000 /* 2000 us */
#define ANALOG_AXIS_TIME 2 /* 2 * refresh */
#define ANALOG_INIT_RETRIES 8 /* 8 times */
#define ANALOG_FUZZ_BITS 2 /* 2 bit more */
#define ANALOG_FUZZ_MAGIC 36 /* 36 u*ms/loop */
#define ANALOG_MAX_NAME_LENGTH 128
#define ANALOG_MAX_PHYS_LENGTH 32
static short analog_axes[] = { ABS_X, ABS_Y, ABS_RUDDER, ABS_THROTTLE };
static short analog_hats[] = { ABS_HAT0X, ABS_HAT0Y, ABS_HAT1X, ABS_HAT1Y, ABS_HAT2X, ABS_HAT2Y };
static short analog_pads[] = { BTN_Y, BTN_Z, BTN_TL, BTN_TR };
static short analog_exts[] = { ANALOG_HAT1_CHF, ANALOG_HAT2_CHF, ANALOG_HAT_FCS };
static short analog_pad_btn[] = { BTN_A, BTN_B, BTN_C, BTN_X, BTN_TL2, BTN_TR2, BTN_SELECT, BTN_START, BTN_MODE, BTN_BASE };
static short analog_joy_btn[] = { BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2,
BTN_BASE3, BTN_BASE4, BTN_BASE5, BTN_BASE6 };
static unsigned char analog_chf[] = { 0xf, 0x0, 0x1, 0x9, 0x2, 0x4, 0xc, 0x8, 0x3, 0x5, 0xb, 0x7, 0xd, 0xe, 0xa, 0x6 };
struct analog {
struct input_dev *dev;
int mask;
short *buttons;
char name[ANALOG_MAX_NAME_LENGTH];
char phys[ANALOG_MAX_PHYS_LENGTH];
};
struct analog_port {
struct gameport *gameport;
struct analog analog[2];
unsigned char mask;
char saitek;
char cooked;
int bads;
int reads;
int loop;
int fuzz;
int axes[4];
int buttons;
int initial[4];
int axtime;
};
/*
* analog_decode() decodes analog joystick data and reports input events.
*/
static void analog_decode(struct analog *analog, int *axes, int *initial, int buttons)
{
struct input_dev *dev = analog->dev;
int i, j;
if (analog->mask & ANALOG_HAT_FCS)
for (i = 0; i < 4; i++)
if (axes[3] < ((initial[3] * ((i << 1) + 1)) >> 3)) {
buttons |= 1 << (i + 14);
break;
}
for (i = j = 0; i < 6; i++)
if (analog->mask & (0x10 << i))
input_report_key(dev, analog->buttons[j++], (buttons >> i) & 1);
if (analog->mask & ANALOG_HBTN_CHF)
for (i = 0; i < 4; i++)
input_report_key(dev, analog->buttons[j++], (buttons >> (i + 10)) & 1);
if (analog->mask & ANALOG_BTN_TL)
input_report_key(dev, analog_pads[0], axes[2] < (initial[2] >> 1));
if (analog->mask & ANALOG_BTN_TR)
input_report_key(dev, analog_pads[1], axes[3] < (initial[3] >> 1));
if (analog->mask & ANALOG_BTN_TL2)
input_report_key(dev, analog_pads[2], axes[2] > (initial[2] + (initial[2] >> 1)));
if (analog->mask & ANALOG_BTN_TR2)
input_report_key(dev, analog_pads[3], axes[3] > (initial[3] + (initial[3] >> 1)));
for (i = j = 0; i < 4; i++)
if (analog->mask & (1 << i))
input_report_abs(dev, analog_axes[j++], axes[i]);
for (i = j = 0; i < 3; i++)
if (analog->mask & analog_exts[i]) {
input_report_abs(dev, analog_hats[j++],
((buttons >> ((i << 2) + 7)) & 1) - ((buttons >> ((i << 2) + 9)) & 1));
input_report_abs(dev, analog_hats[j++],
((buttons >> ((i << 2) + 8)) & 1) - ((buttons >> ((i << 2) + 6)) & 1));
}
input_sync(dev);
}
/*
* analog_cooked_read() reads analog joystick data.
*/
static int analog_cooked_read(struct analog_port *port)
{
struct gameport *gameport = port->gameport;
ktime_t time[4], start, loop, now;
unsigned int loopout, timeout;
unsigned char data[4], this, last;
unsigned long flags;
int i, j;
loopout = (ANALOG_LOOP_TIME * port->loop) / 1000;
timeout = ANALOG_MAX_TIME * NSEC_PER_MSEC;
local_irq_save(flags);
gameport_trigger(gameport);
now = ktime_get();
local_irq_restore(flags);
start = now;
this = port->mask;
i = 0;
do {
loop = now;
last = this;
local_irq_disable();
this = gameport_read(gameport) & port->mask;
now = ktime_get();
local_irq_restore(flags);
if ((last ^ this) && (ktime_sub(now, loop) < loopout)) {
data[i] = last ^ this;
time[i] = now;
i++;
}
} while (this && (i < 4) && (ktime_sub(now, start) < timeout));
this <<= 4;
for (--i; i >= 0; i--) {
this |= data[i];
for (j = 0; j < 4; j++)
if (data[i] & (1 << j))
port->axes[j] = ((u32)ktime_sub(time[i], start) << ANALOG_FUZZ_BITS) / port->loop;
}
return -(this != port->mask);
}
static int analog_button_read(struct analog_port *port, char saitek, char chf)
{
unsigned char u;
int t = 1, i = 0;
int strobe = gameport_time(port->gameport, ANALOG_SAITEK_TIME);
u = gameport_read(port->gameport);
if (!chf) {
port->buttons = (~u >> 4) & 0xf;
return 0;
}
port->buttons = 0;
while ((~u & 0xf0) && (i < 16) && t) {
port->buttons |= 1 << analog_chf[(~u >> 4) & 0xf];
if (!saitek) return 0;
udelay(ANALOG_SAITEK_DELAY);
t = strobe;
gameport_trigger(port->gameport);
while (((u = gameport_read(port->gameport)) & port->mask) && t) t--;
i++;
}
return -(!t || (i == 16));
}
/*
* analog_poll() repeatedly polls the Analog joysticks.
*/
static void analog_poll(struct gameport *gameport)
{
struct analog_port *port = gameport_get_drvdata(gameport);
int i;
char saitek = !!(port->analog[0].mask & ANALOG_SAITEK);
char chf = !!(port->analog[0].mask & ANALOG_ANY_CHF);
if (port->cooked) {
port->bads -= gameport_cooked_read(port->gameport, port->axes, &port->buttons);
if (chf)
port->buttons = port->buttons ? (1 << analog_chf[port->buttons]) : 0;
port->reads++;
} else {
if (!port->axtime--) {
port->bads -= analog_cooked_read(port);
port->bads -= analog_button_read(port, saitek, chf);
port->reads++;
port->axtime = ANALOG_AXIS_TIME - 1;
} else {
if (!saitek)
analog_button_read(port, saitek, chf);
}
}
for (i = 0; i < 2; i++)
if (port->analog[i].mask)
analog_decode(port->analog + i, port->axes, port->initial, port->buttons);
}
/*
* analog_open() is a callback from the input open routine.
*/
static int analog_open(struct input_dev *dev)
{
struct analog_port *port = input_get_drvdata(dev);
gameport_start_polling(port->gameport);
return 0;
}
/*
* analog_close() is a callback from the input close routine.
*/
static void analog_close(struct input_dev *dev)
{
struct analog_port *port = input_get_drvdata(dev);
gameport_stop_polling(port->gameport);
}
/*
* analog_calibrate_timer() calibrates the timer and computes loop
* and timeout values for a joystick port.
*/
static void analog_calibrate_timer(struct analog_port *port)
{
struct gameport *gameport = port->gameport;
unsigned int i, t, tx;
ktime_t t1, t2, t3;
unsigned long flags;
tx = ~0;
for (i = 0; i < 50; i++) {
local_irq_save(flags);
t1 = ktime_get();
for (t = 0; t < 50; t++) {
gameport_read(gameport);
t2 = ktime_get();
}
t3 = ktime_get();
local_irq_restore(flags);
udelay(i);
t = ktime_sub(t2, t1) - ktime_sub(t3, t2);
if (t < tx) tx = t;
}
port->loop = tx / 50;
}
/*
* analog_name() constructs a name for an analog joystick.
*/
static void analog_name(struct analog *analog)
{
struct seq_buf s;
seq_buf_init(&s, analog->name, sizeof(analog->name));
seq_buf_printf(&s, "Analog %d-axis %d-button",
hweight8(analog->mask & ANALOG_AXES_STD),
hweight8(analog->mask & ANALOG_BTNS_STD) + !!(analog->mask & ANALOG_BTNS_CHF) * 2 +
hweight16(analog->mask & ANALOG_BTNS_GAMEPAD) + !!(analog->mask & ANALOG_HBTN_CHF) * 4);
if (analog->mask & ANALOG_HATS_ALL)
seq_buf_printf(&s, " %d-hat",
hweight16(analog->mask & ANALOG_HATS_ALL));
if (analog->mask & ANALOG_HAT_FCS)
seq_buf_printf(&s, " FCS");
if (analog->mask & ANALOG_ANY_CHF)
seq_buf_printf(&s, (analog->mask & ANALOG_SAITEK) ? " Saitek" : " CHF");
seq_buf_printf(&s, (analog->mask & ANALOG_GAMEPAD) ? " gamepad" : " joystick");
}
/*
* analog_init_device()
*/
static int analog_init_device(struct analog_port *port, struct analog *analog, int index)
{
struct input_dev *input_dev;
int i, j, t, v, w, x, y, z;
int error;
analog_name(analog);
snprintf(analog->phys, sizeof(analog->phys),
"%s/input%d", port->gameport->phys, index);
analog->buttons = (analog->mask & ANALOG_GAMEPAD) ? analog_pad_btn : analog_joy_btn;
analog->dev = input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
input_dev->name = analog->name;
input_dev->phys = analog->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_ANALOG;
input_dev->id.product = analog->mask >> 4;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &port->gameport->dev;
input_set_drvdata(input_dev, port);
input_dev->open = analog_open;
input_dev->close = analog_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = j = 0; i < 4; i++)
if (analog->mask & (1 << i)) {
t = analog_axes[j];
x = port->axes[i];
y = (port->axes[0] + port->axes[1]) >> 1;
z = y - port->axes[i];
z = z > 0 ? z : -z;
v = (x >> 3);
w = (x >> 3);
if ((i == 2 || i == 3) && (j == 2 || j == 3) && (z > (y >> 3)))
x = y;
if (analog->mask & ANALOG_SAITEK) {
if (i == 2) x = port->axes[i];
v = x - (x >> 2);
w = (x >> 4);
}
input_set_abs_params(input_dev, t, v, (x << 1) - v, port->fuzz, w);
j++;
}
for (i = j = 0; i < 3; i++)
if (analog->mask & analog_exts[i])
for (x = 0; x < 2; x++) {
t = analog_hats[j++];
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
}
for (i = j = 0; i < 4; i++)
if (analog->mask & (0x10 << i))
set_bit(analog->buttons[j++], input_dev->keybit);
if (analog->mask & ANALOG_BTNS_CHF)
for (i = 0; i < 2; i++)
set_bit(analog->buttons[j++], input_dev->keybit);
if (analog->mask & ANALOG_HBTN_CHF)
for (i = 0; i < 4; i++)
set_bit(analog->buttons[j++], input_dev->keybit);
for (i = 0; i < 4; i++)
if (analog->mask & (ANALOG_BTN_TL << i))
set_bit(analog_pads[i], input_dev->keybit);
analog_decode(analog, port->axes, port->initial, port->buttons);
error = input_register_device(analog->dev);
if (error) {
input_free_device(analog->dev);
return error;
}
return 0;
}
/*
* analog_init_devices() sets up device-specific values and registers the input devices.
*/
static int analog_init_masks(struct analog_port *port)
{
int i;
struct analog *analog = port->analog;
int max[4];
if (!port->mask)
return -1;
if ((port->mask & 3) != 3 && port->mask != 0xc) {
printk(KERN_WARNING "analog.c: Unknown joystick device found "
"(data=%#x, %s), probably not analog joystick.\n",
port->mask, port->gameport->phys);
return -1;
}
i = analog_options[0]; /* FIXME !!! - need to specify options for different ports */
analog[0].mask = i & 0xfffff;
analog[0].mask &= ~(ANALOG_AXES_STD | ANALOG_HAT_FCS | ANALOG_BTNS_GAMEPAD)
| port->mask | ((port->mask << 8) & ANALOG_HAT_FCS)
| ((port->mask << 10) & ANALOG_BTNS_TLR) | ((port->mask << 12) & ANALOG_BTNS_TLR2);
analog[0].mask &= ~(ANALOG_HAT2_CHF)
| ((analog[0].mask & ANALOG_HBTN_CHF) ? 0 : ANALOG_HAT2_CHF);
analog[0].mask &= ~(ANALOG_THROTTLE | ANALOG_BTN_TR | ANALOG_BTN_TR2)
| ((~analog[0].mask & ANALOG_HAT_FCS) >> 8)
| ((~analog[0].mask & ANALOG_HAT_FCS) << 2)
| ((~analog[0].mask & ANALOG_HAT_FCS) << 4);
analog[0].mask &= ~(ANALOG_THROTTLE | ANALOG_RUDDER)
| (((~analog[0].mask & ANALOG_BTNS_TLR ) >> 10)
& ((~analog[0].mask & ANALOG_BTNS_TLR2) >> 12));
analog[1].mask = ((i >> 20) & 0xff) | ((i >> 12) & 0xf0000);
analog[1].mask &= (analog[0].mask & ANALOG_EXTENSIONS) ? ANALOG_GAMEPAD
: (((ANALOG_BTNS_STD | port->mask) & ~analog[0].mask) | ANALOG_GAMEPAD);
if (port->cooked) {
for (i = 0; i < 4; i++) max[i] = port->axes[i] << 1;
if ((analog[0].mask & 0x7) == 0x7) max[2] = (max[0] + max[1]) >> 1;
if ((analog[0].mask & 0xb) == 0xb) max[3] = (max[0] + max[1]) >> 1;
if ((analog[0].mask & ANALOG_BTN_TL) && !(analog[0].mask & ANALOG_BTN_TL2)) max[2] >>= 1;
if ((analog[0].mask & ANALOG_BTN_TR) && !(analog[0].mask & ANALOG_BTN_TR2)) max[3] >>= 1;
if ((analog[0].mask & ANALOG_HAT_FCS)) max[3] >>= 1;
gameport_calibrate(port->gameport, port->axes, max);
}
for (i = 0; i < 4; i++)
port->initial[i] = port->axes[i];
return -!(analog[0].mask || analog[1].mask);
}
static int analog_init_port(struct gameport *gameport, struct gameport_driver *drv, struct analog_port *port)
{
int i, t, u, v;
port->gameport = gameport;
gameport_set_drvdata(gameport, port);
if (!gameport_open(gameport, drv, GAMEPORT_MODE_RAW)) {
analog_calibrate_timer(port);
gameport_trigger(gameport);
t = gameport_read(gameport);
msleep(ANALOG_MAX_TIME);
port->mask = (gameport_read(gameport) ^ t) & t & 0xf;
port->fuzz = (NSEC_PER_MSEC * ANALOG_FUZZ_MAGIC) / port->loop / 1000 + ANALOG_FUZZ_BITS;
for (i = 0; i < ANALOG_INIT_RETRIES; i++) {
if (!analog_cooked_read(port))
break;
msleep(ANALOG_MAX_TIME);
}
u = v = 0;
msleep(ANALOG_MAX_TIME);
t = gameport_time(gameport, ANALOG_MAX_TIME * 1000);
gameport_trigger(gameport);
while ((gameport_read(port->gameport) & port->mask) && (u < t))
u++;
udelay(ANALOG_SAITEK_DELAY);
t = gameport_time(gameport, ANALOG_SAITEK_TIME);
gameport_trigger(gameport);
while ((gameport_read(port->gameport) & port->mask) && (v < t))
v++;
if (v < (u >> 1)) { /* FIXME - more than one port */
analog_options[0] |= /* FIXME - more than one port */
ANALOG_SAITEK | ANALOG_BTNS_CHF | ANALOG_HBTN_CHF | ANALOG_HAT1_CHF;
return 0;
}
gameport_close(gameport);
}
if (!gameport_open(gameport, drv, GAMEPORT_MODE_COOKED)) {
for (i = 0; i < ANALOG_INIT_RETRIES; i++)
if (!gameport_cooked_read(gameport, port->axes, &port->buttons))
break;
for (i = 0; i < 4; i++)
if (port->axes[i] != -1)
port->mask |= 1 << i;
port->fuzz = gameport->fuzz;
port->cooked = 1;
return 0;
}
return gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
}
static int analog_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct analog_port *port;
int i;
int err;
if (!(port = kzalloc(sizeof(struct analog_port), GFP_KERNEL)))
return -ENOMEM;
err = analog_init_port(gameport, drv, port);
if (err)
goto fail1;
err = analog_init_masks(port);
if (err)
goto fail2;
gameport_set_poll_handler(gameport, analog_poll);
gameport_set_poll_interval(gameport, 10);
for (i = 0; i < 2; i++)
if (port->analog[i].mask) {
err = analog_init_device(port, port->analog + i, i);
if (err)
goto fail3;
}
return 0;
fail3: while (--i >= 0)
if (port->analog[i].mask)
input_unregister_device(port->analog[i].dev);
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(port);
return err;
}
static void analog_disconnect(struct gameport *gameport)
{
struct analog_port *port = gameport_get_drvdata(gameport);
int i;
for (i = 0; i < 2; i++)
if (port->analog[i].mask)
input_unregister_device(port->analog[i].dev);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
printk(KERN_INFO "analog.c: %d out of %d reads (%d%%) on %s failed\n",
port->bads, port->reads, port->reads ? (port->bads * 100 / port->reads) : 0,
port->gameport->phys);
kfree(port);
}
struct analog_types {
char *name;
int value;
};
static struct analog_types analog_types[] = {
{ "none", 0x00000000 },
{ "auto", 0x000000ff },
{ "2btn", 0x0000003f },
{ "y-joy", 0x0cc00033 },
{ "y-pad", 0x8cc80033 },
{ "fcs", 0x000008f7 },
{ "chf", 0x000002ff },
{ "fullchf", 0x000007ff },
{ "gamepad", 0x000830f3 },
{ "gamepad8", 0x0008f0f3 },
{ NULL, 0 }
};
static void analog_parse_options(void)
{
int i, j;
char *end;
for (i = 0; i < js_nargs; i++) {
for (j = 0; analog_types[j].name; j++)
if (!strcmp(analog_types[j].name, js[i])) {
analog_options[i] = analog_types[j].value;
break;
}
if (analog_types[j].name) continue;
analog_options[i] = simple_strtoul(js[i], &end, 0);
if (end != js[i]) continue;
analog_options[i] = 0xff;
if (!strlen(js[i])) continue;
printk(KERN_WARNING "analog.c: Bad config for port %d - \"%s\"\n", i, js[i]);
}
for (; i < ANALOG_PORTS; i++)
analog_options[i] = 0xff;
}
/*
* The gameport device structure.
*/
static struct gameport_driver analog_drv = {
.driver = {
.name = "analog",
},
.description = DRIVER_DESC,
.connect = analog_connect,
.disconnect = analog_disconnect,
};
static int __init analog_init(void)
{
analog_parse_options();
return gameport_register_driver(&analog_drv);
}
static void __exit analog_exit(void)
{
gameport_unregister_driver(&analog_drv);
}
module_init(analog_init);
module_exit(analog_exit);
|
linux-master
|
drivers/input/joystick/analog.c
|
// SPDX-License-Identifier: GPL-2.0
/*
* Driver for Phoenix RC Flight Controller Adapter
*
* Copyright (C) 2018 Marcus Folkesson <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/input.h>
#include <linux/mutex.h>
#include <linux/input.h>
#define PXRC_VENDOR_ID 0x1781
#define PXRC_PRODUCT_ID 0x0898
struct pxrc {
struct input_dev *input;
struct usb_interface *intf;
struct urb *urb;
struct mutex pm_mutex;
bool is_open;
char phys[64];
};
static void pxrc_usb_irq(struct urb *urb)
{
struct pxrc *pxrc = urb->context;
u8 *data = urb->transfer_buffer;
int error;
switch (urb->status) {
case 0:
/* success */
break;
case -ETIME:
/* this urb is timing out */
dev_dbg(&pxrc->intf->dev,
"%s - urb timed out - was the device unplugged?\n",
__func__);
return;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
case -EPIPE:
/* this urb is terminated, clean up */
dev_dbg(&pxrc->intf->dev, "%s - urb shutting down with status: %d\n",
__func__, urb->status);
return;
default:
dev_dbg(&pxrc->intf->dev, "%s - nonzero urb status received: %d\n",
__func__, urb->status);
goto exit;
}
if (urb->actual_length == 8) {
input_report_abs(pxrc->input, ABS_X, data[0]);
input_report_abs(pxrc->input, ABS_Y, data[2]);
input_report_abs(pxrc->input, ABS_RX, data[3]);
input_report_abs(pxrc->input, ABS_RY, data[4]);
input_report_abs(pxrc->input, ABS_RUDDER, data[5]);
input_report_abs(pxrc->input, ABS_THROTTLE, data[6]);
input_report_abs(pxrc->input, ABS_MISC, data[7]);
input_report_key(pxrc->input, BTN_A, data[1]);
}
exit:
/* Resubmit to fetch new fresh URBs */
error = usb_submit_urb(urb, GFP_ATOMIC);
if (error && error != -EPERM)
dev_err(&pxrc->intf->dev,
"%s - usb_submit_urb failed with result: %d",
__func__, error);
}
static int pxrc_open(struct input_dev *input)
{
struct pxrc *pxrc = input_get_drvdata(input);
int retval;
mutex_lock(&pxrc->pm_mutex);
retval = usb_submit_urb(pxrc->urb, GFP_KERNEL);
if (retval) {
dev_err(&pxrc->intf->dev,
"%s - usb_submit_urb failed, error: %d\n",
__func__, retval);
retval = -EIO;
goto out;
}
pxrc->is_open = true;
out:
mutex_unlock(&pxrc->pm_mutex);
return retval;
}
static void pxrc_close(struct input_dev *input)
{
struct pxrc *pxrc = input_get_drvdata(input);
mutex_lock(&pxrc->pm_mutex);
usb_kill_urb(pxrc->urb);
pxrc->is_open = false;
mutex_unlock(&pxrc->pm_mutex);
}
static void pxrc_free_urb(void *_pxrc)
{
struct pxrc *pxrc = _pxrc;
usb_free_urb(pxrc->urb);
}
static int pxrc_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev = interface_to_usbdev(intf);
struct pxrc *pxrc;
struct usb_endpoint_descriptor *epirq;
size_t xfer_size;
void *xfer_buf;
int error;
/*
* Locate the endpoint information. This device only has an
* interrupt endpoint.
*/
error = usb_find_common_endpoints(intf->cur_altsetting,
NULL, NULL, &epirq, NULL);
if (error) {
dev_err(&intf->dev, "Could not find endpoint\n");
return error;
}
pxrc = devm_kzalloc(&intf->dev, sizeof(*pxrc), GFP_KERNEL);
if (!pxrc)
return -ENOMEM;
mutex_init(&pxrc->pm_mutex);
pxrc->intf = intf;
usb_set_intfdata(pxrc->intf, pxrc);
xfer_size = usb_endpoint_maxp(epirq);
xfer_buf = devm_kmalloc(&intf->dev, xfer_size, GFP_KERNEL);
if (!xfer_buf)
return -ENOMEM;
pxrc->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!pxrc->urb)
return -ENOMEM;
error = devm_add_action_or_reset(&intf->dev, pxrc_free_urb, pxrc);
if (error)
return error;
usb_fill_int_urb(pxrc->urb, udev,
usb_rcvintpipe(udev, epirq->bEndpointAddress),
xfer_buf, xfer_size, pxrc_usb_irq, pxrc, 1);
pxrc->input = devm_input_allocate_device(&intf->dev);
if (!pxrc->input) {
dev_err(&intf->dev, "couldn't allocate input device\n");
return -ENOMEM;
}
pxrc->input->name = "PXRC Flight Controller Adapter";
usb_make_path(udev, pxrc->phys, sizeof(pxrc->phys));
strlcat(pxrc->phys, "/input0", sizeof(pxrc->phys));
pxrc->input->phys = pxrc->phys;
usb_to_input_id(udev, &pxrc->input->id);
pxrc->input->open = pxrc_open;
pxrc->input->close = pxrc_close;
input_set_capability(pxrc->input, EV_KEY, BTN_A);
input_set_abs_params(pxrc->input, ABS_X, 0, 255, 0, 0);
input_set_abs_params(pxrc->input, ABS_Y, 0, 255, 0, 0);
input_set_abs_params(pxrc->input, ABS_RX, 0, 255, 0, 0);
input_set_abs_params(pxrc->input, ABS_RY, 0, 255, 0, 0);
input_set_abs_params(pxrc->input, ABS_RUDDER, 0, 255, 0, 0);
input_set_abs_params(pxrc->input, ABS_THROTTLE, 0, 255, 0, 0);
input_set_abs_params(pxrc->input, ABS_MISC, 0, 255, 0, 0);
input_set_drvdata(pxrc->input, pxrc);
error = input_register_device(pxrc->input);
if (error)
return error;
return 0;
}
static void pxrc_disconnect(struct usb_interface *intf)
{
/* All driver resources are devm-managed. */
}
static int pxrc_suspend(struct usb_interface *intf, pm_message_t message)
{
struct pxrc *pxrc = usb_get_intfdata(intf);
mutex_lock(&pxrc->pm_mutex);
if (pxrc->is_open)
usb_kill_urb(pxrc->urb);
mutex_unlock(&pxrc->pm_mutex);
return 0;
}
static int pxrc_resume(struct usb_interface *intf)
{
struct pxrc *pxrc = usb_get_intfdata(intf);
int retval = 0;
mutex_lock(&pxrc->pm_mutex);
if (pxrc->is_open && usb_submit_urb(pxrc->urb, GFP_KERNEL) < 0)
retval = -EIO;
mutex_unlock(&pxrc->pm_mutex);
return retval;
}
static int pxrc_pre_reset(struct usb_interface *intf)
{
struct pxrc *pxrc = usb_get_intfdata(intf);
mutex_lock(&pxrc->pm_mutex);
usb_kill_urb(pxrc->urb);
return 0;
}
static int pxrc_post_reset(struct usb_interface *intf)
{
struct pxrc *pxrc = usb_get_intfdata(intf);
int retval = 0;
if (pxrc->is_open && usb_submit_urb(pxrc->urb, GFP_KERNEL) < 0)
retval = -EIO;
mutex_unlock(&pxrc->pm_mutex);
return retval;
}
static int pxrc_reset_resume(struct usb_interface *intf)
{
return pxrc_resume(intf);
}
static const struct usb_device_id pxrc_table[] = {
{ USB_DEVICE(PXRC_VENDOR_ID, PXRC_PRODUCT_ID) },
{ }
};
MODULE_DEVICE_TABLE(usb, pxrc_table);
static struct usb_driver pxrc_driver = {
.name = "pxrc",
.probe = pxrc_probe,
.disconnect = pxrc_disconnect,
.id_table = pxrc_table,
.suspend = pxrc_suspend,
.resume = pxrc_resume,
.pre_reset = pxrc_pre_reset,
.post_reset = pxrc_post_reset,
.reset_resume = pxrc_reset_resume,
};
module_usb_driver(pxrc_driver);
MODULE_AUTHOR("Marcus Folkesson <[email protected]>");
MODULE_DESCRIPTION("PhoenixRC Flight Controller Adapter");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/joystick/pxrc.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* PlayStation 1/2 joypads via SPI interface Driver
*
* Copyright (C) 2017 Tomohiro Yoshidomi <[email protected]>
*
* PlayStation 1/2 joypad's plug (not socket)
* 123 456 789
* (...|...|...)
*
* 1: DAT -> MISO (pullup with 1k owm to 3.3V)
* 2: CMD -> MOSI
* 3: 9V (for motor, if not use N.C.)
* 4: GND
* 5: 3.3V
* 6: Attention -> CS(SS)
* 7: SCK -> SCK
* 8: N.C.
* 9: ACK -> N.C.
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/spi/spi.h>
#include <linux/types.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#define REVERSE_BIT(x) ((((x) & 0x80) >> 7) | (((x) & 0x40) >> 5) | \
(((x) & 0x20) >> 3) | (((x) & 0x10) >> 1) | (((x) & 0x08) << 1) | \
(((x) & 0x04) << 3) | (((x) & 0x02) << 5) | (((x) & 0x01) << 7))
/* PlayStation 1/2 joypad command and response are LSBFIRST. */
/*
* 0x01, 0x42, 0x00, 0x00, 0x00,
* 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
* 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
*/
static const u8 PSX_CMD_POLL[] = {
0x80, 0x42, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
#ifdef CONFIG_JOYSTICK_PSXPAD_SPI_FF
/* 0x01, 0x43, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 */
static const u8 PSX_CMD_ENTER_CFG[] = {
0x80, 0xC2, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00
};
/* 0x01, 0x43, 0x00, 0x00, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A */
static const u8 PSX_CMD_EXIT_CFG[] = {
0x80, 0xC2, 0x00, 0x00, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A
};
/* 0x01, 0x4D, 0x00, 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xFF */
static const u8 PSX_CMD_ENABLE_MOTOR[] = {
0x80, 0xB2, 0x00, 0x00, 0x80, 0xFF, 0xFF, 0xFF, 0xFF
};
#endif /* CONFIG_JOYSTICK_PSXPAD_SPI_FF */
struct psxpad {
struct spi_device *spi;
struct input_dev *idev;
char phys[0x20];
bool motor1enable;
bool motor2enable;
u8 motor1level;
u8 motor2level;
u8 sendbuf[0x20] ____cacheline_aligned;
u8 response[sizeof(PSX_CMD_POLL)] ____cacheline_aligned;
};
static int psxpad_command(struct psxpad *pad, const u8 sendcmdlen)
{
struct spi_transfer xfers = {
.tx_buf = pad->sendbuf,
.rx_buf = pad->response,
.len = sendcmdlen,
};
int err;
err = spi_sync_transfer(pad->spi, &xfers, 1);
if (err) {
dev_err(&pad->spi->dev,
"%s: failed to SPI xfers mode: %d\n",
__func__, err);
return err;
}
return 0;
}
#ifdef CONFIG_JOYSTICK_PSXPAD_SPI_FF
static void psxpad_control_motor(struct psxpad *pad,
bool motor1enable, bool motor2enable)
{
int err;
pad->motor1enable = motor1enable;
pad->motor2enable = motor2enable;
memcpy(pad->sendbuf, PSX_CMD_ENTER_CFG, sizeof(PSX_CMD_ENTER_CFG));
err = psxpad_command(pad, sizeof(PSX_CMD_ENTER_CFG));
if (err) {
dev_err(&pad->spi->dev,
"%s: failed to enter config mode: %d\n",
__func__, err);
return;
}
memcpy(pad->sendbuf, PSX_CMD_ENABLE_MOTOR,
sizeof(PSX_CMD_ENABLE_MOTOR));
pad->sendbuf[3] = pad->motor1enable ? 0x00 : 0xFF;
pad->sendbuf[4] = pad->motor2enable ? 0x80 : 0xFF;
err = psxpad_command(pad, sizeof(PSX_CMD_ENABLE_MOTOR));
if (err) {
dev_err(&pad->spi->dev,
"%s: failed to enable motor mode: %d\n",
__func__, err);
return;
}
memcpy(pad->sendbuf, PSX_CMD_EXIT_CFG, sizeof(PSX_CMD_EXIT_CFG));
err = psxpad_command(pad, sizeof(PSX_CMD_EXIT_CFG));
if (err) {
dev_err(&pad->spi->dev,
"%s: failed to exit config mode: %d\n",
__func__, err);
return;
}
}
static void psxpad_set_motor_level(struct psxpad *pad,
u8 motor1level, u8 motor2level)
{
pad->motor1level = motor1level ? 0xFF : 0x00;
pad->motor2level = REVERSE_BIT(motor2level);
}
static int psxpad_spi_play_effect(struct input_dev *idev,
void *data, struct ff_effect *effect)
{
struct psxpad *pad = input_get_drvdata(idev);
switch (effect->type) {
case FF_RUMBLE:
psxpad_set_motor_level(pad,
(effect->u.rumble.weak_magnitude >> 8) & 0xFFU,
(effect->u.rumble.strong_magnitude >> 8) & 0xFFU);
break;
}
return 0;
}
static int psxpad_spi_init_ff(struct psxpad *pad)
{
int err;
input_set_capability(pad->idev, EV_FF, FF_RUMBLE);
err = input_ff_create_memless(pad->idev, NULL, psxpad_spi_play_effect);
if (err) {
dev_err(&pad->spi->dev,
"input_ff_create_memless() failed: %d\n", err);
return err;
}
return 0;
}
#else /* CONFIG_JOYSTICK_PSXPAD_SPI_FF */
static void psxpad_control_motor(struct psxpad *pad,
bool motor1enable, bool motor2enable)
{
}
static void psxpad_set_motor_level(struct psxpad *pad,
u8 motor1level, u8 motor2level)
{
}
static inline int psxpad_spi_init_ff(struct psxpad *pad)
{
return 0;
}
#endif /* CONFIG_JOYSTICK_PSXPAD_SPI_FF */
static int psxpad_spi_poll_open(struct input_dev *input)
{
struct psxpad *pad = input_get_drvdata(input);
pm_runtime_get_sync(&pad->spi->dev);
return 0;
}
static void psxpad_spi_poll_close(struct input_dev *input)
{
struct psxpad *pad = input_get_drvdata(input);
pm_runtime_put_sync(&pad->spi->dev);
}
static void psxpad_spi_poll(struct input_dev *input)
{
struct psxpad *pad = input_get_drvdata(input);
u8 b_rsp3, b_rsp4;
int err;
psxpad_control_motor(pad, true, true);
memcpy(pad->sendbuf, PSX_CMD_POLL, sizeof(PSX_CMD_POLL));
pad->sendbuf[3] = pad->motor1enable ? pad->motor1level : 0x00;
pad->sendbuf[4] = pad->motor2enable ? pad->motor2level : 0x00;
err = psxpad_command(pad, sizeof(PSX_CMD_POLL));
if (err) {
dev_err(&pad->spi->dev,
"%s: poll command failed mode: %d\n", __func__, err);
return;
}
switch (pad->response[1]) {
case 0xCE: /* 0x73 : analog 1 */
/* button data is inverted */
b_rsp3 = ~pad->response[3];
b_rsp4 = ~pad->response[4];
input_report_abs(input, ABS_X, REVERSE_BIT(pad->response[7]));
input_report_abs(input, ABS_Y, REVERSE_BIT(pad->response[8]));
input_report_abs(input, ABS_RX, REVERSE_BIT(pad->response[5]));
input_report_abs(input, ABS_RY, REVERSE_BIT(pad->response[6]));
input_report_key(input, BTN_DPAD_UP, b_rsp3 & BIT(3));
input_report_key(input, BTN_DPAD_DOWN, b_rsp3 & BIT(1));
input_report_key(input, BTN_DPAD_LEFT, b_rsp3 & BIT(0));
input_report_key(input, BTN_DPAD_RIGHT, b_rsp3 & BIT(2));
input_report_key(input, BTN_X, b_rsp4 & BIT(3));
input_report_key(input, BTN_A, b_rsp4 & BIT(2));
input_report_key(input, BTN_B, b_rsp4 & BIT(1));
input_report_key(input, BTN_Y, b_rsp4 & BIT(0));
input_report_key(input, BTN_TL, b_rsp4 & BIT(5));
input_report_key(input, BTN_TR, b_rsp4 & BIT(4));
input_report_key(input, BTN_TL2, b_rsp4 & BIT(7));
input_report_key(input, BTN_TR2, b_rsp4 & BIT(6));
input_report_key(input, BTN_THUMBL, b_rsp3 & BIT(6));
input_report_key(input, BTN_THUMBR, b_rsp3 & BIT(5));
input_report_key(input, BTN_SELECT, b_rsp3 & BIT(7));
input_report_key(input, BTN_START, b_rsp3 & BIT(4));
break;
case 0x82: /* 0x41 : digital */
/* button data is inverted */
b_rsp3 = ~pad->response[3];
b_rsp4 = ~pad->response[4];
input_report_abs(input, ABS_X, 0x80);
input_report_abs(input, ABS_Y, 0x80);
input_report_abs(input, ABS_RX, 0x80);
input_report_abs(input, ABS_RY, 0x80);
input_report_key(input, BTN_DPAD_UP, b_rsp3 & BIT(3));
input_report_key(input, BTN_DPAD_DOWN, b_rsp3 & BIT(1));
input_report_key(input, BTN_DPAD_LEFT, b_rsp3 & BIT(0));
input_report_key(input, BTN_DPAD_RIGHT, b_rsp3 & BIT(2));
input_report_key(input, BTN_X, b_rsp4 & BIT(3));
input_report_key(input, BTN_A, b_rsp4 & BIT(2));
input_report_key(input, BTN_B, b_rsp4 & BIT(1));
input_report_key(input, BTN_Y, b_rsp4 & BIT(0));
input_report_key(input, BTN_TL, b_rsp4 & BIT(5));
input_report_key(input, BTN_TR, b_rsp4 & BIT(4));
input_report_key(input, BTN_TL2, b_rsp4 & BIT(7));
input_report_key(input, BTN_TR2, b_rsp4 & BIT(6));
input_report_key(input, BTN_THUMBL, false);
input_report_key(input, BTN_THUMBR, false);
input_report_key(input, BTN_SELECT, b_rsp3 & BIT(7));
input_report_key(input, BTN_START, b_rsp3 & BIT(4));
break;
}
input_sync(input);
}
static int psxpad_spi_probe(struct spi_device *spi)
{
struct psxpad *pad;
struct input_dev *idev;
int err;
pad = devm_kzalloc(&spi->dev, sizeof(struct psxpad), GFP_KERNEL);
if (!pad)
return -ENOMEM;
idev = devm_input_allocate_device(&spi->dev);
if (!idev) {
dev_err(&spi->dev, "failed to allocate input device\n");
return -ENOMEM;
}
/* input poll device settings */
pad->idev = idev;
pad->spi = spi;
/* input device settings */
input_set_drvdata(idev, pad);
idev->name = "PlayStation 1/2 joypad";
snprintf(pad->phys, sizeof(pad->phys), "%s/input", dev_name(&spi->dev));
idev->id.bustype = BUS_SPI;
idev->open = psxpad_spi_poll_open;
idev->close = psxpad_spi_poll_close;
/* key/value map settings */
input_set_abs_params(idev, ABS_X, 0, 255, 0, 0);
input_set_abs_params(idev, ABS_Y, 0, 255, 0, 0);
input_set_abs_params(idev, ABS_RX, 0, 255, 0, 0);
input_set_abs_params(idev, ABS_RY, 0, 255, 0, 0);
input_set_capability(idev, EV_KEY, BTN_DPAD_UP);
input_set_capability(idev, EV_KEY, BTN_DPAD_DOWN);
input_set_capability(idev, EV_KEY, BTN_DPAD_LEFT);
input_set_capability(idev, EV_KEY, BTN_DPAD_RIGHT);
input_set_capability(idev, EV_KEY, BTN_A);
input_set_capability(idev, EV_KEY, BTN_B);
input_set_capability(idev, EV_KEY, BTN_X);
input_set_capability(idev, EV_KEY, BTN_Y);
input_set_capability(idev, EV_KEY, BTN_TL);
input_set_capability(idev, EV_KEY, BTN_TR);
input_set_capability(idev, EV_KEY, BTN_TL2);
input_set_capability(idev, EV_KEY, BTN_TR2);
input_set_capability(idev, EV_KEY, BTN_THUMBL);
input_set_capability(idev, EV_KEY, BTN_THUMBR);
input_set_capability(idev, EV_KEY, BTN_SELECT);
input_set_capability(idev, EV_KEY, BTN_START);
err = psxpad_spi_init_ff(pad);
if (err)
return err;
/* SPI settings */
spi->mode = SPI_MODE_3;
spi->bits_per_word = 8;
/* (PlayStation 1/2 joypad might be possible works 250kHz/500kHz) */
spi->master->min_speed_hz = 125000;
spi->master->max_speed_hz = 125000;
spi_setup(spi);
/* pad settings */
psxpad_set_motor_level(pad, 0, 0);
err = input_setup_polling(idev, psxpad_spi_poll);
if (err) {
dev_err(&spi->dev, "failed to set up polling: %d\n", err);
return err;
}
/* poll interval is about 60fps */
input_set_poll_interval(idev, 16);
input_set_min_poll_interval(idev, 8);
input_set_max_poll_interval(idev, 32);
/* register input poll device */
err = input_register_device(idev);
if (err) {
dev_err(&spi->dev,
"failed to register input device: %d\n", err);
return err;
}
pm_runtime_enable(&spi->dev);
return 0;
}
static int psxpad_spi_suspend(struct device *dev)
{
struct spi_device *spi = to_spi_device(dev);
struct psxpad *pad = spi_get_drvdata(spi);
psxpad_set_motor_level(pad, 0, 0);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(psxpad_spi_pm, psxpad_spi_suspend, NULL);
static const struct spi_device_id psxpad_spi_id[] = {
{ "psxpad-spi", 0 },
{ }
};
MODULE_DEVICE_TABLE(spi, psxpad_spi_id);
static struct spi_driver psxpad_spi_driver = {
.driver = {
.name = "psxpad-spi",
.pm = pm_sleep_ptr(&psxpad_spi_pm),
},
.id_table = psxpad_spi_id,
.probe = psxpad_spi_probe,
};
module_spi_driver(psxpad_spi_driver);
MODULE_AUTHOR("Tomohiro Yoshidomi <[email protected]>");
MODULE_DESCRIPTION("PlayStation 1/2 joypads via SPI interface Driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/joystick/psxpad-spi.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2001 Vojtech Pavlik
*/
/*
* Gravis/Kensington GrIP protocol joystick and gamepad driver for Linux
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/input.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "Gravis GrIP protocol joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define GRIP_MODE_GPP 1
#define GRIP_MODE_BD 2
#define GRIP_MODE_XT 3
#define GRIP_MODE_DC 4
#define GRIP_LENGTH_GPP 24
#define GRIP_STROBE_GPP 200 /* 200 us */
#define GRIP_LENGTH_XT 4
#define GRIP_STROBE_XT 64 /* 64 us */
#define GRIP_MAX_CHUNKS_XT 10
#define GRIP_MAX_BITS_XT 30
struct grip {
struct gameport *gameport;
struct input_dev *dev[2];
unsigned char mode[2];
int reads;
int bads;
char phys[2][32];
};
static int grip_btn_gpp[] = { BTN_START, BTN_SELECT, BTN_TR2, BTN_Y, 0, BTN_TL2, BTN_A, BTN_B, BTN_X, 0, BTN_TL, BTN_TR, -1 };
static int grip_btn_bd[] = { BTN_THUMB, BTN_THUMB2, BTN_TRIGGER, BTN_TOP, BTN_BASE, -1 };
static int grip_btn_xt[] = { BTN_TRIGGER, BTN_THUMB, BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_SELECT, BTN_START, BTN_MODE, -1 };
static int grip_btn_dc[] = { BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_BASE5, -1 };
static int grip_abs_gpp[] = { ABS_X, ABS_Y, -1 };
static int grip_abs_bd[] = { ABS_X, ABS_Y, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y, -1 };
static int grip_abs_xt[] = { ABS_X, ABS_Y, ABS_BRAKE, ABS_GAS, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y, ABS_HAT1X, ABS_HAT1Y, -1 };
static int grip_abs_dc[] = { ABS_X, ABS_Y, ABS_RX, ABS_RY, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y, -1 };
static char *grip_name[] = { NULL, "Gravis GamePad Pro", "Gravis Blackhawk Digital",
"Gravis Xterminator Digital", "Gravis Xterminator DualControl" };
static int *grip_abs[] = { NULL, grip_abs_gpp, grip_abs_bd, grip_abs_xt, grip_abs_dc };
static int *grip_btn[] = { NULL, grip_btn_gpp, grip_btn_bd, grip_btn_xt, grip_btn_dc };
static char grip_anx[] = { 0, 0, 3, 5, 5 };
static char grip_cen[] = { 0, 0, 2, 2, 4 };
/*
* grip_gpp_read_packet() reads a Gravis GamePad Pro packet.
*/
static int grip_gpp_read_packet(struct gameport *gameport, int shift, unsigned int *data)
{
unsigned long flags;
unsigned char u, v;
unsigned int t;
int i;
int strobe = gameport_time(gameport, GRIP_STROBE_GPP);
data[0] = 0;
t = strobe;
i = 0;
local_irq_save(flags);
v = gameport_read(gameport) >> shift;
do {
t--;
u = v; v = (gameport_read(gameport) >> shift) & 3;
if (~v & u & 1) {
data[0] |= (v >> 1) << i++;
t = strobe;
}
} while (i < GRIP_LENGTH_GPP && t > 0);
local_irq_restore(flags);
if (i < GRIP_LENGTH_GPP) return -1;
for (i = 0; i < GRIP_LENGTH_GPP && (data[0] & 0xfe4210) ^ 0x7c0000; i++)
data[0] = data[0] >> 1 | (data[0] & 1) << (GRIP_LENGTH_GPP - 1);
return -(i == GRIP_LENGTH_GPP);
}
/*
* grip_xt_read_packet() reads a Gravis Xterminator packet.
*/
static int grip_xt_read_packet(struct gameport *gameport, int shift, unsigned int *data)
{
unsigned int i, j, buf, crc;
unsigned char u, v, w;
unsigned long flags;
unsigned int t;
char status;
int strobe = gameport_time(gameport, GRIP_STROBE_XT);
data[0] = data[1] = data[2] = data[3] = 0;
status = buf = i = j = 0;
t = strobe;
local_irq_save(flags);
v = w = (gameport_read(gameport) >> shift) & 3;
do {
t--;
u = (gameport_read(gameport) >> shift) & 3;
if (u ^ v) {
if ((u ^ v) & 1) {
buf = (buf << 1) | (u >> 1);
t = strobe;
i++;
} else
if ((((u ^ v) & (v ^ w)) >> 1) & ~(u | v | w) & 1) {
if (i == 20) {
crc = buf ^ (buf >> 7) ^ (buf >> 14);
if (!((crc ^ (0x25cb9e70 >> ((crc >> 2) & 0x1c))) & 0xf)) {
data[buf >> 18] = buf >> 4;
status |= 1 << (buf >> 18);
}
j++;
}
t = strobe;
buf = 0;
i = 0;
}
w = v;
v = u;
}
} while (status != 0xf && i < GRIP_MAX_BITS_XT && j < GRIP_MAX_CHUNKS_XT && t > 0);
local_irq_restore(flags);
return -(status != 0xf);
}
/*
* grip_timer() repeatedly polls the joysticks and generates events.
*/
static void grip_poll(struct gameport *gameport)
{
struct grip *grip = gameport_get_drvdata(gameport);
unsigned int data[GRIP_LENGTH_XT];
struct input_dev *dev;
int i, j;
for (i = 0; i < 2; i++) {
dev = grip->dev[i];
if (!dev)
continue;
grip->reads++;
switch (grip->mode[i]) {
case GRIP_MODE_GPP:
if (grip_gpp_read_packet(grip->gameport, (i << 1) + 4, data)) {
grip->bads++;
break;
}
input_report_abs(dev, ABS_X, ((*data >> 15) & 1) - ((*data >> 16) & 1));
input_report_abs(dev, ABS_Y, ((*data >> 13) & 1) - ((*data >> 12) & 1));
for (j = 0; j < 12; j++)
if (grip_btn_gpp[j])
input_report_key(dev, grip_btn_gpp[j], (*data >> j) & 1);
break;
case GRIP_MODE_BD:
if (grip_xt_read_packet(grip->gameport, (i << 1) + 4, data)) {
grip->bads++;
break;
}
input_report_abs(dev, ABS_X, (data[0] >> 2) & 0x3f);
input_report_abs(dev, ABS_Y, 63 - ((data[0] >> 8) & 0x3f));
input_report_abs(dev, ABS_THROTTLE, (data[2] >> 8) & 0x3f);
input_report_abs(dev, ABS_HAT0X, ((data[2] >> 1) & 1) - ( data[2] & 1));
input_report_abs(dev, ABS_HAT0Y, ((data[2] >> 2) & 1) - ((data[2] >> 3) & 1));
for (j = 0; j < 5; j++)
input_report_key(dev, grip_btn_bd[j], (data[3] >> (j + 4)) & 1);
break;
case GRIP_MODE_XT:
if (grip_xt_read_packet(grip->gameport, (i << 1) + 4, data)) {
grip->bads++;
break;
}
input_report_abs(dev, ABS_X, (data[0] >> 2) & 0x3f);
input_report_abs(dev, ABS_Y, 63 - ((data[0] >> 8) & 0x3f));
input_report_abs(dev, ABS_BRAKE, (data[1] >> 2) & 0x3f);
input_report_abs(dev, ABS_GAS, (data[1] >> 8) & 0x3f);
input_report_abs(dev, ABS_THROTTLE, (data[2] >> 8) & 0x3f);
input_report_abs(dev, ABS_HAT0X, ((data[2] >> 1) & 1) - ( data[2] & 1));
input_report_abs(dev, ABS_HAT0Y, ((data[2] >> 2) & 1) - ((data[2] >> 3) & 1));
input_report_abs(dev, ABS_HAT1X, ((data[2] >> 5) & 1) - ((data[2] >> 4) & 1));
input_report_abs(dev, ABS_HAT1Y, ((data[2] >> 6) & 1) - ((data[2] >> 7) & 1));
for (j = 0; j < 11; j++)
input_report_key(dev, grip_btn_xt[j], (data[3] >> (j + 3)) & 1);
break;
case GRIP_MODE_DC:
if (grip_xt_read_packet(grip->gameport, (i << 1) + 4, data)) {
grip->bads++;
break;
}
input_report_abs(dev, ABS_X, (data[0] >> 2) & 0x3f);
input_report_abs(dev, ABS_Y, (data[0] >> 8) & 0x3f);
input_report_abs(dev, ABS_RX, (data[1] >> 2) & 0x3f);
input_report_abs(dev, ABS_RY, (data[1] >> 8) & 0x3f);
input_report_abs(dev, ABS_THROTTLE, (data[2] >> 8) & 0x3f);
input_report_abs(dev, ABS_HAT0X, ((data[2] >> 1) & 1) - ( data[2] & 1));
input_report_abs(dev, ABS_HAT0Y, ((data[2] >> 2) & 1) - ((data[2] >> 3) & 1));
for (j = 0; j < 9; j++)
input_report_key(dev, grip_btn_dc[j], (data[3] >> (j + 3)) & 1);
break;
}
input_sync(dev);
}
}
static int grip_open(struct input_dev *dev)
{
struct grip *grip = input_get_drvdata(dev);
gameport_start_polling(grip->gameport);
return 0;
}
static void grip_close(struct input_dev *dev)
{
struct grip *grip = input_get_drvdata(dev);
gameport_stop_polling(grip->gameport);
}
static int grip_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct grip *grip;
struct input_dev *input_dev;
unsigned int data[GRIP_LENGTH_XT];
int i, j, t;
int err;
if (!(grip = kzalloc(sizeof(struct grip), GFP_KERNEL)))
return -ENOMEM;
grip->gameport = gameport;
gameport_set_drvdata(gameport, grip);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
for (i = 0; i < 2; i++) {
if (!grip_gpp_read_packet(gameport, (i << 1) + 4, data)) {
grip->mode[i] = GRIP_MODE_GPP;
continue;
}
if (!grip_xt_read_packet(gameport, (i << 1) + 4, data)) {
if (!(data[3] & 7)) {
grip->mode[i] = GRIP_MODE_BD;
continue;
}
if (!(data[2] & 0xf0)) {
grip->mode[i] = GRIP_MODE_XT;
continue;
}
grip->mode[i] = GRIP_MODE_DC;
continue;
}
}
if (!grip->mode[0] && !grip->mode[1]) {
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, grip_poll);
gameport_set_poll_interval(gameport, 20);
for (i = 0; i < 2; i++) {
if (!grip->mode[i])
continue;
grip->dev[i] = input_dev = input_allocate_device();
if (!input_dev) {
err = -ENOMEM;
goto fail3;
}
snprintf(grip->phys[i], sizeof(grip->phys[i]),
"%s/input%d", gameport->phys, i);
input_dev->name = grip_name[grip->mode[i]];
input_dev->phys = grip->phys[i];
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_GRAVIS;
input_dev->id.product = grip->mode[i];
input_dev->id.version = 0x0100;
input_dev->dev.parent = &gameport->dev;
input_set_drvdata(input_dev, grip);
input_dev->open = grip_open;
input_dev->close = grip_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (j = 0; (t = grip_abs[grip->mode[i]][j]) >= 0; j++) {
if (j < grip_cen[grip->mode[i]])
input_set_abs_params(input_dev, t, 14, 52, 1, 2);
else if (j < grip_anx[grip->mode[i]])
input_set_abs_params(input_dev, t, 3, 57, 1, 0);
else
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
}
for (j = 0; (t = grip_btn[grip->mode[i]][j]) >= 0; j++)
if (t > 0)
set_bit(t, input_dev->keybit);
err = input_register_device(grip->dev[i]);
if (err)
goto fail4;
}
return 0;
fail4: input_free_device(grip->dev[i]);
fail3: while (--i >= 0)
if (grip->dev[i])
input_unregister_device(grip->dev[i]);
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(grip);
return err;
}
static void grip_disconnect(struct gameport *gameport)
{
struct grip *grip = gameport_get_drvdata(gameport);
int i;
for (i = 0; i < 2; i++)
if (grip->dev[i])
input_unregister_device(grip->dev[i]);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(grip);
}
static struct gameport_driver grip_drv = {
.driver = {
.name = "grip",
.owner = THIS_MODULE,
},
.description = DRIVER_DESC,
.connect = grip_connect,
.disconnect = grip_disconnect,
};
module_gameport_driver(grip_drv);
|
linux-master
|
drivers/input/joystick/grip.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*
* Based on the work of:
* Andree Borrmann Mats Sjövall
*/
/*
* Atari, Amstrad, Commodore, Amiga, Sega, etc. joystick driver for Linux
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/parport.h>
#include <linux/input.h>
#include <linux/mutex.h>
#include <linux/slab.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("Atari, Amstrad, Commodore, Amiga, Sega, etc. joystick driver");
MODULE_LICENSE("GPL");
struct db9_config {
int args[2];
unsigned int nargs;
};
#define DB9_MAX_PORTS 3
static struct db9_config db9_cfg[DB9_MAX_PORTS];
module_param_array_named(dev, db9_cfg[0].args, int, &db9_cfg[0].nargs, 0);
MODULE_PARM_DESC(dev, "Describes first attached device (<parport#>,<type>)");
module_param_array_named(dev2, db9_cfg[1].args, int, &db9_cfg[1].nargs, 0);
MODULE_PARM_DESC(dev2, "Describes second attached device (<parport#>,<type>)");
module_param_array_named(dev3, db9_cfg[2].args, int, &db9_cfg[2].nargs, 0);
MODULE_PARM_DESC(dev3, "Describes third attached device (<parport#>,<type>)");
#define DB9_ARG_PARPORT 0
#define DB9_ARG_MODE 1
#define DB9_MULTI_STICK 0x01
#define DB9_MULTI2_STICK 0x02
#define DB9_GENESIS_PAD 0x03
#define DB9_GENESIS5_PAD 0x05
#define DB9_GENESIS6_PAD 0x06
#define DB9_SATURN_PAD 0x07
#define DB9_MULTI_0802 0x08
#define DB9_MULTI_0802_2 0x09
#define DB9_CD32_PAD 0x0A
#define DB9_SATURN_DPP 0x0B
#define DB9_SATURN_DPP_2 0x0C
#define DB9_MAX_PAD 0x0D
#define DB9_UP 0x01
#define DB9_DOWN 0x02
#define DB9_LEFT 0x04
#define DB9_RIGHT 0x08
#define DB9_FIRE1 0x10
#define DB9_FIRE2 0x20
#define DB9_FIRE3 0x40
#define DB9_FIRE4 0x80
#define DB9_NORMAL 0x0a
#define DB9_NOSELECT 0x08
#define DB9_GENESIS6_DELAY 14
#define DB9_REFRESH_TIME HZ/100
#define DB9_MAX_DEVICES 2
struct db9_mode_data {
const char *name;
const short *buttons;
int n_buttons;
int n_pads;
int n_axis;
int bidirectional;
int reverse;
};
struct db9 {
struct input_dev *dev[DB9_MAX_DEVICES];
struct timer_list timer;
struct pardevice *pd;
int mode;
int used;
int parportno;
struct mutex mutex;
char phys[DB9_MAX_DEVICES][32];
};
static struct db9 *db9_base[3];
static const short db9_multi_btn[] = { BTN_TRIGGER, BTN_THUMB };
static const short db9_genesis_btn[] = { BTN_START, BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_MODE };
static const short db9_cd32_btn[] = { BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START };
static const short db9_abs[] = { ABS_X, ABS_Y, ABS_RX, ABS_RY, ABS_RZ, ABS_Z, ABS_HAT0X, ABS_HAT0Y, ABS_HAT1X, ABS_HAT1Y };
static const struct db9_mode_data db9_modes[] = {
{ NULL, NULL, 0, 0, 0, 0, 0 },
{ "Multisystem joystick", db9_multi_btn, 1, 1, 2, 1, 1 },
{ "Multisystem joystick (2 fire)", db9_multi_btn, 2, 1, 2, 1, 1 },
{ "Genesis pad", db9_genesis_btn, 4, 1, 2, 1, 1 },
{ NULL, NULL, 0, 0, 0, 0, 0 },
{ "Genesis 5 pad", db9_genesis_btn, 6, 1, 2, 1, 1 },
{ "Genesis 6 pad", db9_genesis_btn, 8, 1, 2, 1, 1 },
{ "Saturn pad", db9_cd32_btn, 9, 6, 7, 0, 1 },
{ "Multisystem (0.8.0.2) joystick", db9_multi_btn, 1, 1, 2, 1, 1 },
{ "Multisystem (0.8.0.2-dual) joystick", db9_multi_btn, 1, 2, 2, 1, 1 },
{ "Amiga CD-32 pad", db9_cd32_btn, 7, 1, 2, 1, 1 },
{ "Saturn dpp", db9_cd32_btn, 9, 6, 7, 0, 0 },
{ "Saturn dpp dual", db9_cd32_btn, 9, 12, 7, 0, 0 },
};
/*
* Saturn controllers
*/
#define DB9_SATURN_DELAY 300
static const int db9_saturn_byte[] = { 1, 1, 1, 2, 2, 2, 2, 2, 1 };
static const unsigned char db9_saturn_mask[] = { 0x04, 0x01, 0x02, 0x40, 0x20, 0x10, 0x08, 0x80, 0x08 };
/*
* db9_saturn_write_sub() writes 2 bit data.
*/
static void db9_saturn_write_sub(struct parport *port, int type, unsigned char data, int powered, int pwr_sub)
{
unsigned char c;
switch (type) {
case 1: /* DPP1 */
c = 0x80 | 0x30 | (powered ? 0x08 : 0) | (pwr_sub ? 0x04 : 0) | data;
parport_write_data(port, c);
break;
case 2: /* DPP2 */
c = 0x40 | data << 4 | (powered ? 0x08 : 0) | (pwr_sub ? 0x04 : 0) | 0x03;
parport_write_data(port, c);
break;
case 0: /* DB9 */
c = ((((data & 2) ? 2 : 0) | ((data & 1) ? 4 : 0)) ^ 0x02) | !powered;
parport_write_control(port, c);
break;
}
}
/*
* gc_saturn_read_sub() reads 4 bit data.
*/
static unsigned char db9_saturn_read_sub(struct parport *port, int type)
{
unsigned char data;
if (type) {
/* DPP */
data = parport_read_status(port) ^ 0x80;
return (data & 0x80 ? 1 : 0) | (data & 0x40 ? 2 : 0)
| (data & 0x20 ? 4 : 0) | (data & 0x10 ? 8 : 0);
} else {
/* DB9 */
data = parport_read_data(port) & 0x0f;
return (data & 0x8 ? 1 : 0) | (data & 0x4 ? 2 : 0)
| (data & 0x2 ? 4 : 0) | (data & 0x1 ? 8 : 0);
}
}
/*
* db9_saturn_read_analog() sends clock and reads 8 bit data.
*/
static unsigned char db9_saturn_read_analog(struct parport *port, int type, int powered)
{
unsigned char data;
db9_saturn_write_sub(port, type, 0, powered, 0);
udelay(DB9_SATURN_DELAY);
data = db9_saturn_read_sub(port, type) << 4;
db9_saturn_write_sub(port, type, 2, powered, 0);
udelay(DB9_SATURN_DELAY);
data |= db9_saturn_read_sub(port, type);
return data;
}
/*
* db9_saturn_read_packet() reads whole saturn packet at connector
* and returns device identifier code.
*/
static unsigned char db9_saturn_read_packet(struct parport *port, unsigned char *data, int type, int powered)
{
int i, j;
unsigned char tmp;
db9_saturn_write_sub(port, type, 3, powered, 0);
data[0] = db9_saturn_read_sub(port, type);
switch (data[0] & 0x0f) {
case 0xf:
/* 1111 no pad */
return data[0] = 0xff;
case 0x4: case 0x4 | 0x8:
/* ?100 : digital controller */
db9_saturn_write_sub(port, type, 0, powered, 1);
data[2] = db9_saturn_read_sub(port, type) << 4;
db9_saturn_write_sub(port, type, 2, powered, 1);
data[1] = db9_saturn_read_sub(port, type) << 4;
db9_saturn_write_sub(port, type, 1, powered, 1);
data[1] |= db9_saturn_read_sub(port, type);
db9_saturn_write_sub(port, type, 3, powered, 1);
/* data[2] |= db9_saturn_read_sub(port, type); */
data[2] |= data[0];
return data[0] = 0x02;
case 0x1:
/* 0001 : analog controller or multitap */
db9_saturn_write_sub(port, type, 2, powered, 0);
udelay(DB9_SATURN_DELAY);
data[0] = db9_saturn_read_analog(port, type, powered);
if (data[0] != 0x41) {
/* read analog controller */
for (i = 0; i < (data[0] & 0x0f); i++)
data[i + 1] = db9_saturn_read_analog(port, type, powered);
db9_saturn_write_sub(port, type, 3, powered, 0);
return data[0];
} else {
/* read multitap */
if (db9_saturn_read_analog(port, type, powered) != 0x60)
return data[0] = 0xff;
for (i = 0; i < 60; i += 10) {
data[i] = db9_saturn_read_analog(port, type, powered);
if (data[i] != 0xff)
/* read each pad */
for (j = 0; j < (data[i] & 0x0f); j++)
data[i + j + 1] = db9_saturn_read_analog(port, type, powered);
}
db9_saturn_write_sub(port, type, 3, powered, 0);
return 0x41;
}
case 0x0:
/* 0000 : mouse */
db9_saturn_write_sub(port, type, 2, powered, 0);
udelay(DB9_SATURN_DELAY);
tmp = db9_saturn_read_analog(port, type, powered);
if (tmp == 0xff) {
for (i = 0; i < 3; i++)
data[i + 1] = db9_saturn_read_analog(port, type, powered);
db9_saturn_write_sub(port, type, 3, powered, 0);
return data[0] = 0xe3;
}
fallthrough;
default:
return data[0];
}
}
/*
* db9_saturn_report() analyzes packet and reports.
*/
static int db9_saturn_report(unsigned char id, unsigned char data[60], struct input_dev *devs[], int n, int max_pads)
{
struct input_dev *dev;
int tmp, i, j;
tmp = (id == 0x41) ? 60 : 10;
for (j = 0; j < tmp && n < max_pads; j += 10, n++) {
dev = devs[n];
switch (data[j]) {
case 0x16: /* multi controller (analog 4 axis) */
input_report_abs(dev, db9_abs[5], data[j + 6]);
fallthrough;
case 0x15: /* mission stick (analog 3 axis) */
input_report_abs(dev, db9_abs[3], data[j + 4]);
input_report_abs(dev, db9_abs[4], data[j + 5]);
fallthrough;
case 0x13: /* racing controller (analog 1 axis) */
input_report_abs(dev, db9_abs[2], data[j + 3]);
fallthrough;
case 0x34: /* saturn keyboard (udlr ZXC ASD QE Esc) */
case 0x02: /* digital pad (digital 2 axis + buttons) */
input_report_abs(dev, db9_abs[0], !(data[j + 1] & 128) - !(data[j + 1] & 64));
input_report_abs(dev, db9_abs[1], !(data[j + 1] & 32) - !(data[j + 1] & 16));
for (i = 0; i < 9; i++)
input_report_key(dev, db9_cd32_btn[i], ~data[j + db9_saturn_byte[i]] & db9_saturn_mask[i]);
break;
case 0x19: /* mission stick x2 (analog 6 axis + buttons) */
input_report_abs(dev, db9_abs[0], !(data[j + 1] & 128) - !(data[j + 1] & 64));
input_report_abs(dev, db9_abs[1], !(data[j + 1] & 32) - !(data[j + 1] & 16));
for (i = 0; i < 9; i++)
input_report_key(dev, db9_cd32_btn[i], ~data[j + db9_saturn_byte[i]] & db9_saturn_mask[i]);
input_report_abs(dev, db9_abs[2], data[j + 3]);
input_report_abs(dev, db9_abs[3], data[j + 4]);
input_report_abs(dev, db9_abs[4], data[j + 5]);
/*
input_report_abs(dev, db9_abs[8], (data[j + 6] & 128 ? 0 : 1) - (data[j + 6] & 64 ? 0 : 1));
input_report_abs(dev, db9_abs[9], (data[j + 6] & 32 ? 0 : 1) - (data[j + 6] & 16 ? 0 : 1));
*/
input_report_abs(dev, db9_abs[6], data[j + 7]);
input_report_abs(dev, db9_abs[7], data[j + 8]);
input_report_abs(dev, db9_abs[5], data[j + 9]);
break;
case 0xd3: /* sankyo ff (analog 1 axis + stop btn) */
input_report_key(dev, BTN_A, data[j + 3] & 0x80);
input_report_abs(dev, db9_abs[2], data[j + 3] & 0x7f);
break;
case 0xe3: /* shuttle mouse (analog 2 axis + buttons. signed value) */
input_report_key(dev, BTN_START, data[j + 1] & 0x08);
input_report_key(dev, BTN_A, data[j + 1] & 0x04);
input_report_key(dev, BTN_C, data[j + 1] & 0x02);
input_report_key(dev, BTN_B, data[j + 1] & 0x01);
input_report_abs(dev, db9_abs[2], data[j + 2] ^ 0x80);
input_report_abs(dev, db9_abs[3], (0xff-(data[j + 3] ^ 0x80))+1); /* */
break;
case 0xff:
default: /* no pad */
input_report_abs(dev, db9_abs[0], 0);
input_report_abs(dev, db9_abs[1], 0);
for (i = 0; i < 9; i++)
input_report_key(dev, db9_cd32_btn[i], 0);
break;
}
}
return n;
}
static int db9_saturn(int mode, struct parport *port, struct input_dev *devs[])
{
unsigned char id, data[60];
int type, n, max_pads;
int tmp, i;
switch (mode) {
case DB9_SATURN_PAD:
type = 0;
n = 1;
break;
case DB9_SATURN_DPP:
type = 1;
n = 1;
break;
case DB9_SATURN_DPP_2:
type = 1;
n = 2;
break;
default:
return -1;
}
max_pads = min(db9_modes[mode].n_pads, DB9_MAX_DEVICES);
for (tmp = 0, i = 0; i < n; i++) {
id = db9_saturn_read_packet(port, data, type + i, 1);
tmp = db9_saturn_report(id, data, devs, tmp, max_pads);
}
return 0;
}
static void db9_timer(struct timer_list *t)
{
struct db9 *db9 = from_timer(db9, t, timer);
struct parport *port = db9->pd->port;
struct input_dev *dev = db9->dev[0];
struct input_dev *dev2 = db9->dev[1];
int data, i;
switch (db9->mode) {
case DB9_MULTI_0802_2:
data = parport_read_data(port) >> 3;
input_report_abs(dev2, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev2, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
input_report_key(dev2, BTN_TRIGGER, ~data & DB9_FIRE1);
fallthrough;
case DB9_MULTI_0802:
data = parport_read_status(port) >> 3;
input_report_abs(dev, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
input_report_key(dev, BTN_TRIGGER, data & DB9_FIRE1);
break;
case DB9_MULTI_STICK:
data = parport_read_data(port);
input_report_abs(dev, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
input_report_key(dev, BTN_TRIGGER, ~data & DB9_FIRE1);
break;
case DB9_MULTI2_STICK:
data = parport_read_data(port);
input_report_abs(dev, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
input_report_key(dev, BTN_TRIGGER, ~data & DB9_FIRE1);
input_report_key(dev, BTN_THUMB, ~data & DB9_FIRE2);
break;
case DB9_GENESIS_PAD:
parport_write_control(port, DB9_NOSELECT);
data = parport_read_data(port);
input_report_abs(dev, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
input_report_key(dev, BTN_B, ~data & DB9_FIRE1);
input_report_key(dev, BTN_C, ~data & DB9_FIRE2);
parport_write_control(port, DB9_NORMAL);
data = parport_read_data(port);
input_report_key(dev, BTN_A, ~data & DB9_FIRE1);
input_report_key(dev, BTN_START, ~data & DB9_FIRE2);
break;
case DB9_GENESIS5_PAD:
parport_write_control(port, DB9_NOSELECT);
data = parport_read_data(port);
input_report_abs(dev, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
input_report_key(dev, BTN_B, ~data & DB9_FIRE1);
input_report_key(dev, BTN_C, ~data & DB9_FIRE2);
parport_write_control(port, DB9_NORMAL);
data = parport_read_data(port);
input_report_key(dev, BTN_A, ~data & DB9_FIRE1);
input_report_key(dev, BTN_X, ~data & DB9_FIRE2);
input_report_key(dev, BTN_Y, ~data & DB9_LEFT);
input_report_key(dev, BTN_START, ~data & DB9_RIGHT);
break;
case DB9_GENESIS6_PAD:
parport_write_control(port, DB9_NOSELECT); /* 1 */
udelay(DB9_GENESIS6_DELAY);
data = parport_read_data(port);
input_report_abs(dev, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
input_report_key(dev, BTN_B, ~data & DB9_FIRE1);
input_report_key(dev, BTN_C, ~data & DB9_FIRE2);
parport_write_control(port, DB9_NORMAL);
udelay(DB9_GENESIS6_DELAY);
data = parport_read_data(port);
input_report_key(dev, BTN_A, ~data & DB9_FIRE1);
input_report_key(dev, BTN_START, ~data & DB9_FIRE2);
parport_write_control(port, DB9_NOSELECT); /* 2 */
udelay(DB9_GENESIS6_DELAY);
parport_write_control(port, DB9_NORMAL);
udelay(DB9_GENESIS6_DELAY);
parport_write_control(port, DB9_NOSELECT); /* 3 */
udelay(DB9_GENESIS6_DELAY);
data=parport_read_data(port);
input_report_key(dev, BTN_X, ~data & DB9_LEFT);
input_report_key(dev, BTN_Y, ~data & DB9_DOWN);
input_report_key(dev, BTN_Z, ~data & DB9_UP);
input_report_key(dev, BTN_MODE, ~data & DB9_RIGHT);
parport_write_control(port, DB9_NORMAL);
udelay(DB9_GENESIS6_DELAY);
parport_write_control(port, DB9_NOSELECT); /* 4 */
udelay(DB9_GENESIS6_DELAY);
parport_write_control(port, DB9_NORMAL);
break;
case DB9_SATURN_PAD:
case DB9_SATURN_DPP:
case DB9_SATURN_DPP_2:
db9_saturn(db9->mode, port, db9->dev);
break;
case DB9_CD32_PAD:
data = parport_read_data(port);
input_report_abs(dev, ABS_X, (data & DB9_RIGHT ? 0 : 1) - (data & DB9_LEFT ? 0 : 1));
input_report_abs(dev, ABS_Y, (data & DB9_DOWN ? 0 : 1) - (data & DB9_UP ? 0 : 1));
parport_write_control(port, 0x0a);
for (i = 0; i < 7; i++) {
data = parport_read_data(port);
parport_write_control(port, 0x02);
parport_write_control(port, 0x0a);
input_report_key(dev, db9_cd32_btn[i], ~data & DB9_FIRE2);
}
parport_write_control(port, 0x00);
break;
}
input_sync(dev);
mod_timer(&db9->timer, jiffies + DB9_REFRESH_TIME);
}
static int db9_open(struct input_dev *dev)
{
struct db9 *db9 = input_get_drvdata(dev);
struct parport *port = db9->pd->port;
int err;
err = mutex_lock_interruptible(&db9->mutex);
if (err)
return err;
if (!db9->used++) {
parport_claim(db9->pd);
parport_write_data(port, 0xff);
if (db9_modes[db9->mode].reverse) {
parport_data_reverse(port);
parport_write_control(port, DB9_NORMAL);
}
mod_timer(&db9->timer, jiffies + DB9_REFRESH_TIME);
}
mutex_unlock(&db9->mutex);
return 0;
}
static void db9_close(struct input_dev *dev)
{
struct db9 *db9 = input_get_drvdata(dev);
struct parport *port = db9->pd->port;
mutex_lock(&db9->mutex);
if (!--db9->used) {
del_timer_sync(&db9->timer);
parport_write_control(port, 0x00);
parport_data_forward(port);
parport_release(db9->pd);
}
mutex_unlock(&db9->mutex);
}
static void db9_attach(struct parport *pp)
{
struct db9 *db9;
const struct db9_mode_data *db9_mode;
struct pardevice *pd;
struct input_dev *input_dev;
int i, j, port_idx;
int mode;
struct pardev_cb db9_parport_cb;
for (port_idx = 0; port_idx < DB9_MAX_PORTS; port_idx++) {
if (db9_cfg[port_idx].nargs == 0 ||
db9_cfg[port_idx].args[DB9_ARG_PARPORT] < 0)
continue;
if (db9_cfg[port_idx].args[DB9_ARG_PARPORT] == pp->number)
break;
}
if (port_idx == DB9_MAX_PORTS) {
pr_debug("Not using parport%d.\n", pp->number);
return;
}
mode = db9_cfg[port_idx].args[DB9_ARG_MODE];
if (mode < 1 || mode >= DB9_MAX_PAD || !db9_modes[mode].n_buttons) {
printk(KERN_ERR "db9.c: Bad device type %d\n", mode);
return;
}
db9_mode = &db9_modes[mode];
if (db9_mode->bidirectional && !(pp->modes & PARPORT_MODE_TRISTATE)) {
printk(KERN_ERR "db9.c: specified parport is not bidirectional\n");
return;
}
memset(&db9_parport_cb, 0, sizeof(db9_parport_cb));
db9_parport_cb.flags = PARPORT_FLAG_EXCL;
pd = parport_register_dev_model(pp, "db9", &db9_parport_cb, port_idx);
if (!pd) {
printk(KERN_ERR "db9.c: parport busy already - lp.o loaded?\n");
return;
}
db9 = kzalloc(sizeof(struct db9), GFP_KERNEL);
if (!db9)
goto err_unreg_pardev;
mutex_init(&db9->mutex);
db9->pd = pd;
db9->mode = mode;
db9->parportno = pp->number;
timer_setup(&db9->timer, db9_timer, 0);
for (i = 0; i < (min(db9_mode->n_pads, DB9_MAX_DEVICES)); i++) {
db9->dev[i] = input_dev = input_allocate_device();
if (!input_dev) {
printk(KERN_ERR "db9.c: Not enough memory for input device\n");
goto err_unreg_devs;
}
snprintf(db9->phys[i], sizeof(db9->phys[i]),
"%s/input%d", db9->pd->port->name, i);
input_dev->name = db9_mode->name;
input_dev->phys = db9->phys[i];
input_dev->id.bustype = BUS_PARPORT;
input_dev->id.vendor = 0x0002;
input_dev->id.product = mode;
input_dev->id.version = 0x0100;
input_set_drvdata(input_dev, db9);
input_dev->open = db9_open;
input_dev->close = db9_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (j = 0; j < db9_mode->n_buttons; j++)
set_bit(db9_mode->buttons[j], input_dev->keybit);
for (j = 0; j < db9_mode->n_axis; j++) {
if (j < 2)
input_set_abs_params(input_dev, db9_abs[j], -1, 1, 0, 0);
else
input_set_abs_params(input_dev, db9_abs[j], 1, 255, 0, 0);
}
if (input_register_device(input_dev))
goto err_free_dev;
}
db9_base[port_idx] = db9;
return;
err_free_dev:
input_free_device(db9->dev[i]);
err_unreg_devs:
while (--i >= 0)
input_unregister_device(db9->dev[i]);
kfree(db9);
err_unreg_pardev:
parport_unregister_device(pd);
}
static void db9_detach(struct parport *port)
{
int i;
struct db9 *db9;
for (i = 0; i < DB9_MAX_PORTS; i++) {
if (db9_base[i] && db9_base[i]->parportno == port->number)
break;
}
if (i == DB9_MAX_PORTS)
return;
db9 = db9_base[i];
db9_base[i] = NULL;
for (i = 0; i < min(db9_modes[db9->mode].n_pads, DB9_MAX_DEVICES); i++)
input_unregister_device(db9->dev[i]);
parport_unregister_device(db9->pd);
kfree(db9);
}
static struct parport_driver db9_parport_driver = {
.name = "db9",
.match_port = db9_attach,
.detach = db9_detach,
.devmodel = true,
};
static int __init db9_init(void)
{
int i;
int have_dev = 0;
for (i = 0; i < DB9_MAX_PORTS; i++) {
if (db9_cfg[i].nargs == 0 || db9_cfg[i].args[DB9_ARG_PARPORT] < 0)
continue;
if (db9_cfg[i].nargs < 2) {
printk(KERN_ERR "db9.c: Device type must be specified.\n");
return -EINVAL;
}
have_dev = 1;
}
if (!have_dev)
return -ENODEV;
return parport_register_driver(&db9_parport_driver);
}
static void __exit db9_exit(void)
{
parport_unregister_driver(&db9_parport_driver);
}
module_init(db9_init);
module_exit(db9_exit);
|
linux-master
|
drivers/input/joystick/db9.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2001 Vojtech Pavlik
*/
/*
* Driver for Amiga joysticks for Linux/m68k
*/
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/mutex.h>
#include <asm/amigahw.h>
#include <asm/amigaints.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("Driver for Amiga joysticks");
MODULE_LICENSE("GPL");
static int amijoy[2] = { 0, 1 };
module_param_array_named(map, amijoy, uint, NULL, 0);
MODULE_PARM_DESC(map, "Map of attached joysticks in form of <a>,<b> (default is 0,1)");
static int amijoy_used;
static DEFINE_MUTEX(amijoy_mutex);
static struct input_dev *amijoy_dev[2];
static char *amijoy_phys[2] = { "amijoy/input0", "amijoy/input1" };
static irqreturn_t amijoy_interrupt(int irq, void *dummy)
{
int i, data = 0, button = 0;
for (i = 0; i < 2; i++)
if (amijoy[i]) {
switch (i) {
case 0: data = ~amiga_custom.joy0dat; button = (~ciaa.pra >> 6) & 1; break;
case 1: data = ~amiga_custom.joy1dat; button = (~ciaa.pra >> 7) & 1; break;
}
input_report_key(amijoy_dev[i], BTN_TRIGGER, button);
input_report_abs(amijoy_dev[i], ABS_X, ((data >> 1) & 1) - ((data >> 9) & 1));
data = ~(data ^ (data << 1));
input_report_abs(amijoy_dev[i], ABS_Y, ((data >> 1) & 1) - ((data >> 9) & 1));
input_sync(amijoy_dev[i]);
}
return IRQ_HANDLED;
}
static int amijoy_open(struct input_dev *dev)
{
int err;
err = mutex_lock_interruptible(&amijoy_mutex);
if (err)
return err;
if (!amijoy_used && request_irq(IRQ_AMIGA_VERTB, amijoy_interrupt, 0, "amijoy", amijoy_interrupt)) {
printk(KERN_ERR "amijoy.c: Can't allocate irq %d\n", IRQ_AMIGA_VERTB);
err = -EBUSY;
goto out;
}
amijoy_used++;
out:
mutex_unlock(&amijoy_mutex);
return err;
}
static void amijoy_close(struct input_dev *dev)
{
mutex_lock(&amijoy_mutex);
if (!--amijoy_used)
free_irq(IRQ_AMIGA_VERTB, amijoy_interrupt);
mutex_unlock(&amijoy_mutex);
}
static int __init amijoy_init(void)
{
int i, j;
int err;
if (!MACH_IS_AMIGA)
return -ENODEV;
for (i = 0; i < 2; i++) {
if (!amijoy[i])
continue;
amijoy_dev[i] = input_allocate_device();
if (!amijoy_dev[i]) {
err = -ENOMEM;
goto fail;
}
if (!request_mem_region(CUSTOM_PHYSADDR + 10 + i * 2, 2, "amijoy [Denise]")) {
input_free_device(amijoy_dev[i]);
err = -EBUSY;
goto fail;
}
amijoy_dev[i]->name = "Amiga joystick";
amijoy_dev[i]->phys = amijoy_phys[i];
amijoy_dev[i]->id.bustype = BUS_AMIGA;
amijoy_dev[i]->id.vendor = 0x0001;
amijoy_dev[i]->id.product = 0x0003;
amijoy_dev[i]->id.version = 0x0100;
amijoy_dev[i]->open = amijoy_open;
amijoy_dev[i]->close = amijoy_close;
amijoy_dev[i]->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
amijoy_dev[i]->absbit[0] = BIT_MASK(ABS_X) | BIT_MASK(ABS_Y);
amijoy_dev[i]->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) |
BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT);
for (j = 0; j < 2; j++) {
input_set_abs_params(amijoy_dev[i], ABS_X + j,
-1, 1, 0, 0);
}
err = input_register_device(amijoy_dev[i]);
if (err) {
input_free_device(amijoy_dev[i]);
goto fail;
}
}
return 0;
fail: while (--i >= 0)
if (amijoy[i]) {
input_unregister_device(amijoy_dev[i]);
release_mem_region(CUSTOM_PHYSADDR + 10 + i * 2, 2);
}
return err;
}
static void __exit amijoy_exit(void)
{
int i;
for (i = 0; i < 2; i++)
if (amijoy[i]) {
input_unregister_device(amijoy_dev[i]);
release_mem_region(CUSTOM_PHYSADDR + 10 + i * 2, 2);
}
}
module_init(amijoy_init);
module_exit(amijoy_exit);
|
linux-master
|
drivers/input/joystick/amijoy.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2001 Vojtech Pavlik
*/
/*
* Guillemot Digital Interface Protocol driver for Linux
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/gameport.h>
#include <linux/input.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "Guillemot Digital joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define GUILLEMOT_MAX_START 600 /* 600 us */
#define GUILLEMOT_MAX_STROBE 60 /* 60 us */
#define GUILLEMOT_MAX_LENGTH 17 /* 17 bytes */
static short guillemot_abs_pad[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, -1 };
static short guillemot_btn_pad[] =
{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_MODE, BTN_SELECT, -1 };
static struct {
int x;
int y;
} guillemot_hat_to_axis[16] = {{ 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}};
struct guillemot_type {
unsigned char id;
short *abs;
short *btn;
int hat;
char *name;
};
struct guillemot {
struct gameport *gameport;
struct input_dev *dev;
int bads;
int reads;
struct guillemot_type *type;
unsigned char length;
char phys[32];
};
static struct guillemot_type guillemot_type[] = {
{ 0x00, guillemot_abs_pad, guillemot_btn_pad, 1, "Guillemot Pad" },
{ 0 }};
/*
* guillemot_read_packet() reads Guillemot joystick data.
*/
static int guillemot_read_packet(struct gameport *gameport, u8 *data)
{
unsigned long flags;
unsigned char u, v;
unsigned int t, s;
int i;
for (i = 0; i < GUILLEMOT_MAX_LENGTH; i++)
data[i] = 0;
i = 0;
t = gameport_time(gameport, GUILLEMOT_MAX_START);
s = gameport_time(gameport, GUILLEMOT_MAX_STROBE);
local_irq_save(flags);
gameport_trigger(gameport);
v = gameport_read(gameport);
while (t > 0 && i < GUILLEMOT_MAX_LENGTH * 8) {
t--;
u = v; v = gameport_read(gameport);
if (v & ~u & 0x10) {
data[i >> 3] |= ((v >> 5) & 1) << (i & 7);
i++;
t = s;
}
}
local_irq_restore(flags);
return i;
}
/*
* guillemot_poll() reads and analyzes Guillemot joystick data.
*/
static void guillemot_poll(struct gameport *gameport)
{
struct guillemot *guillemot = gameport_get_drvdata(gameport);
struct input_dev *dev = guillemot->dev;
u8 data[GUILLEMOT_MAX_LENGTH];
int i;
guillemot->reads++;
if (guillemot_read_packet(guillemot->gameport, data) != GUILLEMOT_MAX_LENGTH * 8 ||
data[0] != 0x55 || data[16] != 0xaa) {
guillemot->bads++;
} else {
for (i = 0; i < 6 && guillemot->type->abs[i] >= 0; i++)
input_report_abs(dev, guillemot->type->abs[i], data[i + 5]);
if (guillemot->type->hat) {
input_report_abs(dev, ABS_HAT0X, guillemot_hat_to_axis[data[4] >> 4].x);
input_report_abs(dev, ABS_HAT0Y, guillemot_hat_to_axis[data[4] >> 4].y);
}
for (i = 0; i < 16 && guillemot->type->btn[i] >= 0; i++)
input_report_key(dev, guillemot->type->btn[i], (data[2 + (i >> 3)] >> (i & 7)) & 1);
}
input_sync(dev);
}
/*
* guillemot_open() is a callback from the input open routine.
*/
static int guillemot_open(struct input_dev *dev)
{
struct guillemot *guillemot = input_get_drvdata(dev);
gameport_start_polling(guillemot->gameport);
return 0;
}
/*
* guillemot_close() is a callback from the input close routine.
*/
static void guillemot_close(struct input_dev *dev)
{
struct guillemot *guillemot = input_get_drvdata(dev);
gameport_stop_polling(guillemot->gameport);
}
/*
* guillemot_connect() probes for Guillemot joysticks.
*/
static int guillemot_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct guillemot *guillemot;
struct input_dev *input_dev;
u8 data[GUILLEMOT_MAX_LENGTH];
int i, t;
int err;
guillemot = kzalloc(sizeof(struct guillemot), GFP_KERNEL);
input_dev = input_allocate_device();
if (!guillemot || !input_dev) {
err = -ENOMEM;
goto fail1;
}
guillemot->gameport = gameport;
guillemot->dev = input_dev;
gameport_set_drvdata(gameport, guillemot);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
i = guillemot_read_packet(gameport, data);
if (i != GUILLEMOT_MAX_LENGTH * 8 || data[0] != 0x55 || data[16] != 0xaa) {
err = -ENODEV;
goto fail2;
}
for (i = 0; guillemot_type[i].name; i++)
if (guillemot_type[i].id == data[11])
break;
if (!guillemot_type[i].name) {
printk(KERN_WARNING "guillemot.c: Unknown joystick on %s. [ %02x%02x:%04x, ver %d.%02d ]\n",
gameport->phys, data[12], data[13], data[11], data[14], data[15]);
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, guillemot_poll);
gameport_set_poll_interval(gameport, 20);
snprintf(guillemot->phys, sizeof(guillemot->phys), "%s/input0", gameport->phys);
guillemot->type = guillemot_type + i;
input_dev->name = guillemot_type[i].name;
input_dev->phys = guillemot->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_GUILLEMOT;
input_dev->id.product = guillemot_type[i].id;
input_dev->id.version = (int)data[14] << 8 | data[15];
input_dev->dev.parent = &gameport->dev;
input_set_drvdata(input_dev, guillemot);
input_dev->open = guillemot_open;
input_dev->close = guillemot_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; (t = guillemot->type->abs[i]) >= 0; i++)
input_set_abs_params(input_dev, t, 0, 255, 0, 0);
if (guillemot->type->hat) {
input_set_abs_params(input_dev, ABS_HAT0X, -1, 1, 0, 0);
input_set_abs_params(input_dev, ABS_HAT0Y, -1, 1, 0, 0);
}
for (i = 0; (t = guillemot->type->btn[i]) >= 0; i++)
set_bit(t, input_dev->keybit);
err = input_register_device(guillemot->dev);
if (err)
goto fail2;
return 0;
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
input_free_device(input_dev);
kfree(guillemot);
return err;
}
static void guillemot_disconnect(struct gameport *gameport)
{
struct guillemot *guillemot = gameport_get_drvdata(gameport);
printk(KERN_INFO "guillemot.c: Failed %d reads out of %d on %s\n", guillemot->reads, guillemot->bads, guillemot->phys);
input_unregister_device(guillemot->dev);
gameport_close(gameport);
kfree(guillemot);
}
static struct gameport_driver guillemot_drv = {
.driver = {
.name = "guillemot",
},
.description = DRIVER_DESC,
.connect = guillemot_connect,
.disconnect = guillemot_disconnect,
};
module_gameport_driver(guillemot_drv);
|
linux-master
|
drivers/input/joystick/guillemot.c
|
// SPDX-License-Identifier: GPL-2.0
/*
* Input driver for joysticks connected over ADC.
* Copyright (c) 2019-2020 Artur Rojek <[email protected]>
*/
#include <linux/ctype.h>
#include <linux/input.h>
#include <linux/iio/iio.h>
#include <linux/iio/consumer.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/property.h>
#include <asm/unaligned.h>
struct adc_joystick_axis {
u32 code;
s32 range[2];
s32 fuzz;
s32 flat;
};
struct adc_joystick {
struct input_dev *input;
struct iio_cb_buffer *buffer;
struct adc_joystick_axis *axes;
struct iio_channel *chans;
int num_chans;
bool polled;
};
static void adc_joystick_poll(struct input_dev *input)
{
struct adc_joystick *joy = input_get_drvdata(input);
int i, val, ret;
for (i = 0; i < joy->num_chans; i++) {
ret = iio_read_channel_raw(&joy->chans[i], &val);
if (ret < 0)
return;
input_report_abs(input, joy->axes[i].code, val);
}
input_sync(input);
}
static int adc_joystick_handle(const void *data, void *private)
{
struct adc_joystick *joy = private;
enum iio_endian endianness;
int bytes, msb, val, idx, i;
const u16 *data_u16;
bool sign;
bytes = joy->chans[0].channel->scan_type.storagebits >> 3;
for (i = 0; i < joy->num_chans; ++i) {
idx = joy->chans[i].channel->scan_index;
endianness = joy->chans[i].channel->scan_type.endianness;
msb = joy->chans[i].channel->scan_type.realbits - 1;
sign = tolower(joy->chans[i].channel->scan_type.sign) == 's';
switch (bytes) {
case 1:
val = ((const u8 *)data)[idx];
break;
case 2:
data_u16 = (const u16 *)data + idx;
/*
* Data is aligned to the sample size by IIO core.
* Call `get_unaligned_xe16` to hide type casting.
*/
if (endianness == IIO_BE)
val = get_unaligned_be16(data_u16);
else if (endianness == IIO_LE)
val = get_unaligned_le16(data_u16);
else /* IIO_CPU */
val = *data_u16;
break;
default:
return -EINVAL;
}
val >>= joy->chans[i].channel->scan_type.shift;
if (sign)
val = sign_extend32(val, msb);
else
val &= GENMASK(msb, 0);
input_report_abs(joy->input, joy->axes[i].code, val);
}
input_sync(joy->input);
return 0;
}
static int adc_joystick_open(struct input_dev *dev)
{
struct adc_joystick *joy = input_get_drvdata(dev);
struct device *devp = &dev->dev;
int ret;
ret = iio_channel_start_all_cb(joy->buffer);
if (ret)
dev_err(devp, "Unable to start callback buffer: %d\n", ret);
return ret;
}
static void adc_joystick_close(struct input_dev *dev)
{
struct adc_joystick *joy = input_get_drvdata(dev);
iio_channel_stop_all_cb(joy->buffer);
}
static void adc_joystick_cleanup(void *data)
{
iio_channel_release_all_cb(data);
}
static int adc_joystick_set_axes(struct device *dev, struct adc_joystick *joy)
{
struct adc_joystick_axis *axes;
struct fwnode_handle *child;
int num_axes, error, i;
num_axes = device_get_child_node_count(dev);
if (!num_axes) {
dev_err(dev, "Unable to find child nodes\n");
return -EINVAL;
}
if (num_axes != joy->num_chans) {
dev_err(dev, "Got %d child nodes for %d channels\n",
num_axes, joy->num_chans);
return -EINVAL;
}
axes = devm_kmalloc_array(dev, num_axes, sizeof(*axes), GFP_KERNEL);
if (!axes)
return -ENOMEM;
device_for_each_child_node(dev, child) {
error = fwnode_property_read_u32(child, "reg", &i);
if (error) {
dev_err(dev, "reg invalid or missing\n");
goto err_fwnode_put;
}
if (i >= num_axes) {
error = -EINVAL;
dev_err(dev, "No matching axis for reg %d\n", i);
goto err_fwnode_put;
}
error = fwnode_property_read_u32(child, "linux,code",
&axes[i].code);
if (error) {
dev_err(dev, "linux,code invalid or missing\n");
goto err_fwnode_put;
}
error = fwnode_property_read_u32_array(child, "abs-range",
axes[i].range, 2);
if (error) {
dev_err(dev, "abs-range invalid or missing\n");
goto err_fwnode_put;
}
fwnode_property_read_u32(child, "abs-fuzz", &axes[i].fuzz);
fwnode_property_read_u32(child, "abs-flat", &axes[i].flat);
input_set_abs_params(joy->input, axes[i].code,
axes[i].range[0], axes[i].range[1],
axes[i].fuzz, axes[i].flat);
input_set_capability(joy->input, EV_ABS, axes[i].code);
}
joy->axes = axes;
return 0;
err_fwnode_put:
fwnode_handle_put(child);
return error;
}
static int adc_joystick_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct adc_joystick *joy;
struct input_dev *input;
int error;
int bits;
int i;
unsigned int poll_interval;
joy = devm_kzalloc(dev, sizeof(*joy), GFP_KERNEL);
if (!joy)
return -ENOMEM;
joy->chans = devm_iio_channel_get_all(dev);
if (IS_ERR(joy->chans)) {
error = PTR_ERR(joy->chans);
if (error != -EPROBE_DEFER)
dev_err(dev, "Unable to get IIO channels");
return error;
}
error = device_property_read_u32(dev, "poll-interval", &poll_interval);
if (error) {
/* -EINVAL means the property is absent. */
if (error != -EINVAL)
return error;
} else if (poll_interval == 0) {
dev_err(dev, "Unable to get poll-interval\n");
return -EINVAL;
} else {
joy->polled = true;
}
/*
* Count how many channels we got. NULL terminated.
* Do not check the storage size if using polling.
*/
for (i = 0; joy->chans[i].indio_dev; i++) {
if (joy->polled)
continue;
bits = joy->chans[i].channel->scan_type.storagebits;
if (!bits || bits > 16) {
dev_err(dev, "Unsupported channel storage size\n");
return -EINVAL;
}
if (bits != joy->chans[0].channel->scan_type.storagebits) {
dev_err(dev, "Channels must have equal storage size\n");
return -EINVAL;
}
}
joy->num_chans = i;
input = devm_input_allocate_device(dev);
if (!input) {
dev_err(dev, "Unable to allocate input device\n");
return -ENOMEM;
}
joy->input = input;
input->name = pdev->name;
input->id.bustype = BUS_HOST;
error = adc_joystick_set_axes(dev, joy);
if (error)
return error;
if (joy->polled) {
input_setup_polling(input, adc_joystick_poll);
input_set_poll_interval(input, poll_interval);
} else {
input->open = adc_joystick_open;
input->close = adc_joystick_close;
joy->buffer = iio_channel_get_all_cb(dev, adc_joystick_handle,
joy);
if (IS_ERR(joy->buffer)) {
dev_err(dev, "Unable to allocate callback buffer\n");
return PTR_ERR(joy->buffer);
}
error = devm_add_action_or_reset(dev, adc_joystick_cleanup,
joy->buffer);
if (error) {
dev_err(dev, "Unable to add action\n");
return error;
}
}
input_set_drvdata(input, joy);
error = input_register_device(input);
if (error) {
dev_err(dev, "Unable to register input device\n");
return error;
}
return 0;
}
static const struct of_device_id adc_joystick_of_match[] = {
{ .compatible = "adc-joystick", },
{ }
};
MODULE_DEVICE_TABLE(of, adc_joystick_of_match);
static struct platform_driver adc_joystick_driver = {
.driver = {
.name = "adc-joystick",
.of_match_table = adc_joystick_of_match,
},
.probe = adc_joystick_probe,
};
module_platform_driver(adc_joystick_driver);
MODULE_DESCRIPTION("Input driver for joysticks connected over ADC");
MODULE_AUTHOR("Artur Rojek <[email protected]>");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/joystick/adc-joystick.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2001 Vojtech Pavlik
*
* Based on the work of:
* Steffen Schwenke
*/
/*
* TurboGraFX parallel port interface driver for Linux.
*/
#include <linux/kernel.h>
#include <linux/parport.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/slab.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("TurboGraFX parallel port interface driver");
MODULE_LICENSE("GPL");
#define TGFX_MAX_PORTS 3
#define TGFX_MAX_DEVICES 7
struct tgfx_config {
int args[TGFX_MAX_DEVICES + 1];
unsigned int nargs;
};
static struct tgfx_config tgfx_cfg[TGFX_MAX_PORTS];
module_param_array_named(map, tgfx_cfg[0].args, int, &tgfx_cfg[0].nargs, 0);
MODULE_PARM_DESC(map, "Describes first set of devices (<parport#>,<js1>,<js2>,..<js7>");
module_param_array_named(map2, tgfx_cfg[1].args, int, &tgfx_cfg[1].nargs, 0);
MODULE_PARM_DESC(map2, "Describes second set of devices");
module_param_array_named(map3, tgfx_cfg[2].args, int, &tgfx_cfg[2].nargs, 0);
MODULE_PARM_DESC(map3, "Describes third set of devices");
#define TGFX_REFRESH_TIME HZ/100 /* 10 ms */
#define TGFX_TRIGGER 0x08
#define TGFX_UP 0x10
#define TGFX_DOWN 0x20
#define TGFX_LEFT 0x40
#define TGFX_RIGHT 0x80
#define TGFX_THUMB 0x02
#define TGFX_THUMB2 0x04
#define TGFX_TOP 0x01
#define TGFX_TOP2 0x08
static int tgfx_buttons[] = { BTN_TRIGGER, BTN_THUMB, BTN_THUMB2, BTN_TOP, BTN_TOP2 };
static struct tgfx {
struct pardevice *pd;
struct timer_list timer;
struct input_dev *dev[TGFX_MAX_DEVICES];
char name[TGFX_MAX_DEVICES][64];
char phys[TGFX_MAX_DEVICES][32];
int sticks;
int used;
int parportno;
struct mutex sem;
} *tgfx_base[TGFX_MAX_PORTS];
/*
* tgfx_timer() reads and analyzes TurboGraFX joystick data.
*/
static void tgfx_timer(struct timer_list *t)
{
struct tgfx *tgfx = from_timer(tgfx, t, timer);
struct input_dev *dev;
int data1, data2, i;
for (i = 0; i < 7; i++)
if (tgfx->sticks & (1 << i)) {
dev = tgfx->dev[i];
parport_write_data(tgfx->pd->port, ~(1 << i));
data1 = parport_read_status(tgfx->pd->port) ^ 0x7f;
data2 = parport_read_control(tgfx->pd->port) ^ 0x04; /* CAVEAT parport */
input_report_abs(dev, ABS_X, !!(data1 & TGFX_RIGHT) - !!(data1 & TGFX_LEFT));
input_report_abs(dev, ABS_Y, !!(data1 & TGFX_DOWN ) - !!(data1 & TGFX_UP ));
input_report_key(dev, BTN_TRIGGER, (data1 & TGFX_TRIGGER));
input_report_key(dev, BTN_THUMB, (data2 & TGFX_THUMB ));
input_report_key(dev, BTN_THUMB2, (data2 & TGFX_THUMB2 ));
input_report_key(dev, BTN_TOP, (data2 & TGFX_TOP ));
input_report_key(dev, BTN_TOP2, (data2 & TGFX_TOP2 ));
input_sync(dev);
}
mod_timer(&tgfx->timer, jiffies + TGFX_REFRESH_TIME);
}
static int tgfx_open(struct input_dev *dev)
{
struct tgfx *tgfx = input_get_drvdata(dev);
int err;
err = mutex_lock_interruptible(&tgfx->sem);
if (err)
return err;
if (!tgfx->used++) {
parport_claim(tgfx->pd);
parport_write_control(tgfx->pd->port, 0x04);
mod_timer(&tgfx->timer, jiffies + TGFX_REFRESH_TIME);
}
mutex_unlock(&tgfx->sem);
return 0;
}
static void tgfx_close(struct input_dev *dev)
{
struct tgfx *tgfx = input_get_drvdata(dev);
mutex_lock(&tgfx->sem);
if (!--tgfx->used) {
del_timer_sync(&tgfx->timer);
parport_write_control(tgfx->pd->port, 0x00);
parport_release(tgfx->pd);
}
mutex_unlock(&tgfx->sem);
}
/*
* tgfx_probe() probes for tg gamepads.
*/
static void tgfx_attach(struct parport *pp)
{
struct tgfx *tgfx;
struct input_dev *input_dev;
struct pardevice *pd;
int i, j, port_idx;
int *n_buttons, n_devs;
struct pardev_cb tgfx_parport_cb;
for (port_idx = 0; port_idx < TGFX_MAX_PORTS; port_idx++) {
if (tgfx_cfg[port_idx].nargs == 0 ||
tgfx_cfg[port_idx].args[0] < 0)
continue;
if (tgfx_cfg[port_idx].args[0] == pp->number)
break;
}
if (port_idx == TGFX_MAX_PORTS) {
pr_debug("Not using parport%d.\n", pp->number);
return;
}
n_buttons = tgfx_cfg[port_idx].args + 1;
n_devs = tgfx_cfg[port_idx].nargs - 1;
memset(&tgfx_parport_cb, 0, sizeof(tgfx_parport_cb));
tgfx_parport_cb.flags = PARPORT_FLAG_EXCL;
pd = parport_register_dev_model(pp, "turbografx", &tgfx_parport_cb,
port_idx);
if (!pd) {
pr_err("parport busy already - lp.o loaded?\n");
return;
}
tgfx = kzalloc(sizeof(struct tgfx), GFP_KERNEL);
if (!tgfx) {
printk(KERN_ERR "turbografx.c: Not enough memory\n");
goto err_unreg_pardev;
}
mutex_init(&tgfx->sem);
tgfx->pd = pd;
tgfx->parportno = pp->number;
timer_setup(&tgfx->timer, tgfx_timer, 0);
for (i = 0; i < n_devs; i++) {
if (n_buttons[i] < 1)
continue;
if (n_buttons[i] > ARRAY_SIZE(tgfx_buttons)) {
printk(KERN_ERR "turbografx.c: Invalid number of buttons %d\n", n_buttons[i]);
goto err_unreg_devs;
}
tgfx->dev[i] = input_dev = input_allocate_device();
if (!input_dev) {
printk(KERN_ERR "turbografx.c: Not enough memory for input device\n");
goto err_unreg_devs;
}
tgfx->sticks |= (1 << i);
snprintf(tgfx->name[i], sizeof(tgfx->name[i]),
"TurboGraFX %d-button Multisystem joystick", n_buttons[i]);
snprintf(tgfx->phys[i], sizeof(tgfx->phys[i]),
"%s/input%d", tgfx->pd->port->name, i);
input_dev->name = tgfx->name[i];
input_dev->phys = tgfx->phys[i];
input_dev->id.bustype = BUS_PARPORT;
input_dev->id.vendor = 0x0003;
input_dev->id.product = n_buttons[i];
input_dev->id.version = 0x0100;
input_set_drvdata(input_dev, tgfx);
input_dev->open = tgfx_open;
input_dev->close = tgfx_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_set_abs_params(input_dev, ABS_X, -1, 1, 0, 0);
input_set_abs_params(input_dev, ABS_Y, -1, 1, 0, 0);
for (j = 0; j < n_buttons[i]; j++)
set_bit(tgfx_buttons[j], input_dev->keybit);
if (input_register_device(tgfx->dev[i]))
goto err_free_dev;
}
if (!tgfx->sticks) {
printk(KERN_ERR "turbografx.c: No valid devices specified\n");
goto err_free_tgfx;
}
tgfx_base[port_idx] = tgfx;
return;
err_free_dev:
input_free_device(tgfx->dev[i]);
err_unreg_devs:
while (--i >= 0)
if (tgfx->dev[i])
input_unregister_device(tgfx->dev[i]);
err_free_tgfx:
kfree(tgfx);
err_unreg_pardev:
parport_unregister_device(pd);
}
static void tgfx_detach(struct parport *port)
{
int i;
struct tgfx *tgfx;
for (i = 0; i < TGFX_MAX_PORTS; i++) {
if (tgfx_base[i] && tgfx_base[i]->parportno == port->number)
break;
}
if (i == TGFX_MAX_PORTS)
return;
tgfx = tgfx_base[i];
tgfx_base[i] = NULL;
for (i = 0; i < TGFX_MAX_DEVICES; i++)
if (tgfx->dev[i])
input_unregister_device(tgfx->dev[i]);
parport_unregister_device(tgfx->pd);
kfree(tgfx);
}
static struct parport_driver tgfx_parport_driver = {
.name = "turbografx",
.match_port = tgfx_attach,
.detach = tgfx_detach,
.devmodel = true,
};
static int __init tgfx_init(void)
{
int i;
int have_dev = 0;
for (i = 0; i < TGFX_MAX_PORTS; i++) {
if (tgfx_cfg[i].nargs == 0 || tgfx_cfg[i].args[0] < 0)
continue;
if (tgfx_cfg[i].nargs < 2) {
printk(KERN_ERR "turbografx.c: at least one joystick must be specified\n");
return -EINVAL;
}
have_dev = 1;
}
if (!have_dev)
return -ENODEV;
return parport_register_driver(&tgfx_parport_driver);
}
static void __exit tgfx_exit(void)
{
parport_unregister_driver(&tgfx_parport_driver);
}
module_init(tgfx_init);
module_exit(tgfx_exit);
|
linux-master
|
drivers/input/joystick/turbografx.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2001 Vojtech Pavlik
*
* Based on the work of:
* Trystan Larey-Williams
*/
/*
* ThrustMaster DirectConnect (BSP) joystick family driver for Linux
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/gameport.h>
#include <linux/input.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "ThrustMaster DirectConnect joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define TMDC_MAX_START 600 /* 600 us */
#define TMDC_MAX_STROBE 60 /* 60 us */
#define TMDC_MAX_LENGTH 13
#define TMDC_MODE_M3DI 1
#define TMDC_MODE_3DRP 3
#define TMDC_MODE_AT 4
#define TMDC_MODE_FM 8
#define TMDC_MODE_FGP 163
#define TMDC_BYTE_ID 10
#define TMDC_BYTE_REV 11
#define TMDC_BYTE_DEF 12
#define TMDC_ABS 7
#define TMDC_ABS_HAT 4
#define TMDC_BTN 16
static const unsigned char tmdc_byte_a[16] = { 0, 1, 3, 4, 6, 7 };
static const unsigned char tmdc_byte_d[16] = { 2, 5, 8, 9 };
static const signed char tmdc_abs[TMDC_ABS] =
{ ABS_X, ABS_Y, ABS_RUDDER, ABS_THROTTLE, ABS_RX, ABS_RY, ABS_RZ };
static const signed char tmdc_abs_hat[TMDC_ABS_HAT] =
{ ABS_HAT0X, ABS_HAT0Y, ABS_HAT1X, ABS_HAT1Y };
static const signed char tmdc_abs_at[TMDC_ABS] =
{ ABS_X, ABS_Y, ABS_RUDDER, -1, ABS_THROTTLE };
static const signed char tmdc_abs_fm[TMDC_ABS] =
{ ABS_RX, ABS_RY, ABS_X, ABS_Y };
static const short tmdc_btn_pad[TMDC_BTN] =
{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_START, BTN_SELECT, BTN_TL, BTN_TR };
static const short tmdc_btn_joy[TMDC_BTN] =
{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_THUMB2, BTN_PINKIE,
BTN_BASE3, BTN_BASE4, BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z };
static const short tmdc_btn_fm[TMDC_BTN] =
{ BTN_TRIGGER, BTN_C, BTN_B, BTN_A, BTN_THUMB, BTN_X, BTN_Y, BTN_Z, BTN_TOP, BTN_TOP2 };
static const short tmdc_btn_at[TMDC_BTN] =
{ BTN_TRIGGER, BTN_THUMB2, BTN_PINKIE, BTN_THUMB, BTN_BASE6, BTN_BASE5, BTN_BASE4,
BTN_BASE3, BTN_BASE2, BTN_BASE };
static const struct {
int x;
int y;
} tmdc_hat_to_axis[] = {{ 0, 0}, { 1, 0}, { 0,-1}, {-1, 0}, { 0, 1}};
static const struct tmdc_model {
unsigned char id;
const char *name;
char abs;
char hats;
char btnc[4];
char btno[4];
const signed char *axes;
const short *buttons;
} tmdc_models[] = {
{ 1, "ThrustMaster Millennium 3D Inceptor", 6, 2, { 4, 2 }, { 4, 6 }, tmdc_abs, tmdc_btn_joy },
{ 3, "ThrustMaster Rage 3D Gamepad", 2, 0, { 8, 2 }, { 0, 0 }, tmdc_abs, tmdc_btn_pad },
{ 4, "ThrustMaster Attack Throttle", 5, 2, { 4, 6 }, { 4, 2 }, tmdc_abs_at, tmdc_btn_at },
{ 8, "ThrustMaster FragMaster", 4, 0, { 8, 2 }, { 0, 0 }, tmdc_abs_fm, tmdc_btn_fm },
{ 163, "Thrustmaster Fusion GamePad", 2, 0, { 8, 2 }, { 0, 0 }, tmdc_abs, tmdc_btn_pad },
{ 0, "Unknown %d-axis, %d-button TM device %d", 0, 0, { 0, 0 }, { 0, 0 }, tmdc_abs, tmdc_btn_joy }
};
struct tmdc_port {
struct input_dev *dev;
char name[64];
char phys[32];
int mode;
const signed char *abs;
const short *btn;
unsigned char absc;
unsigned char btnc[4];
unsigned char btno[4];
};
struct tmdc {
struct gameport *gameport;
struct tmdc_port *port[2];
#if 0
struct input_dev *dev[2];
char name[2][64];
char phys[2][32];
int mode[2];
signed char *abs[2];
short *btn[2];
unsigned char absc[2];
unsigned char btnc[2][4];
unsigned char btno[2][4];
#endif
int reads;
int bads;
unsigned char exists;
};
/*
* tmdc_read_packet() reads a ThrustMaster packet.
*/
static int tmdc_read_packet(struct gameport *gameport, unsigned char data[2][TMDC_MAX_LENGTH])
{
unsigned char u, v, w, x;
unsigned long flags;
int i[2], j[2], t[2], p, k;
p = gameport_time(gameport, TMDC_MAX_STROBE);
for (k = 0; k < 2; k++) {
t[k] = gameport_time(gameport, TMDC_MAX_START);
i[k] = j[k] = 0;
}
local_irq_save(flags);
gameport_trigger(gameport);
w = gameport_read(gameport) >> 4;
do {
x = w;
w = gameport_read(gameport) >> 4;
for (k = 0, v = w, u = x; k < 2; k++, v >>= 2, u >>= 2) {
if (~v & u & 2) {
if (t[k] <= 0 || i[k] >= TMDC_MAX_LENGTH) continue;
t[k] = p;
if (j[k] == 0) { /* Start bit */
if (~v & 1) t[k] = 0;
data[k][i[k]] = 0; j[k]++; continue;
}
if (j[k] == 9) { /* Stop bit */
if (v & 1) t[k] = 0;
j[k] = 0; i[k]++; continue;
}
data[k][i[k]] |= (~v & 1) << (j[k]++ - 1); /* Data bit */
}
t[k]--;
}
} while (t[0] > 0 || t[1] > 0);
local_irq_restore(flags);
return (i[0] == TMDC_MAX_LENGTH) | ((i[1] == TMDC_MAX_LENGTH) << 1);
}
static int tmdc_parse_packet(struct tmdc_port *port, unsigned char *data)
{
int i, k, l;
if (data[TMDC_BYTE_ID] != port->mode)
return -1;
for (i = 0; i < port->absc; i++) {
if (port->abs[i] < 0)
return 0;
input_report_abs(port->dev, port->abs[i], data[tmdc_byte_a[i]]);
}
switch (port->mode) {
case TMDC_MODE_M3DI:
i = tmdc_byte_d[0];
input_report_abs(port->dev, ABS_HAT0X, ((data[i] >> 3) & 1) - ((data[i] >> 1) & 1));
input_report_abs(port->dev, ABS_HAT0Y, ((data[i] >> 2) & 1) - ( data[i] & 1));
break;
case TMDC_MODE_AT:
i = tmdc_byte_a[3];
input_report_abs(port->dev, ABS_HAT0X, tmdc_hat_to_axis[(data[i] - 141) / 25].x);
input_report_abs(port->dev, ABS_HAT0Y, tmdc_hat_to_axis[(data[i] - 141) / 25].y);
break;
}
for (k = l = 0; k < 4; k++) {
for (i = 0; i < port->btnc[k]; i++)
input_report_key(port->dev, port->btn[i + l],
((data[tmdc_byte_d[k]] >> (i + port->btno[k])) & 1));
l += port->btnc[k];
}
input_sync(port->dev);
return 0;
}
/*
* tmdc_poll() reads and analyzes ThrustMaster joystick data.
*/
static void tmdc_poll(struct gameport *gameport)
{
unsigned char data[2][TMDC_MAX_LENGTH];
struct tmdc *tmdc = gameport_get_drvdata(gameport);
unsigned char r, bad = 0;
int i;
tmdc->reads++;
if ((r = tmdc_read_packet(tmdc->gameport, data)) != tmdc->exists)
bad = 1;
else {
for (i = 0; i < 2; i++) {
if (r & (1 << i) & tmdc->exists) {
if (tmdc_parse_packet(tmdc->port[i], data[i]))
bad = 1;
}
}
}
tmdc->bads += bad;
}
static int tmdc_open(struct input_dev *dev)
{
struct tmdc *tmdc = input_get_drvdata(dev);
gameport_start_polling(tmdc->gameport);
return 0;
}
static void tmdc_close(struct input_dev *dev)
{
struct tmdc *tmdc = input_get_drvdata(dev);
gameport_stop_polling(tmdc->gameport);
}
static int tmdc_setup_port(struct tmdc *tmdc, int idx, unsigned char *data)
{
const struct tmdc_model *model;
struct tmdc_port *port;
struct input_dev *input_dev;
int i, j, b = 0;
int err;
tmdc->port[idx] = port = kzalloc(sizeof (struct tmdc_port), GFP_KERNEL);
input_dev = input_allocate_device();
if (!port || !input_dev) {
err = -ENOMEM;
goto fail;
}
port->mode = data[TMDC_BYTE_ID];
for (model = tmdc_models; model->id && model->id != port->mode; model++)
/* empty */;
port->abs = model->axes;
port->btn = model->buttons;
if (!model->id) {
port->absc = data[TMDC_BYTE_DEF] >> 4;
for (i = 0; i < 4; i++)
port->btnc[i] = i < (data[TMDC_BYTE_DEF] & 0xf) ? 8 : 0;
} else {
port->absc = model->abs;
for (i = 0; i < 4; i++)
port->btnc[i] = model->btnc[i];
}
for (i = 0; i < 4; i++)
port->btno[i] = model->btno[i];
snprintf(port->name, sizeof(port->name), model->name,
port->absc, (data[TMDC_BYTE_DEF] & 0xf) << 3, port->mode);
snprintf(port->phys, sizeof(port->phys), "%s/input%d", tmdc->gameport->phys, i);
port->dev = input_dev;
input_dev->name = port->name;
input_dev->phys = port->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_THRUSTMASTER;
input_dev->id.product = model->id;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &tmdc->gameport->dev;
input_set_drvdata(input_dev, tmdc);
input_dev->open = tmdc_open;
input_dev->close = tmdc_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; i < port->absc && i < TMDC_ABS; i++)
if (port->abs[i] >= 0)
input_set_abs_params(input_dev, port->abs[i], 8, 248, 2, 4);
for (i = 0; i < model->hats && i < TMDC_ABS_HAT; i++)
input_set_abs_params(input_dev, tmdc_abs_hat[i], -1, 1, 0, 0);
for (i = 0; i < 4; i++) {
for (j = 0; j < port->btnc[i] && j < TMDC_BTN; j++)
set_bit(port->btn[j + b], input_dev->keybit);
b += port->btnc[i];
}
err = input_register_device(port->dev);
if (err)
goto fail;
return 0;
fail: input_free_device(input_dev);
kfree(port);
return err;
}
/*
* tmdc_probe() probes for ThrustMaster type joysticks.
*/
static int tmdc_connect(struct gameport *gameport, struct gameport_driver *drv)
{
unsigned char data[2][TMDC_MAX_LENGTH];
struct tmdc *tmdc;
int i;
int err;
if (!(tmdc = kzalloc(sizeof(struct tmdc), GFP_KERNEL)))
return -ENOMEM;
tmdc->gameport = gameport;
gameport_set_drvdata(gameport, tmdc);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
if (!(tmdc->exists = tmdc_read_packet(gameport, data))) {
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, tmdc_poll);
gameport_set_poll_interval(gameport, 20);
for (i = 0; i < 2; i++) {
if (tmdc->exists & (1 << i)) {
err = tmdc_setup_port(tmdc, i, data[i]);
if (err)
goto fail3;
}
}
return 0;
fail3: while (--i >= 0) {
if (tmdc->port[i]) {
input_unregister_device(tmdc->port[i]->dev);
kfree(tmdc->port[i]);
}
}
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(tmdc);
return err;
}
static void tmdc_disconnect(struct gameport *gameport)
{
struct tmdc *tmdc = gameport_get_drvdata(gameport);
int i;
for (i = 0; i < 2; i++) {
if (tmdc->port[i]) {
input_unregister_device(tmdc->port[i]->dev);
kfree(tmdc->port[i]);
}
}
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(tmdc);
}
static struct gameport_driver tmdc_drv = {
.driver = {
.name = "tmdc",
.owner = THIS_MODULE,
},
.description = DRIVER_DESC,
.connect = tmdc_connect,
.disconnect = tmdc_disconnect,
};
module_gameport_driver(tmdc_drv);
|
linux-master
|
drivers/input/joystick/tmdc.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2005 Vojtech Pavlik
*/
/*
* Logitech ADI joystick family driver for Linux
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/gameport.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "Logitech ADI joystick family driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Times, array sizes, flags, ids.
*/
#define ADI_MAX_START 200 /* Trigger to packet timeout [200us] */
#define ADI_MAX_STROBE 40 /* Single bit timeout [40us] */
#define ADI_INIT_DELAY 10 /* Delay after init packet [10ms] */
#define ADI_DATA_DELAY 4 /* Delay after data packet [4ms] */
#define ADI_MAX_LENGTH 256
#define ADI_MIN_LENGTH 8
#define ADI_MIN_LEN_LENGTH 10
#define ADI_MIN_ID_LENGTH 66
#define ADI_MAX_NAME_LENGTH 64
#define ADI_MAX_CNAME_LENGTH 16
#define ADI_MAX_PHYS_LENGTH 64
#define ADI_FLAG_HAT 0x04
#define ADI_FLAG_10BIT 0x08
#define ADI_ID_TPD 0x01
#define ADI_ID_WGP 0x06
#define ADI_ID_WGPE 0x08
#define ADI_ID_MAX 0x0a
/*
* Names, buttons, axes ...
*/
static char *adi_names[] = { "WingMan Extreme Digital", "ThunderPad Digital", "SideCar", "CyberMan 2",
"WingMan Interceptor", "WingMan Formula", "WingMan GamePad",
"WingMan Extreme Digital 3D", "WingMan GamePad Extreme",
"WingMan GamePad USB", "Unknown Device %#x" };
static char adi_wmgpe_abs[] = { ABS_X, ABS_Y, ABS_HAT0X, ABS_HAT0Y };
static char adi_wmi_abs[] = { ABS_X, ABS_Y, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y, ABS_HAT1X, ABS_HAT1Y, ABS_HAT2X, ABS_HAT2Y };
static char adi_wmed3d_abs[] = { ABS_X, ABS_Y, ABS_THROTTLE, ABS_RZ, ABS_HAT0X, ABS_HAT0Y };
static char adi_cm2_abs[] = { ABS_X, ABS_Y, ABS_Z, ABS_RX, ABS_RY, ABS_RZ };
static char adi_wmf_abs[] = { ABS_WHEEL, ABS_GAS, ABS_BRAKE, ABS_HAT0X, ABS_HAT0Y, ABS_HAT1X, ABS_HAT1Y, ABS_HAT2X, ABS_HAT2Y };
static short adi_wmgpe_key[] = { BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START, BTN_MODE, BTN_SELECT };
static short adi_wmi_key[] = { BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_EXTRA };
static short adi_wmed3d_key[] = { BTN_TRIGGER, BTN_THUMB, BTN_THUMB2, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2 };
static short adi_cm2_key[] = { BTN_1, BTN_2, BTN_3, BTN_4, BTN_5, BTN_6, BTN_7, BTN_8 };
static char* adi_abs[] = { adi_wmi_abs, adi_wmgpe_abs, adi_wmf_abs, adi_cm2_abs, adi_wmi_abs, adi_wmf_abs,
adi_wmgpe_abs, adi_wmed3d_abs, adi_wmgpe_abs, adi_wmgpe_abs, adi_wmi_abs };
static short* adi_key[] = { adi_wmi_key, adi_wmgpe_key, adi_cm2_key, adi_cm2_key, adi_wmi_key, adi_cm2_key,
adi_wmgpe_key, adi_wmed3d_key, adi_wmgpe_key, adi_wmgpe_key, adi_wmi_key };
/*
* Hat to axis conversion arrays.
*/
static struct {
int x;
int y;
} adi_hat_to_axis[] = {{ 0, 0}, { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}};
/*
* Per-port information.
*/
struct adi {
struct input_dev *dev;
int length;
int ret;
int idx;
unsigned char id;
char buttons;
char axes10;
char axes8;
signed char pad;
char hats;
char *abs;
short *key;
char name[ADI_MAX_NAME_LENGTH];
char cname[ADI_MAX_CNAME_LENGTH];
char phys[ADI_MAX_PHYS_LENGTH];
unsigned char data[ADI_MAX_LENGTH];
};
struct adi_port {
struct gameport *gameport;
struct adi adi[2];
int bad;
int reads;
};
/*
* adi_read_packet() reads a Logitech ADI packet.
*/
static void adi_read_packet(struct adi_port *port)
{
struct adi *adi = port->adi;
struct gameport *gameport = port->gameport;
unsigned char u, v, w, x;
int t[2], s[2], i;
unsigned long flags;
for (i = 0; i < 2; i++) {
adi[i].ret = -1;
t[i] = gameport_time(gameport, ADI_MAX_START);
s[i] = 0;
}
local_irq_save(flags);
gameport_trigger(gameport);
v = gameport_read(gameport);
do {
u = v;
w = u ^ (v = x = gameport_read(gameport));
for (i = 0; i < 2; i++, w >>= 2, x >>= 2) {
t[i]--;
if ((w & 0x30) && s[i]) {
if ((w & 0x30) < 0x30 && adi[i].ret < ADI_MAX_LENGTH && t[i] > 0) {
adi[i].data[++adi[i].ret] = w;
t[i] = gameport_time(gameport, ADI_MAX_STROBE);
} else t[i] = 0;
} else if (!(x & 0x30)) s[i] = 1;
}
} while (t[0] > 0 || t[1] > 0);
local_irq_restore(flags);
return;
}
/*
* adi_move_bits() detects a possible 2-stream mode, and moves
* the bits accordingly.
*/
static void adi_move_bits(struct adi_port *port, int length)
{
int i;
struct adi *adi = port->adi;
adi[0].idx = adi[1].idx = 0;
if (adi[0].ret <= 0 || adi[1].ret <= 0) return;
if (adi[0].data[0] & 0x20 || ~adi[1].data[0] & 0x20) return;
for (i = 1; i <= adi[1].ret; i++)
adi[0].data[((length - 1) >> 1) + i + 1] = adi[1].data[i];
adi[0].ret += adi[1].ret;
adi[1].ret = -1;
}
/*
* adi_get_bits() gathers bits from the data packet.
*/
static inline int adi_get_bits(struct adi *adi, int count)
{
int bits = 0;
int i;
if ((adi->idx += count) > adi->ret) return 0;
for (i = 0; i < count; i++)
bits |= ((adi->data[adi->idx - i] >> 5) & 1) << i;
return bits;
}
/*
* adi_decode() decodes Logitech joystick data into input events.
*/
static int adi_decode(struct adi *adi)
{
struct input_dev *dev = adi->dev;
char *abs = adi->abs;
short *key = adi->key;
int i, t;
if (adi->ret < adi->length || adi->id != (adi_get_bits(adi, 4) | (adi_get_bits(adi, 4) << 4)))
return -1;
for (i = 0; i < adi->axes10; i++)
input_report_abs(dev, *abs++, adi_get_bits(adi, 10));
for (i = 0; i < adi->axes8; i++)
input_report_abs(dev, *abs++, adi_get_bits(adi, 8));
for (i = 0; i < adi->buttons && i < 63; i++) {
if (i == adi->pad) {
t = adi_get_bits(adi, 4);
input_report_abs(dev, *abs++, ((t >> 2) & 1) - ( t & 1));
input_report_abs(dev, *abs++, ((t >> 1) & 1) - ((t >> 3) & 1));
}
input_report_key(dev, *key++, adi_get_bits(adi, 1));
}
for (i = 0; i < adi->hats; i++) {
if ((t = adi_get_bits(adi, 4)) > 8) t = 0;
input_report_abs(dev, *abs++, adi_hat_to_axis[t].x);
input_report_abs(dev, *abs++, adi_hat_to_axis[t].y);
}
for (i = 63; i < adi->buttons; i++)
input_report_key(dev, *key++, adi_get_bits(adi, 1));
input_sync(dev);
return 0;
}
/*
* adi_read() reads the data packet and decodes it.
*/
static int adi_read(struct adi_port *port)
{
int i;
int result = 0;
adi_read_packet(port);
adi_move_bits(port, port->adi[0].length);
for (i = 0; i < 2; i++)
if (port->adi[i].length)
result |= adi_decode(port->adi + i);
return result;
}
/*
* adi_poll() repeatedly polls the Logitech joysticks.
*/
static void adi_poll(struct gameport *gameport)
{
struct adi_port *port = gameport_get_drvdata(gameport);
port->bad -= adi_read(port);
port->reads++;
}
/*
* adi_open() is a callback from the input open routine.
*/
static int adi_open(struct input_dev *dev)
{
struct adi_port *port = input_get_drvdata(dev);
gameport_start_polling(port->gameport);
return 0;
}
/*
* adi_close() is a callback from the input close routine.
*/
static void adi_close(struct input_dev *dev)
{
struct adi_port *port = input_get_drvdata(dev);
gameport_stop_polling(port->gameport);
}
/*
* adi_init_digital() sends a trigger & delay sequence
* to reset and initialize a Logitech joystick into digital mode.
*/
static void adi_init_digital(struct gameport *gameport)
{
static const int seq[] = { 4, -2, -3, 10, -6, -11, -7, -9, 11, 0 };
int i;
for (i = 0; seq[i]; i++) {
gameport_trigger(gameport);
if (seq[i] > 0)
msleep(seq[i]);
if (seq[i] < 0) {
mdelay(-seq[i]);
udelay(-seq[i]*14); /* It looks like mdelay() is off by approx 1.4% */
}
}
}
static void adi_id_decode(struct adi *adi, struct adi_port *port)
{
int i, t;
if (adi->ret < ADI_MIN_ID_LENGTH) /* Minimum ID packet length */
return;
if (adi->ret < (t = adi_get_bits(adi, 10))) {
printk(KERN_WARNING "adi: Short ID packet: reported: %d != read: %d\n", t, adi->ret);
return;
}
adi->id = adi_get_bits(adi, 4) | (adi_get_bits(adi, 4) << 4);
if ((t = adi_get_bits(adi, 4)) & ADI_FLAG_HAT) adi->hats++;
adi->length = adi_get_bits(adi, 10);
if (adi->length >= ADI_MAX_LENGTH || adi->length < ADI_MIN_LENGTH) {
printk(KERN_WARNING "adi: Bad data packet length (%d).\n", adi->length);
adi->length = 0;
return;
}
adi->axes8 = adi_get_bits(adi, 4);
adi->buttons = adi_get_bits(adi, 6);
if (adi_get_bits(adi, 6) != 8 && adi->hats) {
printk(KERN_WARNING "adi: Other than 8-dir POVs not supported yet.\n");
adi->length = 0;
return;
}
adi->buttons += adi_get_bits(adi, 6);
adi->hats += adi_get_bits(adi, 4);
i = adi_get_bits(adi, 4);
if (t & ADI_FLAG_10BIT) {
adi->axes10 = adi->axes8 - i;
adi->axes8 = i;
}
t = adi_get_bits(adi, 4);
for (i = 0; i < t; i++)
adi->cname[i] = adi_get_bits(adi, 8);
adi->cname[i] = 0;
t = 8 + adi->buttons + adi->axes10 * 10 + adi->axes8 * 8 + adi->hats * 4;
if (adi->length != t && adi->length != t + (t & 1)) {
printk(KERN_WARNING "adi: Expected length %d != data length %d\n", t, adi->length);
adi->length = 0;
return;
}
switch (adi->id) {
case ADI_ID_TPD:
adi->pad = 4;
adi->buttons -= 4;
break;
case ADI_ID_WGP:
adi->pad = 0;
adi->buttons -= 4;
break;
default:
adi->pad = -1;
break;
}
}
static int adi_init_input(struct adi *adi, struct adi_port *port, int half)
{
struct input_dev *input_dev;
char buf[ADI_MAX_NAME_LENGTH];
int i, t;
adi->dev = input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
t = adi->id < ADI_ID_MAX ? adi->id : ADI_ID_MAX;
snprintf(buf, ADI_MAX_PHYS_LENGTH, adi_names[t], adi->id);
snprintf(adi->name, ADI_MAX_NAME_LENGTH, "Logitech %s [%s]", buf, adi->cname);
snprintf(adi->phys, ADI_MAX_PHYS_LENGTH, "%s/input%d", port->gameport->phys, half);
adi->abs = adi_abs[t];
adi->key = adi_key[t];
input_dev->name = adi->name;
input_dev->phys = adi->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_LOGITECH;
input_dev->id.product = adi->id;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &port->gameport->dev;
input_set_drvdata(input_dev, port);
input_dev->open = adi_open;
input_dev->close = adi_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; i < adi->axes10 + adi->axes8 + (adi->hats + (adi->pad != -1)) * 2; i++)
set_bit(adi->abs[i], input_dev->absbit);
for (i = 0; i < adi->buttons; i++)
set_bit(adi->key[i], input_dev->keybit);
return 0;
}
static void adi_init_center(struct adi *adi)
{
int i, t, x;
if (!adi->length)
return;
for (i = 0; i < adi->axes10 + adi->axes8 + (adi->hats + (adi->pad != -1)) * 2; i++) {
t = adi->abs[i];
x = input_abs_get_val(adi->dev, t);
if (t == ABS_THROTTLE || t == ABS_RUDDER || adi->id == ADI_ID_WGPE)
x = i < adi->axes10 ? 512 : 128;
if (i < adi->axes10)
input_set_abs_params(adi->dev, t, 64, x * 2 - 64, 2, 16);
else if (i < adi->axes10 + adi->axes8)
input_set_abs_params(adi->dev, t, 48, x * 2 - 48, 1, 16);
else
input_set_abs_params(adi->dev, t, -1, 1, 0, 0);
}
}
/*
* adi_connect() probes for Logitech ADI joysticks.
*/
static int adi_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct adi_port *port;
int i;
int err;
port = kzalloc(sizeof(struct adi_port), GFP_KERNEL);
if (!port)
return -ENOMEM;
port->gameport = gameport;
gameport_set_drvdata(gameport, port);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
adi_init_digital(gameport);
adi_read_packet(port);
if (port->adi[0].ret >= ADI_MIN_LEN_LENGTH)
adi_move_bits(port, adi_get_bits(port->adi, 10));
for (i = 0; i < 2; i++) {
adi_id_decode(port->adi + i, port);
if (!port->adi[i].length)
continue;
err = adi_init_input(port->adi + i, port, i);
if (err)
goto fail2;
}
if (!port->adi[0].length && !port->adi[1].length) {
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, adi_poll);
gameport_set_poll_interval(gameport, 20);
msleep(ADI_INIT_DELAY);
if (adi_read(port)) {
msleep(ADI_DATA_DELAY);
adi_read(port);
}
for (i = 0; i < 2; i++)
if (port->adi[i].length > 0) {
adi_init_center(port->adi + i);
err = input_register_device(port->adi[i].dev);
if (err)
goto fail3;
}
return 0;
fail3: while (--i >= 0) {
if (port->adi[i].length > 0) {
input_unregister_device(port->adi[i].dev);
port->adi[i].dev = NULL;
}
}
fail2: for (i = 0; i < 2; i++)
input_free_device(port->adi[i].dev);
gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(port);
return err;
}
static void adi_disconnect(struct gameport *gameport)
{
int i;
struct adi_port *port = gameport_get_drvdata(gameport);
for (i = 0; i < 2; i++)
if (port->adi[i].length > 0)
input_unregister_device(port->adi[i].dev);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(port);
}
static struct gameport_driver adi_drv = {
.driver = {
.name = "adi",
},
.description = DRIVER_DESC,
.connect = adi_connect,
.disconnect = adi_disconnect,
};
module_gameport_driver(adi_drv);
|
linux-master
|
drivers/input/joystick/adi.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2001 Vojtech Pavlik
*
* Based on the work of:
* Toby Deshane
*/
/*
* InterAct digital gamepad/joystick driver for Linux
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/gameport.h>
#include <linux/input.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "InterAct digital joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define INTERACT_MAX_START 600 /* 400 us */
#define INTERACT_MAX_STROBE 60 /* 40 us */
#define INTERACT_MAX_LENGTH 32 /* 32 bits */
#define INTERACT_TYPE_HHFX 0 /* HammerHead/FX */
#define INTERACT_TYPE_PP8D 1 /* ProPad 8 */
struct interact {
struct gameport *gameport;
struct input_dev *dev;
int bads;
int reads;
unsigned char type;
unsigned char length;
char phys[32];
};
static short interact_abs_hhfx[] =
{ ABS_RX, ABS_RY, ABS_X, ABS_Y, ABS_HAT0X, ABS_HAT0Y, -1 };
static short interact_abs_pp8d[] =
{ ABS_X, ABS_Y, -1 };
static short interact_btn_hhfx[] =
{ BTN_TR, BTN_X, BTN_Y, BTN_Z, BTN_A, BTN_B, BTN_C, BTN_TL, BTN_TL2, BTN_TR2, BTN_MODE, BTN_SELECT, -1 };
static short interact_btn_pp8d[] =
{ BTN_C, BTN_TL, BTN_TR, BTN_A, BTN_B, BTN_Y, BTN_Z, BTN_X, -1 };
struct interact_type {
int id;
short *abs;
short *btn;
char *name;
unsigned char length;
unsigned char b8;
};
static struct interact_type interact_type[] = {
{ 0x6202, interact_abs_hhfx, interact_btn_hhfx, "InterAct HammerHead/FX", 32, 4 },
{ 0x53f8, interact_abs_pp8d, interact_btn_pp8d, "InterAct ProPad 8 Digital", 16, 0 },
{ 0 }};
/*
* interact_read_packet() reads and InterAct joystick data.
*/
static int interact_read_packet(struct gameport *gameport, int length, u32 *data)
{
unsigned long flags;
unsigned char u, v;
unsigned int t, s;
int i;
i = 0;
data[0] = data[1] = data[2] = 0;
t = gameport_time(gameport, INTERACT_MAX_START);
s = gameport_time(gameport, INTERACT_MAX_STROBE);
local_irq_save(flags);
gameport_trigger(gameport);
v = gameport_read(gameport);
while (t > 0 && i < length) {
t--;
u = v; v = gameport_read(gameport);
if (v & ~u & 0x40) {
data[0] = (data[0] << 1) | ((v >> 4) & 1);
data[1] = (data[1] << 1) | ((v >> 5) & 1);
data[2] = (data[2] << 1) | ((v >> 7) & 1);
i++;
t = s;
}
}
local_irq_restore(flags);
return i;
}
/*
* interact_poll() reads and analyzes InterAct joystick data.
*/
static void interact_poll(struct gameport *gameport)
{
struct interact *interact = gameport_get_drvdata(gameport);
struct input_dev *dev = interact->dev;
u32 data[3];
int i;
interact->reads++;
if (interact_read_packet(interact->gameport, interact->length, data) < interact->length) {
interact->bads++;
} else {
for (i = 0; i < 3; i++)
data[i] <<= INTERACT_MAX_LENGTH - interact->length;
switch (interact->type) {
case INTERACT_TYPE_HHFX:
for (i = 0; i < 4; i++)
input_report_abs(dev, interact_abs_hhfx[i], (data[i & 1] >> ((i >> 1) << 3)) & 0xff);
for (i = 0; i < 2; i++)
input_report_abs(dev, ABS_HAT0Y - i,
((data[1] >> ((i << 1) + 17)) & 1) - ((data[1] >> ((i << 1) + 16)) & 1));
for (i = 0; i < 8; i++)
input_report_key(dev, interact_btn_hhfx[i], (data[0] >> (i + 16)) & 1);
for (i = 0; i < 4; i++)
input_report_key(dev, interact_btn_hhfx[i + 8], (data[1] >> (i + 20)) & 1);
break;
case INTERACT_TYPE_PP8D:
for (i = 0; i < 2; i++)
input_report_abs(dev, interact_abs_pp8d[i],
((data[0] >> ((i << 1) + 20)) & 1) - ((data[0] >> ((i << 1) + 21)) & 1));
for (i = 0; i < 8; i++)
input_report_key(dev, interact_btn_pp8d[i], (data[1] >> (i + 16)) & 1);
break;
}
}
input_sync(dev);
}
/*
* interact_open() is a callback from the input open routine.
*/
static int interact_open(struct input_dev *dev)
{
struct interact *interact = input_get_drvdata(dev);
gameport_start_polling(interact->gameport);
return 0;
}
/*
* interact_close() is a callback from the input close routine.
*/
static void interact_close(struct input_dev *dev)
{
struct interact *interact = input_get_drvdata(dev);
gameport_stop_polling(interact->gameport);
}
/*
* interact_connect() probes for InterAct joysticks.
*/
static int interact_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct interact *interact;
struct input_dev *input_dev;
__u32 data[3];
int i, t;
int err;
interact = kzalloc(sizeof(struct interact), GFP_KERNEL);
input_dev = input_allocate_device();
if (!interact || !input_dev) {
err = -ENOMEM;
goto fail1;
}
interact->gameport = gameport;
interact->dev = input_dev;
gameport_set_drvdata(gameport, interact);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
i = interact_read_packet(gameport, INTERACT_MAX_LENGTH * 2, data);
if (i != 32 || (data[0] >> 24) != 0x0c || (data[1] >> 24) != 0x02) {
err = -ENODEV;
goto fail2;
}
for (i = 0; interact_type[i].length; i++)
if (interact_type[i].id == (data[2] >> 16))
break;
if (!interact_type[i].length) {
printk(KERN_WARNING "interact.c: Unknown joystick on %s. [len %d d0 %08x d1 %08x i2 %08x]\n",
gameport->phys, i, data[0], data[1], data[2]);
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, interact_poll);
gameport_set_poll_interval(gameport, 20);
snprintf(interact->phys, sizeof(interact->phys), "%s/input0", gameport->phys);
interact->type = i;
interact->length = interact_type[i].length;
input_dev->name = interact_type[i].name;
input_dev->phys = interact->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_INTERACT;
input_dev->id.product = interact_type[i].id;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &gameport->dev;
input_set_drvdata(input_dev, interact);
input_dev->open = interact_open;
input_dev->close = interact_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; (t = interact_type[interact->type].abs[i]) >= 0; i++) {
if (i < interact_type[interact->type].b8)
input_set_abs_params(input_dev, t, 0, 255, 0, 0);
else
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
}
for (i = 0; (t = interact_type[interact->type].btn[i]) >= 0; i++)
__set_bit(t, input_dev->keybit);
err = input_register_device(interact->dev);
if (err)
goto fail2;
return 0;
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
input_free_device(input_dev);
kfree(interact);
return err;
}
static void interact_disconnect(struct gameport *gameport)
{
struct interact *interact = gameport_get_drvdata(gameport);
input_unregister_device(interact->dev);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(interact);
}
static struct gameport_driver interact_drv = {
.driver = {
.name = "interact",
},
.description = DRIVER_DESC,
.connect = interact_connect,
.disconnect = interact_disconnect,
};
module_gameport_driver(interact_drv);
|
linux-master
|
drivers/input/joystick/interact.c
|
// SPDX-License-Identifier: GPL-2.0
/*
* Support for the four N64 controllers.
*
* Copyright (c) 2021 Lauri Kasanen
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/limits.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/timer.h>
MODULE_AUTHOR("Lauri Kasanen <[email protected]>");
MODULE_DESCRIPTION("Driver for N64 controllers");
MODULE_LICENSE("GPL");
#define PIF_RAM 0x1fc007c0
#define SI_DRAM_REG 0
#define SI_READ_REG 1
#define SI_WRITE_REG 4
#define SI_STATUS_REG 6
#define SI_STATUS_DMA_BUSY BIT(0)
#define SI_STATUS_IO_BUSY BIT(1)
#define N64_CONTROLLER_ID 0x0500
#define MAX_CONTROLLERS 4
static const char *n64joy_phys[MAX_CONTROLLERS] = {
"n64joy/port0",
"n64joy/port1",
"n64joy/port2",
"n64joy/port3",
};
struct n64joy_priv {
u64 si_buf[8] ____cacheline_aligned;
struct timer_list timer;
struct mutex n64joy_mutex;
struct input_dev *n64joy_dev[MAX_CONTROLLERS];
u32 __iomem *reg_base;
u8 n64joy_opened;
};
struct joydata {
unsigned int: 16; /* unused */
unsigned int err: 2;
unsigned int: 14; /* unused */
union {
u32 data;
struct {
unsigned int a: 1;
unsigned int b: 1;
unsigned int z: 1;
unsigned int start: 1;
unsigned int up: 1;
unsigned int down: 1;
unsigned int left: 1;
unsigned int right: 1;
unsigned int: 2; /* unused */
unsigned int l: 1;
unsigned int r: 1;
unsigned int c_up: 1;
unsigned int c_down: 1;
unsigned int c_left: 1;
unsigned int c_right: 1;
signed int x: 8;
signed int y: 8;
};
};
};
static void n64joy_write_reg(u32 __iomem *reg_base, const u8 reg, const u32 value)
{
writel(value, reg_base + reg);
}
static u32 n64joy_read_reg(u32 __iomem *reg_base, const u8 reg)
{
return readl(reg_base + reg);
}
static void n64joy_wait_si_dma(u32 __iomem *reg_base)
{
while (n64joy_read_reg(reg_base, SI_STATUS_REG) &
(SI_STATUS_DMA_BUSY | SI_STATUS_IO_BUSY))
cpu_relax();
}
static void n64joy_exec_pif(struct n64joy_priv *priv, const u64 in[8])
{
unsigned long flags;
dma_cache_wback_inv((unsigned long) in, 8 * 8);
dma_cache_inv((unsigned long) priv->si_buf, 8 * 8);
local_irq_save(flags);
n64joy_wait_si_dma(priv->reg_base);
barrier();
n64joy_write_reg(priv->reg_base, SI_DRAM_REG, virt_to_phys(in));
barrier();
n64joy_write_reg(priv->reg_base, SI_WRITE_REG, PIF_RAM);
barrier();
n64joy_wait_si_dma(priv->reg_base);
barrier();
n64joy_write_reg(priv->reg_base, SI_DRAM_REG, virt_to_phys(priv->si_buf));
barrier();
n64joy_write_reg(priv->reg_base, SI_READ_REG, PIF_RAM);
barrier();
n64joy_wait_si_dma(priv->reg_base);
local_irq_restore(flags);
}
static const u64 polldata[] ____cacheline_aligned = {
0xff010401ffffffff,
0xff010401ffffffff,
0xff010401ffffffff,
0xff010401ffffffff,
0xfe00000000000000,
0,
0,
1
};
static void n64joy_poll(struct timer_list *t)
{
const struct joydata *data;
struct n64joy_priv *priv = container_of(t, struct n64joy_priv, timer);
struct input_dev *dev;
u32 i;
n64joy_exec_pif(priv, polldata);
data = (struct joydata *) priv->si_buf;
for (i = 0; i < MAX_CONTROLLERS; i++) {
if (!priv->n64joy_dev[i])
continue;
dev = priv->n64joy_dev[i];
/* d-pad */
input_report_key(dev, BTN_DPAD_UP, data[i].up);
input_report_key(dev, BTN_DPAD_DOWN, data[i].down);
input_report_key(dev, BTN_DPAD_LEFT, data[i].left);
input_report_key(dev, BTN_DPAD_RIGHT, data[i].right);
/* c buttons */
input_report_key(dev, BTN_FORWARD, data[i].c_up);
input_report_key(dev, BTN_BACK, data[i].c_down);
input_report_key(dev, BTN_LEFT, data[i].c_left);
input_report_key(dev, BTN_RIGHT, data[i].c_right);
/* matching buttons */
input_report_key(dev, BTN_START, data[i].start);
input_report_key(dev, BTN_Z, data[i].z);
/* remaining ones: a, b, l, r */
input_report_key(dev, BTN_0, data[i].a);
input_report_key(dev, BTN_1, data[i].b);
input_report_key(dev, BTN_2, data[i].l);
input_report_key(dev, BTN_3, data[i].r);
input_report_abs(dev, ABS_X, data[i].x);
input_report_abs(dev, ABS_Y, data[i].y);
input_sync(dev);
}
mod_timer(&priv->timer, jiffies + msecs_to_jiffies(16));
}
static int n64joy_open(struct input_dev *dev)
{
struct n64joy_priv *priv = input_get_drvdata(dev);
int err;
err = mutex_lock_interruptible(&priv->n64joy_mutex);
if (err)
return err;
if (!priv->n64joy_opened) {
/*
* We could use the vblank irq, but it's not important if
* the poll point slightly changes.
*/
timer_setup(&priv->timer, n64joy_poll, 0);
mod_timer(&priv->timer, jiffies + msecs_to_jiffies(16));
}
priv->n64joy_opened++;
mutex_unlock(&priv->n64joy_mutex);
return err;
}
static void n64joy_close(struct input_dev *dev)
{
struct n64joy_priv *priv = input_get_drvdata(dev);
mutex_lock(&priv->n64joy_mutex);
if (!--priv->n64joy_opened)
del_timer_sync(&priv->timer);
mutex_unlock(&priv->n64joy_mutex);
}
static const u64 __initconst scandata[] ____cacheline_aligned = {
0xff010300ffffffff,
0xff010300ffffffff,
0xff010300ffffffff,
0xff010300ffffffff,
0xfe00000000000000,
0,
0,
1
};
/*
* The target device is embedded and RAM-constrained. We save RAM
* by initializing in __init code that gets dropped late in boot.
* For the same reason there is no module or unloading support.
*/
static int __init n64joy_probe(struct platform_device *pdev)
{
const struct joydata *data;
struct n64joy_priv *priv;
struct input_dev *dev;
int err = 0;
u32 i, j, found = 0;
priv = kzalloc(sizeof(struct n64joy_priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
mutex_init(&priv->n64joy_mutex);
priv->reg_base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(priv->reg_base)) {
err = PTR_ERR(priv->reg_base);
goto fail;
}
/* The controllers are not hotpluggable, so we can scan in init */
n64joy_exec_pif(priv, scandata);
data = (struct joydata *) priv->si_buf;
for (i = 0; i < MAX_CONTROLLERS; i++) {
if (!data[i].err && data[i].data >> 16 == N64_CONTROLLER_ID) {
found++;
dev = priv->n64joy_dev[i] = input_allocate_device();
if (!priv->n64joy_dev[i]) {
err = -ENOMEM;
goto fail;
}
input_set_drvdata(dev, priv);
dev->name = "N64 controller";
dev->phys = n64joy_phys[i];
dev->id.bustype = BUS_HOST;
dev->id.vendor = 0;
dev->id.product = data[i].data >> 16;
dev->id.version = 0;
dev->dev.parent = &pdev->dev;
dev->open = n64joy_open;
dev->close = n64joy_close;
/* d-pad */
input_set_capability(dev, EV_KEY, BTN_DPAD_UP);
input_set_capability(dev, EV_KEY, BTN_DPAD_DOWN);
input_set_capability(dev, EV_KEY, BTN_DPAD_LEFT);
input_set_capability(dev, EV_KEY, BTN_DPAD_RIGHT);
/* c buttons */
input_set_capability(dev, EV_KEY, BTN_LEFT);
input_set_capability(dev, EV_KEY, BTN_RIGHT);
input_set_capability(dev, EV_KEY, BTN_FORWARD);
input_set_capability(dev, EV_KEY, BTN_BACK);
/* matching buttons */
input_set_capability(dev, EV_KEY, BTN_START);
input_set_capability(dev, EV_KEY, BTN_Z);
/* remaining ones: a, b, l, r */
input_set_capability(dev, EV_KEY, BTN_0);
input_set_capability(dev, EV_KEY, BTN_1);
input_set_capability(dev, EV_KEY, BTN_2);
input_set_capability(dev, EV_KEY, BTN_3);
for (j = 0; j < 2; j++)
input_set_abs_params(dev, ABS_X + j,
S8_MIN, S8_MAX, 0, 0);
err = input_register_device(dev);
if (err) {
input_free_device(dev);
goto fail;
}
}
}
pr_info("%u controller(s) connected\n", found);
if (!found)
return -ENODEV;
return 0;
fail:
for (i = 0; i < MAX_CONTROLLERS; i++) {
if (!priv->n64joy_dev[i])
continue;
input_unregister_device(priv->n64joy_dev[i]);
}
return err;
}
static struct platform_driver n64joy_driver = {
.driver = {
.name = "n64joy",
},
};
static int __init n64joy_init(void)
{
return platform_driver_probe(&n64joy_driver, n64joy_probe);
}
module_init(n64joy_init);
|
linux-master
|
drivers/input/joystick/n64joy.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2001 Vojtech Pavlik
*/
/*
* Genius Flight 2000 joystick driver for Linux
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/gameport.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "Genius Flight 2000 joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define GF2K_START 400 /* The time we wait for the first bit [400 us] */
#define GF2K_STROBE 40 /* The time we wait for the first bit [40 us] */
#define GF2K_TIMEOUT 4 /* Wait for everything to settle [4 ms] */
#define GF2K_LENGTH 80 /* Max number of triplets in a packet */
/*
* Genius joystick ids ...
*/
#define GF2K_ID_G09 1
#define GF2K_ID_F30D 2
#define GF2K_ID_F30 3
#define GF2K_ID_F31D 4
#define GF2K_ID_F305 5
#define GF2K_ID_F23P 6
#define GF2K_ID_F31 7
#define GF2K_ID_MAX 7
static char gf2k_length[] = { 40, 40, 40, 40, 40, 40, 40, 40 };
static char gf2k_hat_to_axis[][2] = {{ 0, 0}, { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}};
static char *gf2k_names[] = {"", "Genius G-09D", "Genius F-30D", "Genius F-30", "Genius MaxFighter F-31D",
"Genius F-30-5", "Genius Flight2000 F-23", "Genius F-31"};
static unsigned char gf2k_hats[] = { 0, 2, 0, 0, 2, 0, 2, 0 };
static unsigned char gf2k_axes[] = { 0, 2, 0, 0, 4, 0, 4, 0 };
static unsigned char gf2k_joys[] = { 0, 0, 0, 0,10, 0, 8, 0 };
static unsigned char gf2k_pads[] = { 0, 6, 0, 0, 0, 0, 0, 0 };
static unsigned char gf2k_lens[] = { 0,18, 0, 0,18, 0,18, 0 };
static unsigned char gf2k_abs[] = { ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, ABS_GAS, ABS_BRAKE };
static short gf2k_btn_joy[] = { BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4 };
static short gf2k_btn_pad[] = { BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_TL2, BTN_TR2, BTN_START, BTN_SELECT };
static short gf2k_seq_reset[] = { 240, 340, 0 };
static short gf2k_seq_digital[] = { 590, 320, 860, 0 };
struct gf2k {
struct gameport *gameport;
struct input_dev *dev;
int reads;
int bads;
unsigned char id;
unsigned char length;
char phys[32];
};
/*
* gf2k_read_packet() reads a Genius Flight2000 packet.
*/
static int gf2k_read_packet(struct gameport *gameport, int length, char *data)
{
unsigned char u, v;
int i;
unsigned int t, p;
unsigned long flags;
t = gameport_time(gameport, GF2K_START);
p = gameport_time(gameport, GF2K_STROBE);
i = 0;
local_irq_save(flags);
gameport_trigger(gameport);
v = gameport_read(gameport);
while (t > 0 && i < length) {
t--; u = v;
v = gameport_read(gameport);
if (v & ~u & 0x10) {
data[i++] = v >> 5;
t = p;
}
}
local_irq_restore(flags);
return i;
}
/*
* gf2k_trigger_seq() initializes a Genius Flight2000 joystick
* into digital mode.
*/
static void gf2k_trigger_seq(struct gameport *gameport, short *seq)
{
unsigned long flags;
int i, t;
local_irq_save(flags);
i = 0;
do {
gameport_trigger(gameport);
t = gameport_time(gameport, GF2K_TIMEOUT * 1000);
while ((gameport_read(gameport) & 1) && t) t--;
udelay(seq[i]);
} while (seq[++i]);
gameport_trigger(gameport);
local_irq_restore(flags);
}
/*
* js_sw_get_bits() composes bits from the triplet buffer into a __u64.
* Parameter 'pos' is bit number inside packet where to start at, 'num' is number
* of bits to be read, 'shift' is offset in the resulting __u64 to start at, bits
* is number of bits per triplet.
*/
#define GB(p,n,s) gf2k_get_bits(data, p, n, s)
static int gf2k_get_bits(unsigned char *buf, int pos, int num, int shift)
{
__u64 data = 0;
int i;
for (i = 0; i < num / 3 + 2; i++)
data |= buf[pos / 3 + i] << (i * 3);
data >>= pos % 3;
data &= (1 << num) - 1;
data <<= shift;
return data;
}
static void gf2k_read(struct gf2k *gf2k, unsigned char *data)
{
struct input_dev *dev = gf2k->dev;
int i, t;
for (i = 0; i < 4 && i < gf2k_axes[gf2k->id]; i++)
input_report_abs(dev, gf2k_abs[i], GB(i<<3,8,0) | GB(i+46,1,8) | GB(i+50,1,9));
for (i = 0; i < 2 && i < gf2k_axes[gf2k->id] - 4; i++)
input_report_abs(dev, gf2k_abs[i], GB(i*9+60,8,0) | GB(i+54,1,9));
t = GB(40,4,0);
for (i = 0; i < gf2k_hats[gf2k->id]; i++)
input_report_abs(dev, ABS_HAT0X + i, gf2k_hat_to_axis[t][i]);
t = GB(44,2,0) | GB(32,8,2) | GB(78,2,10);
for (i = 0; i < gf2k_joys[gf2k->id]; i++)
input_report_key(dev, gf2k_btn_joy[i], (t >> i) & 1);
for (i = 0; i < gf2k_pads[gf2k->id]; i++)
input_report_key(dev, gf2k_btn_pad[i], (t >> i) & 1);
input_sync(dev);
}
/*
* gf2k_poll() reads and analyzes Genius joystick data.
*/
static void gf2k_poll(struct gameport *gameport)
{
struct gf2k *gf2k = gameport_get_drvdata(gameport);
unsigned char data[GF2K_LENGTH];
gf2k->reads++;
if (gf2k_read_packet(gf2k->gameport, gf2k_length[gf2k->id], data) < gf2k_length[gf2k->id])
gf2k->bads++;
else
gf2k_read(gf2k, data);
}
static int gf2k_open(struct input_dev *dev)
{
struct gf2k *gf2k = input_get_drvdata(dev);
gameport_start_polling(gf2k->gameport);
return 0;
}
static void gf2k_close(struct input_dev *dev)
{
struct gf2k *gf2k = input_get_drvdata(dev);
gameport_stop_polling(gf2k->gameport);
}
/*
* gf2k_connect() probes for Genius id joysticks.
*/
static int gf2k_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct gf2k *gf2k;
struct input_dev *input_dev;
unsigned char data[GF2K_LENGTH];
int i, err;
gf2k = kzalloc(sizeof(struct gf2k), GFP_KERNEL);
input_dev = input_allocate_device();
if (!gf2k || !input_dev) {
err = -ENOMEM;
goto fail1;
}
gf2k->gameport = gameport;
gf2k->dev = input_dev;
gameport_set_drvdata(gameport, gf2k);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
gf2k_trigger_seq(gameport, gf2k_seq_reset);
msleep(GF2K_TIMEOUT);
gf2k_trigger_seq(gameport, gf2k_seq_digital);
msleep(GF2K_TIMEOUT);
if (gf2k_read_packet(gameport, GF2K_LENGTH, data) < 12) {
err = -ENODEV;
goto fail2;
}
if (!(gf2k->id = GB(7,2,0) | GB(3,3,2) | GB(0,3,5))) {
err = -ENODEV;
goto fail2;
}
#ifdef RESET_WORKS
if ((gf2k->id != (GB(19,2,0) | GB(15,3,2) | GB(12,3,5))) &&
(gf2k->id != (GB(31,2,0) | GB(27,3,2) | GB(24,3,5)))) {
err = -ENODEV;
goto fail2;
}
#else
gf2k->id = 6;
#endif
if (gf2k->id > GF2K_ID_MAX || !gf2k_axes[gf2k->id]) {
printk(KERN_WARNING "gf2k.c: Not yet supported joystick on %s. [id: %d type:%s]\n",
gameport->phys, gf2k->id, gf2k->id > GF2K_ID_MAX ? "Unknown" : gf2k_names[gf2k->id]);
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, gf2k_poll);
gameport_set_poll_interval(gameport, 20);
snprintf(gf2k->phys, sizeof(gf2k->phys), "%s/input0", gameport->phys);
gf2k->length = gf2k_lens[gf2k->id];
input_dev->name = gf2k_names[gf2k->id];
input_dev->phys = gf2k->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_GENIUS;
input_dev->id.product = gf2k->id;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &gameport->dev;
input_set_drvdata(input_dev, gf2k);
input_dev->open = gf2k_open;
input_dev->close = gf2k_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; i < gf2k_axes[gf2k->id]; i++)
set_bit(gf2k_abs[i], input_dev->absbit);
for (i = 0; i < gf2k_hats[gf2k->id]; i++)
input_set_abs_params(input_dev, ABS_HAT0X + i, -1, 1, 0, 0);
for (i = 0; i < gf2k_joys[gf2k->id]; i++)
set_bit(gf2k_btn_joy[i], input_dev->keybit);
for (i = 0; i < gf2k_pads[gf2k->id]; i++)
set_bit(gf2k_btn_pad[i], input_dev->keybit);
gf2k_read_packet(gameport, gf2k->length, data);
gf2k_read(gf2k, data);
for (i = 0; i < gf2k_axes[gf2k->id]; i++) {
int max = i < 2 ?
input_abs_get_val(input_dev, gf2k_abs[i]) * 2 :
input_abs_get_val(input_dev, gf2k_abs[0]) +
input_abs_get_val(input_dev, gf2k_abs[1]);
int flat = i < 2 ? 24 : 0;
input_set_abs_params(input_dev, gf2k_abs[i],
32, max - 32, 8, flat);
}
err = input_register_device(gf2k->dev);
if (err)
goto fail2;
return 0;
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
input_free_device(input_dev);
kfree(gf2k);
return err;
}
static void gf2k_disconnect(struct gameport *gameport)
{
struct gf2k *gf2k = gameport_get_drvdata(gameport);
input_unregister_device(gf2k->dev);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(gf2k);
}
static struct gameport_driver gf2k_drv = {
.driver = {
.name = "gf2k",
},
.description = DRIVER_DESC,
.connect = gf2k_connect,
.disconnect = gf2k_disconnect,
};
module_gameport_driver(gf2k_drv);
|
linux-master
|
drivers/input/joystick/gf2k.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*
* Based on the work of:
* David Thompson
* Joseph Krahn
*/
/*
* SpaceTec SpaceBall 2003/3003/4000 FLX driver for Linux
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <asm/unaligned.h>
#define DRIVER_DESC "SpaceTec SpaceBall 2003/3003/4000 FLX driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Constants.
*/
#define SPACEBALL_MAX_LENGTH 128
#define SPACEBALL_MAX_ID 9
#define SPACEBALL_1003 1
#define SPACEBALL_2003B 3
#define SPACEBALL_2003C 4
#define SPACEBALL_3003C 7
#define SPACEBALL_4000FLX 8
#define SPACEBALL_4000FLX_L 9
static int spaceball_axes[] = { ABS_X, ABS_Z, ABS_Y, ABS_RX, ABS_RZ, ABS_RY };
static char *spaceball_names[] = {
"?", "SpaceTec SpaceBall 1003", "SpaceTec SpaceBall 2003", "SpaceTec SpaceBall 2003B",
"SpaceTec SpaceBall 2003C", "SpaceTec SpaceBall 3003", "SpaceTec SpaceBall SpaceController",
"SpaceTec SpaceBall 3003C", "SpaceTec SpaceBall 4000FLX", "SpaceTec SpaceBall 4000FLX Lefty" };
/*
* Per-Ball data.
*/
struct spaceball {
struct input_dev *dev;
int idx;
int escape;
unsigned char data[SPACEBALL_MAX_LENGTH];
char phys[32];
};
/*
* spaceball_process_packet() decodes packets the driver receives from the
* SpaceBall.
*/
static void spaceball_process_packet(struct spaceball* spaceball)
{
struct input_dev *dev = spaceball->dev;
unsigned char *data = spaceball->data;
int i;
if (spaceball->idx < 2) return;
switch (spaceball->data[0]) {
case 'D': /* Ball data */
if (spaceball->idx != 15) return;
/*
* Skip first three bytes; read six axes worth of data.
* Axis values are signed 16-bit big-endian.
*/
data += 3;
for (i = 0; i < ARRAY_SIZE(spaceball_axes); i++) {
input_report_abs(dev, spaceball_axes[i],
(__s16)get_unaligned_be16(&data[i * 2]));
}
break;
case 'K': /* Button data */
if (spaceball->idx != 3) return;
input_report_key(dev, BTN_1, (data[2] & 0x01) || (data[2] & 0x20));
input_report_key(dev, BTN_2, data[2] & 0x02);
input_report_key(dev, BTN_3, data[2] & 0x04);
input_report_key(dev, BTN_4, data[2] & 0x08);
input_report_key(dev, BTN_5, data[1] & 0x01);
input_report_key(dev, BTN_6, data[1] & 0x02);
input_report_key(dev, BTN_7, data[1] & 0x04);
input_report_key(dev, BTN_8, data[1] & 0x10);
break;
case '.': /* Advanced button data */
if (spaceball->idx != 3) return;
input_report_key(dev, BTN_1, data[2] & 0x01);
input_report_key(dev, BTN_2, data[2] & 0x02);
input_report_key(dev, BTN_3, data[2] & 0x04);
input_report_key(dev, BTN_4, data[2] & 0x08);
input_report_key(dev, BTN_5, data[2] & 0x10);
input_report_key(dev, BTN_6, data[2] & 0x20);
input_report_key(dev, BTN_7, data[2] & 0x80);
input_report_key(dev, BTN_8, data[1] & 0x01);
input_report_key(dev, BTN_9, data[1] & 0x02);
input_report_key(dev, BTN_A, data[1] & 0x04);
input_report_key(dev, BTN_B, data[1] & 0x08);
input_report_key(dev, BTN_C, data[1] & 0x10);
input_report_key(dev, BTN_MODE, data[1] & 0x20);
break;
case 'E': /* Device error */
spaceball->data[spaceball->idx - 1] = 0;
printk(KERN_ERR "spaceball: Device error. [%s]\n", spaceball->data + 1);
break;
case '?': /* Bad command packet */
spaceball->data[spaceball->idx - 1] = 0;
printk(KERN_ERR "spaceball: Bad command. [%s]\n", spaceball->data + 1);
break;
}
input_sync(dev);
}
/*
* Spaceball 4000 FLX packets all start with a one letter packet-type decriptor,
* and end in 0x0d. It uses '^' as an escape for CR, XOFF and XON characters which
* can occur in the axis values.
*/
static irqreturn_t spaceball_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct spaceball *spaceball = serio_get_drvdata(serio);
switch (data) {
case 0xd:
spaceball_process_packet(spaceball);
spaceball->idx = 0;
spaceball->escape = 0;
break;
case '^':
if (!spaceball->escape) {
spaceball->escape = 1;
break;
}
spaceball->escape = 0;
fallthrough;
case 'M':
case 'Q':
case 'S':
if (spaceball->escape) {
spaceball->escape = 0;
data &= 0x1f;
}
fallthrough;
default:
if (spaceball->escape)
spaceball->escape = 0;
if (spaceball->idx < SPACEBALL_MAX_LENGTH)
spaceball->data[spaceball->idx++] = data;
break;
}
return IRQ_HANDLED;
}
/*
* spaceball_disconnect() is the opposite of spaceball_connect()
*/
static void spaceball_disconnect(struct serio *serio)
{
struct spaceball* spaceball = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(spaceball->dev);
kfree(spaceball);
}
/*
* spaceball_connect() is the routine that is called when someone adds a
* new serio device that supports Spaceball protocol and registers it as
* an input device.
*/
static int spaceball_connect(struct serio *serio, struct serio_driver *drv)
{
struct spaceball *spaceball;
struct input_dev *input_dev;
int err = -ENOMEM;
int i, id;
if ((id = serio->id.id) > SPACEBALL_MAX_ID)
return -ENODEV;
spaceball = kmalloc(sizeof(struct spaceball), GFP_KERNEL);
input_dev = input_allocate_device();
if (!spaceball || !input_dev)
goto fail1;
spaceball->dev = input_dev;
snprintf(spaceball->phys, sizeof(spaceball->phys), "%s/input0", serio->phys);
input_dev->name = spaceball_names[id];
input_dev->phys = spaceball->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_SPACEBALL;
input_dev->id.product = id;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
switch (id) {
case SPACEBALL_4000FLX:
case SPACEBALL_4000FLX_L:
input_dev->keybit[BIT_WORD(BTN_0)] |= BIT_MASK(BTN_9);
input_dev->keybit[BIT_WORD(BTN_A)] |= BIT_MASK(BTN_A) |
BIT_MASK(BTN_B) | BIT_MASK(BTN_C) |
BIT_MASK(BTN_MODE);
fallthrough;
default:
input_dev->keybit[BIT_WORD(BTN_0)] |= BIT_MASK(BTN_2) |
BIT_MASK(BTN_3) | BIT_MASK(BTN_4) |
BIT_MASK(BTN_5) | BIT_MASK(BTN_6) |
BIT_MASK(BTN_7) | BIT_MASK(BTN_8);
fallthrough;
case SPACEBALL_3003C:
input_dev->keybit[BIT_WORD(BTN_0)] |= BIT_MASK(BTN_1) |
BIT_MASK(BTN_8);
}
for (i = 0; i < 3; i++) {
input_set_abs_params(input_dev, ABS_X + i, -8000, 8000, 8, 40);
input_set_abs_params(input_dev, ABS_RX + i, -1600, 1600, 2, 8);
}
serio_set_drvdata(serio, spaceball);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(spaceball->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(spaceball);
return err;
}
/*
* The serio driver structure.
*/
static const struct serio_device_id spaceball_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_SPACEBALL,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, spaceball_serio_ids);
static struct serio_driver spaceball_drv = {
.driver = {
.name = "spaceball",
},
.description = DRIVER_DESC,
.id_table = spaceball_serio_ids,
.interrupt = spaceball_interrupt,
.connect = spaceball_connect,
.disconnect = spaceball_disconnect,
};
module_serio_driver(spaceball_drv);
|
linux-master
|
drivers/input/joystick/spaceball.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000-2001 Vojtech Pavlik
* Copyright (c) 2000 Mark Fletcher
*/
/*
* Gravis Stinger gamepad driver for Linux
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Gravis Stinger gamepad driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Constants.
*/
#define STINGER_MAX_LENGTH 8
/*
* Per-Stinger data.
*/
struct stinger {
struct input_dev *dev;
int idx;
unsigned char data[STINGER_MAX_LENGTH];
char phys[32];
};
/*
* stinger_process_packet() decodes packets the driver receives from the
* Stinger. It updates the data accordingly.
*/
static void stinger_process_packet(struct stinger *stinger)
{
struct input_dev *dev = stinger->dev;
unsigned char *data = stinger->data;
if (!stinger->idx) return;
input_report_key(dev, BTN_A, ((data[0] & 0x20) >> 5));
input_report_key(dev, BTN_B, ((data[0] & 0x10) >> 4));
input_report_key(dev, BTN_C, ((data[0] & 0x08) >> 3));
input_report_key(dev, BTN_X, ((data[0] & 0x04) >> 2));
input_report_key(dev, BTN_Y, ((data[3] & 0x20) >> 5));
input_report_key(dev, BTN_Z, ((data[3] & 0x10) >> 4));
input_report_key(dev, BTN_TL, ((data[3] & 0x08) >> 3));
input_report_key(dev, BTN_TR, ((data[3] & 0x04) >> 2));
input_report_key(dev, BTN_SELECT, ((data[3] & 0x02) >> 1));
input_report_key(dev, BTN_START, (data[3] & 0x01));
input_report_abs(dev, ABS_X, (data[1] & 0x3F) - ((data[0] & 0x01) << 6));
input_report_abs(dev, ABS_Y, ((data[0] & 0x02) << 5) - (data[2] & 0x3F));
input_sync(dev);
return;
}
/*
* stinger_interrupt() is called by the low level driver when characters
* are ready for us. We then buffer them for further processing, or call the
* packet processing routine.
*/
static irqreturn_t stinger_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct stinger *stinger = serio_get_drvdata(serio);
/* All Stinger packets are 4 bytes */
if (stinger->idx < STINGER_MAX_LENGTH)
stinger->data[stinger->idx++] = data;
if (stinger->idx == 4) {
stinger_process_packet(stinger);
stinger->idx = 0;
}
return IRQ_HANDLED;
}
/*
* stinger_disconnect() is the opposite of stinger_connect()
*/
static void stinger_disconnect(struct serio *serio)
{
struct stinger *stinger = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(stinger->dev);
kfree(stinger);
}
/*
* stinger_connect() is the routine that is called when someone adds a
* new serio device that supports Stinger protocol and registers it as
* an input device.
*/
static int stinger_connect(struct serio *serio, struct serio_driver *drv)
{
struct stinger *stinger;
struct input_dev *input_dev;
int err = -ENOMEM;
stinger = kmalloc(sizeof(struct stinger), GFP_KERNEL);
input_dev = input_allocate_device();
if (!stinger || !input_dev)
goto fail1;
stinger->dev = input_dev;
snprintf(stinger->phys, sizeof(stinger->phys), "%s/serio0", serio->phys);
input_dev->name = "Gravis Stinger";
input_dev->phys = stinger->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_STINGER;
input_dev->id.product = 0x0001;
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_A)] = BIT_MASK(BTN_A) | BIT_MASK(BTN_B) |
BIT_MASK(BTN_C) | BIT_MASK(BTN_X) | BIT_MASK(BTN_Y) |
BIT_MASK(BTN_Z) | BIT_MASK(BTN_TL) | BIT_MASK(BTN_TR) |
BIT_MASK(BTN_START) | BIT_MASK(BTN_SELECT);
input_set_abs_params(input_dev, ABS_X, -64, 64, 0, 4);
input_set_abs_params(input_dev, ABS_Y, -64, 64, 0, 4);
serio_set_drvdata(serio, stinger);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(stinger->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(stinger);
return err;
}
/*
* The serio driver structure.
*/
static const struct serio_device_id stinger_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_STINGER,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, stinger_serio_ids);
static struct serio_driver stinger_drv = {
.driver = {
.name = "stinger",
},
.description = DRIVER_DESC,
.id_table = stinger_serio_ids,
.interrupt = stinger_interrupt,
.connect = stinger_connect,
.disconnect = stinger_disconnect,
};
module_serio_driver(stinger_drv);
|
linux-master
|
drivers/input/joystick/stinger.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Parallel port to Walkera WK-0701 TX joystick
*
* Copyright (c) 2008 Peter Popovec
*
* More about driver: <file:Documentation/input/devices/walkera0701.rst>
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define RESERVE 20000
#define SYNC_PULSE 1306000
#define BIN0_PULSE 288000
#define BIN1_PULSE 438000
#define ANALOG_MIN_PULSE 318000
#define ANALOG_MAX_PULSE 878000
#define ANALOG_DELTA 80000
#define BIN_SAMPLE ((BIN0_PULSE + BIN1_PULSE) / 2)
#define NO_SYNC 25
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/parport.h>
#include <linux/input.h>
#include <linux/hrtimer.h>
MODULE_AUTHOR("Peter Popovec <[email protected]>");
MODULE_DESCRIPTION("Walkera WK-0701 TX as joystick");
MODULE_LICENSE("GPL");
static unsigned int walkera0701_pp_no;
module_param_named(port, walkera0701_pp_no, int, 0);
MODULE_PARM_DESC(port,
"Parallel port adapter for Walkera WK-0701 TX (default is 0)");
/*
* For now, only one device is supported, if somebody need more devices, code
* can be expanded, one struct walkera_dev per device must be allocated and
* set up by walkera0701_connect (release of device by walkera0701_disconnect)
*/
struct walkera_dev {
unsigned char buf[25];
u64 irq_time, irq_lasttime;
int counter;
int ack;
struct input_dev *input_dev;
struct hrtimer timer;
struct parport *parport;
struct pardevice *pardevice;
};
static struct walkera_dev w_dev;
static inline void walkera0701_parse_frame(struct walkera_dev *w)
{
int i;
int val1, val2, val3, val4, val5, val6, val7, val8;
int magic, magic_bit;
int crc1, crc2;
for (crc1 = crc2 = i = 0; i < 10; i++) {
crc1 += w->buf[i] & 7;
crc2 += (w->buf[i] & 8) >> 3;
}
if ((w->buf[10] & 7) != (crc1 & 7))
return;
if (((w->buf[10] & 8) >> 3) != (((crc1 >> 3) + crc2) & 1))
return;
for (crc1 = crc2 = 0, i = 11; i < 23; i++) {
crc1 += w->buf[i] & 7;
crc2 += (w->buf[i] & 8) >> 3;
}
if ((w->buf[23] & 7) != (crc1 & 7))
return;
if (((w->buf[23] & 8) >> 3) != (((crc1 >> 3) + crc2) & 1))
return;
val1 = ((w->buf[0] & 7) * 256 + w->buf[1] * 16 + w->buf[2]) >> 2;
val1 *= ((w->buf[0] >> 2) & 2) - 1; /* sign */
val2 = (w->buf[2] & 1) << 8 | (w->buf[3] << 4) | w->buf[4];
val2 *= (w->buf[2] & 2) - 1; /* sign */
val3 = ((w->buf[5] & 7) * 256 + w->buf[6] * 16 + w->buf[7]) >> 2;
val3 *= ((w->buf[5] >> 2) & 2) - 1; /* sign */
val4 = (w->buf[7] & 1) << 8 | (w->buf[8] << 4) | w->buf[9];
val4 *= (w->buf[7] & 2) - 1; /* sign */
val5 = ((w->buf[11] & 7) * 256 + w->buf[12] * 16 + w->buf[13]) >> 2;
val5 *= ((w->buf[11] >> 2) & 2) - 1; /* sign */
val6 = (w->buf[13] & 1) << 8 | (w->buf[14] << 4) | w->buf[15];
val6 *= (w->buf[13] & 2) - 1; /* sign */
val7 = ((w->buf[16] & 7) * 256 + w->buf[17] * 16 + w->buf[18]) >> 2;
val7 *= ((w->buf[16] >> 2) & 2) - 1; /*sign */
val8 = (w->buf[18] & 1) << 8 | (w->buf[19] << 4) | w->buf[20];
val8 *= (w->buf[18] & 2) - 1; /*sign */
magic = (w->buf[21] << 4) | w->buf[22];
magic_bit = (w->buf[24] & 8) >> 3;
pr_debug("%4d %4d %4d %4d %4d %4d %4d %4d (magic %2x %d)\n",
val1, val2, val3, val4, val5, val6, val7, val8,
magic, magic_bit);
input_report_abs(w->input_dev, ABS_X, val2);
input_report_abs(w->input_dev, ABS_Y, val1);
input_report_abs(w->input_dev, ABS_Z, val6);
input_report_abs(w->input_dev, ABS_THROTTLE, val3);
input_report_abs(w->input_dev, ABS_RUDDER, val4);
input_report_abs(w->input_dev, ABS_MISC, val7);
input_report_key(w->input_dev, BTN_GEAR_DOWN, val5 > 0);
}
static inline int read_ack(struct pardevice *p)
{
return parport_read_status(p->port) & 0x40;
}
/* falling edge, prepare to BIN value calculation */
static void walkera0701_irq_handler(void *handler_data)
{
u64 pulse_time;
struct walkera_dev *w = handler_data;
w->irq_time = ktime_to_ns(ktime_get());
pulse_time = w->irq_time - w->irq_lasttime;
w->irq_lasttime = w->irq_time;
/* cancel timer, if in handler or active do resync */
if (unlikely(0 != hrtimer_try_to_cancel(&w->timer))) {
w->counter = NO_SYNC;
return;
}
if (w->counter < NO_SYNC) {
if (w->ack) {
pulse_time -= BIN1_PULSE;
w->buf[w->counter] = 8;
} else {
pulse_time -= BIN0_PULSE;
w->buf[w->counter] = 0;
}
if (w->counter == 24) { /* full frame */
walkera0701_parse_frame(w);
w->counter = NO_SYNC;
if (abs(pulse_time - SYNC_PULSE) < RESERVE) /* new frame sync */
w->counter = 0;
} else {
if ((pulse_time > (ANALOG_MIN_PULSE - RESERVE)
&& (pulse_time < (ANALOG_MAX_PULSE + RESERVE)))) {
pulse_time -= (ANALOG_MIN_PULSE - RESERVE);
pulse_time = (u32) pulse_time / ANALOG_DELTA; /* overtiping is safe, pulsetime < s32.. */
w->buf[w->counter++] |= (pulse_time & 7);
} else
w->counter = NO_SYNC;
}
} else if (abs(pulse_time - SYNC_PULSE - BIN0_PULSE) <
RESERVE + BIN1_PULSE - BIN0_PULSE) /* frame sync .. */
w->counter = 0;
hrtimer_start(&w->timer, BIN_SAMPLE, HRTIMER_MODE_REL);
}
static enum hrtimer_restart timer_handler(struct hrtimer
*handle)
{
struct walkera_dev *w;
w = container_of(handle, struct walkera_dev, timer);
w->ack = read_ack(w->pardevice);
return HRTIMER_NORESTART;
}
static int walkera0701_open(struct input_dev *dev)
{
struct walkera_dev *w = input_get_drvdata(dev);
if (parport_claim(w->pardevice))
return -EBUSY;
parport_enable_irq(w->parport);
return 0;
}
static void walkera0701_close(struct input_dev *dev)
{
struct walkera_dev *w = input_get_drvdata(dev);
parport_disable_irq(w->parport);
hrtimer_cancel(&w->timer);
parport_release(w->pardevice);
}
static void walkera0701_attach(struct parport *pp)
{
struct pardev_cb walkera0701_parport_cb;
struct walkera_dev *w = &w_dev;
if (pp->number != walkera0701_pp_no) {
pr_debug("Not using parport%d.\n", pp->number);
return;
}
if (pp->irq == -1) {
pr_err("parport %d does not have interrupt assigned\n",
pp->number);
return;
}
w->parport = pp;
memset(&walkera0701_parport_cb, 0, sizeof(walkera0701_parport_cb));
walkera0701_parport_cb.flags = PARPORT_FLAG_EXCL;
walkera0701_parport_cb.irq_func = walkera0701_irq_handler;
walkera0701_parport_cb.private = w;
w->pardevice = parport_register_dev_model(pp, "walkera0701",
&walkera0701_parport_cb, 0);
if (!w->pardevice) {
pr_err("failed to register parport device\n");
return;
}
if (parport_negotiate(w->pardevice->port, IEEE1284_MODE_COMPAT)) {
pr_err("failed to negotiate parport mode\n");
goto err_unregister_device;
}
hrtimer_init(&w->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
w->timer.function = timer_handler;
w->input_dev = input_allocate_device();
if (!w->input_dev) {
pr_err("failed to allocate input device\n");
goto err_unregister_device;
}
input_set_drvdata(w->input_dev, w);
w->input_dev->name = "Walkera WK-0701 TX";
w->input_dev->phys = w->parport->name;
w->input_dev->id.bustype = BUS_PARPORT;
/* TODO what id vendor/product/version ? */
w->input_dev->id.vendor = 0x0001;
w->input_dev->id.product = 0x0001;
w->input_dev->id.version = 0x0100;
w->input_dev->dev.parent = w->parport->dev;
w->input_dev->open = walkera0701_open;
w->input_dev->close = walkera0701_close;
w->input_dev->evbit[0] = BIT(EV_ABS) | BIT_MASK(EV_KEY);
w->input_dev->keybit[BIT_WORD(BTN_GEAR_DOWN)] = BIT_MASK(BTN_GEAR_DOWN);
input_set_abs_params(w->input_dev, ABS_X, -512, 512, 0, 0);
input_set_abs_params(w->input_dev, ABS_Y, -512, 512, 0, 0);
input_set_abs_params(w->input_dev, ABS_Z, -512, 512, 0, 0);
input_set_abs_params(w->input_dev, ABS_THROTTLE, -512, 512, 0, 0);
input_set_abs_params(w->input_dev, ABS_RUDDER, -512, 512, 0, 0);
input_set_abs_params(w->input_dev, ABS_MISC, -512, 512, 0, 0);
if (input_register_device(w->input_dev)) {
pr_err("failed to register input device\n");
goto err_free_input_dev;
}
return;
err_free_input_dev:
input_free_device(w->input_dev);
err_unregister_device:
parport_unregister_device(w->pardevice);
}
static void walkera0701_detach(struct parport *port)
{
struct walkera_dev *w = &w_dev;
if (!w->pardevice || w->parport->number != port->number)
return;
input_unregister_device(w->input_dev);
parport_unregister_device(w->pardevice);
w->parport = NULL;
}
static struct parport_driver walkera0701_parport_driver = {
.name = "walkera0701",
.match_port = walkera0701_attach,
.detach = walkera0701_detach,
.devmodel = true,
};
static int __init walkera0701_init(void)
{
return parport_register_driver(&walkera0701_parport_driver);
}
static void __exit walkera0701_exit(void)
{
parport_unregister_driver(&walkera0701_parport_driver);
}
module_init(walkera0701_init);
module_exit(walkera0701_exit);
|
linux-master
|
drivers/input/joystick/walkera0701.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2001 Arndt Schoenewald
* Copyright (c) 2000-2001 Vojtech Pavlik
* Copyright (c) 2000 Mark Fletcher
*
* Sponsored by Quelltext AG (http://www.quelltext-ag.de), Dortmund, Germany
*/
/*
* Driver to use Handykey's Twiddler (the first edition, i.e. the one with
* the RS232 interface) as a joystick under Linux
*
* The Twiddler is a one-handed chording keyboard featuring twelve buttons on
* the front, six buttons on the top, and a built-in tilt sensor. The buttons
* on the front, which are grouped as four rows of three buttons, are pressed
* by the four fingers (this implies only one button per row can be held down
* at the same time) and the buttons on the top are for the thumb. The tilt
* sensor delivers X and Y axis data depending on how the Twiddler is held.
* Additional information can be found at http://www.handykey.com.
*
* This driver does not use the Twiddler for its intended purpose, i.e. as
* a chording keyboard, but as a joystick: pressing and releasing a button
* immediately sends a corresponding button event, and tilting it generates
* corresponding ABS_X and ABS_Y events. This turns the Twiddler into a game
* controller with amazing 18 buttons :-)
*
* Note: The Twiddler2 (the successor of the Twiddler that connects directly
* to the PS/2 keyboard and mouse ports) is NOT supported by this driver!
*
* For questions or feedback regarding this driver module please contact:
* Arndt Schoenewald <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Handykey Twiddler keyboard as a joystick driver"
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Constants.
*/
#define TWIDJOY_MAX_LENGTH 5
static struct twidjoy_button_spec {
int bitshift;
int bitmask;
int buttons[3];
}
twidjoy_buttons[] = {
{ 0, 3, { BTN_A, BTN_B, BTN_C } },
{ 2, 3, { BTN_X, BTN_Y, BTN_Z } },
{ 4, 3, { BTN_TL, BTN_TR, BTN_TR2 } },
{ 6, 3, { BTN_SELECT, BTN_START, BTN_MODE } },
{ 8, 1, { BTN_BASE5 } },
{ 9, 1, { BTN_BASE } },
{ 10, 1, { BTN_BASE3 } },
{ 11, 1, { BTN_BASE4 } },
{ 12, 1, { BTN_BASE2 } },
{ 13, 1, { BTN_BASE6 } },
{ 0, 0, { 0 } }
};
/*
* Per-Twiddler data.
*/
struct twidjoy {
struct input_dev *dev;
int idx;
unsigned char data[TWIDJOY_MAX_LENGTH];
char phys[32];
};
/*
* twidjoy_process_packet() decodes packets the driver receives from the
* Twiddler. It updates the data accordingly.
*/
static void twidjoy_process_packet(struct twidjoy *twidjoy)
{
struct input_dev *dev = twidjoy->dev;
unsigned char *data = twidjoy->data;
struct twidjoy_button_spec *bp;
int button_bits, abs_x, abs_y;
button_bits = ((data[1] & 0x7f) << 7) | (data[0] & 0x7f);
for (bp = twidjoy_buttons; bp->bitmask; bp++) {
int value = (button_bits & (bp->bitmask << bp->bitshift)) >> bp->bitshift;
int i;
for (i = 0; i < bp->bitmask; i++)
input_report_key(dev, bp->buttons[i], i+1 == value);
}
abs_x = ((data[4] & 0x07) << 5) | ((data[3] & 0x7C) >> 2);
if (data[4] & 0x08) abs_x -= 256;
abs_y = ((data[3] & 0x01) << 7) | ((data[2] & 0x7F) >> 0);
if (data[3] & 0x02) abs_y -= 256;
input_report_abs(dev, ABS_X, -abs_x);
input_report_abs(dev, ABS_Y, +abs_y);
input_sync(dev);
}
/*
* twidjoy_interrupt() is called by the low level driver when characters
* are ready for us. We then buffer them for further processing, or call the
* packet processing routine.
*/
static irqreturn_t twidjoy_interrupt(struct serio *serio, unsigned char data, unsigned int flags)
{
struct twidjoy *twidjoy = serio_get_drvdata(serio);
/* All Twiddler packets are 5 bytes. The fact that the first byte
* has a MSB of 0 and all other bytes have a MSB of 1 can be used
* to check and regain sync. */
if ((data & 0x80) == 0)
twidjoy->idx = 0; /* this byte starts a new packet */
else if (twidjoy->idx == 0)
return IRQ_HANDLED; /* wrong MSB -- ignore this byte */
if (twidjoy->idx < TWIDJOY_MAX_LENGTH)
twidjoy->data[twidjoy->idx++] = data;
if (twidjoy->idx == TWIDJOY_MAX_LENGTH) {
twidjoy_process_packet(twidjoy);
twidjoy->idx = 0;
}
return IRQ_HANDLED;
}
/*
* twidjoy_disconnect() is the opposite of twidjoy_connect()
*/
static void twidjoy_disconnect(struct serio *serio)
{
struct twidjoy *twidjoy = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(twidjoy->dev);
kfree(twidjoy);
}
/*
* twidjoy_connect() is the routine that is called when someone adds a
* new serio device. It looks for the Twiddler, and if found, registers
* it as an input device.
*/
static int twidjoy_connect(struct serio *serio, struct serio_driver *drv)
{
struct twidjoy_button_spec *bp;
struct twidjoy *twidjoy;
struct input_dev *input_dev;
int err = -ENOMEM;
int i;
twidjoy = kzalloc(sizeof(struct twidjoy), GFP_KERNEL);
input_dev = input_allocate_device();
if (!twidjoy || !input_dev)
goto fail1;
twidjoy->dev = input_dev;
snprintf(twidjoy->phys, sizeof(twidjoy->phys), "%s/input0", serio->phys);
input_dev->name = "Handykey Twiddler";
input_dev->phys = twidjoy->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_TWIDJOY;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_set_abs_params(input_dev, ABS_X, -50, 50, 4, 4);
input_set_abs_params(input_dev, ABS_Y, -50, 50, 4, 4);
for (bp = twidjoy_buttons; bp->bitmask; bp++)
for (i = 0; i < bp->bitmask; i++)
set_bit(bp->buttons[i], input_dev->keybit);
serio_set_drvdata(serio, twidjoy);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(twidjoy->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(twidjoy);
return err;
}
/*
* The serio driver structure.
*/
static const struct serio_device_id twidjoy_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_TWIDJOY,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, twidjoy_serio_ids);
static struct serio_driver twidjoy_drv = {
.driver = {
.name = "twidjoy",
},
.description = DRIVER_DESC,
.id_table = twidjoy_serio_ids,
.interrupt = twidjoy_interrupt,
.connect = twidjoy_connect,
.disconnect = twidjoy_disconnect,
};
module_serio_driver(twidjoy_drv);
|
linux-master
|
drivers/input/joystick/twidjoy.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* derived from "twidjoy.c"
*
* Copyright (c) 2008 Martin Kebert
* Copyright (c) 2001 Arndt Schoenewald
* Copyright (c) 2000-2001 Vojtech Pavlik
* Copyright (c) 2000 Mark Fletcher
*/
/*
* Driver to use 4CH RC transmitter using Zhen Hua 5-byte protocol (Walkera Lama,
* EasyCopter etc.) as a joystick under Linux.
*
* RC transmitters using Zhen Hua 5-byte protocol are cheap four channels
* transmitters for control a RC planes or RC helicopters with possibility to
* connect on a serial port.
* Data coming from transmitter is in this order:
* 1. byte = synchronisation byte
* 2. byte = X axis
* 3. byte = Y axis
* 4. byte = RZ axis
* 5. byte = Z axis
* (and this is repeated)
*
* For questions or feedback regarding this driver module please contact:
* Martin Kebert <[email protected]> - but I am not a C-programmer nor kernel
* coder :-(
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/bitrev.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "RC transmitter with 5-byte Zhen Hua protocol joystick driver"
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Constants.
*/
#define ZHENHUA_MAX_LENGTH 5
/*
* Zhen Hua data.
*/
struct zhenhua {
struct input_dev *dev;
int idx;
unsigned char data[ZHENHUA_MAX_LENGTH];
char phys[32];
};
/*
* zhenhua_process_packet() decodes packets the driver receives from the
* RC transmitter. It updates the data accordingly.
*/
static void zhenhua_process_packet(struct zhenhua *zhenhua)
{
struct input_dev *dev = zhenhua->dev;
unsigned char *data = zhenhua->data;
input_report_abs(dev, ABS_Y, data[1]);
input_report_abs(dev, ABS_X, data[2]);
input_report_abs(dev, ABS_RZ, data[3]);
input_report_abs(dev, ABS_Z, data[4]);
input_sync(dev);
}
/*
* zhenhua_interrupt() is called by the low level driver when characters
* are ready for us. We then buffer them for further processing, or call the
* packet processing routine.
*/
static irqreturn_t zhenhua_interrupt(struct serio *serio, unsigned char data, unsigned int flags)
{
struct zhenhua *zhenhua = serio_get_drvdata(serio);
/* All Zhen Hua packets are 5 bytes. The fact that the first byte
* is allways 0xf7 and all others are in range 0x32 - 0xc8 (50-200)
* can be used to check and regain sync. */
if (data == 0xef)
zhenhua->idx = 0; /* this byte starts a new packet */
else if (zhenhua->idx == 0)
return IRQ_HANDLED; /* wrong MSB -- ignore this byte */
if (zhenhua->idx < ZHENHUA_MAX_LENGTH)
zhenhua->data[zhenhua->idx++] = bitrev8(data);
if (zhenhua->idx == ZHENHUA_MAX_LENGTH) {
zhenhua_process_packet(zhenhua);
zhenhua->idx = 0;
}
return IRQ_HANDLED;
}
/*
* zhenhua_disconnect() is the opposite of zhenhua_connect()
*/
static void zhenhua_disconnect(struct serio *serio)
{
struct zhenhua *zhenhua = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(zhenhua->dev);
kfree(zhenhua);
}
/*
* zhenhua_connect() is the routine that is called when someone adds a
* new serio device. It looks for the Twiddler, and if found, registers
* it as an input device.
*/
static int zhenhua_connect(struct serio *serio, struct serio_driver *drv)
{
struct zhenhua *zhenhua;
struct input_dev *input_dev;
int err = -ENOMEM;
zhenhua = kzalloc(sizeof(struct zhenhua), GFP_KERNEL);
input_dev = input_allocate_device();
if (!zhenhua || !input_dev)
goto fail1;
zhenhua->dev = input_dev;
snprintf(zhenhua->phys, sizeof(zhenhua->phys), "%s/input0", serio->phys);
input_dev->name = "Zhen Hua 5-byte device";
input_dev->phys = zhenhua->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_ZHENHUA;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT(EV_ABS);
input_set_abs_params(input_dev, ABS_X, 50, 200, 0, 0);
input_set_abs_params(input_dev, ABS_Y, 50, 200, 0, 0);
input_set_abs_params(input_dev, ABS_Z, 50, 200, 0, 0);
input_set_abs_params(input_dev, ABS_RZ, 50, 200, 0, 0);
serio_set_drvdata(serio, zhenhua);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(zhenhua->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(zhenhua);
return err;
}
/*
* The serio driver structure.
*/
static const struct serio_device_id zhenhua_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_ZHENHUA,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, zhenhua_serio_ids);
static struct serio_driver zhenhua_drv = {
.driver = {
.name = "zhenhua",
},
.description = DRIVER_DESC,
.id_table = zhenhua_serio_ids,
.interrupt = zhenhua_interrupt,
.connect = zhenhua_connect,
.disconnect = zhenhua_disconnect,
};
module_serio_driver(zhenhua_drv);
|
linux-master
|
drivers/input/joystick/zhenhua.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* Magellan and Space Mouse 6dof controller driver for Linux
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Magellan and SpaceMouse 6dof controller driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define MAGELLAN_MAX_LENGTH 32
static int magellan_buttons[] = { BTN_0, BTN_1, BTN_2, BTN_3, BTN_4, BTN_5, BTN_6, BTN_7, BTN_8 };
static int magellan_axes[] = { ABS_X, ABS_Y, ABS_Z, ABS_RX, ABS_RY, ABS_RZ };
/*
* Per-Magellan data.
*/
struct magellan {
struct input_dev *dev;
int idx;
unsigned char data[MAGELLAN_MAX_LENGTH];
char phys[32];
};
/*
* magellan_crunch_nibbles() verifies that the bytes sent from the Magellan
* have correct upper nibbles for the lower ones, if not, the packet will
* be thrown away. It also strips these upper halves to simplify further
* processing.
*/
static int magellan_crunch_nibbles(unsigned char *data, int count)
{
static unsigned char nibbles[16] = "0AB3D56GH9:K<MN?";
do {
if (data[count] == nibbles[data[count] & 0xf])
data[count] = data[count] & 0xf;
else
return -1;
} while (--count);
return 0;
}
static void magellan_process_packet(struct magellan* magellan)
{
struct input_dev *dev = magellan->dev;
unsigned char *data = magellan->data;
int i, t;
if (!magellan->idx) return;
switch (magellan->data[0]) {
case 'd': /* Axis data */
if (magellan->idx != 25) return;
if (magellan_crunch_nibbles(data, 24)) return;
for (i = 0; i < 6; i++)
input_report_abs(dev, magellan_axes[i],
(data[(i << 2) + 1] << 12 | data[(i << 2) + 2] << 8 |
data[(i << 2) + 3] << 4 | data[(i << 2) + 4]) - 32768);
break;
case 'k': /* Button data */
if (magellan->idx != 4) return;
if (magellan_crunch_nibbles(data, 3)) return;
t = (data[1] << 1) | (data[2] << 5) | data[3];
for (i = 0; i < 9; i++) input_report_key(dev, magellan_buttons[i], (t >> i) & 1);
break;
}
input_sync(dev);
}
static irqreturn_t magellan_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct magellan* magellan = serio_get_drvdata(serio);
if (data == '\r') {
magellan_process_packet(magellan);
magellan->idx = 0;
} else {
if (magellan->idx < MAGELLAN_MAX_LENGTH)
magellan->data[magellan->idx++] = data;
}
return IRQ_HANDLED;
}
/*
* magellan_disconnect() is the opposite of magellan_connect()
*/
static void magellan_disconnect(struct serio *serio)
{
struct magellan* magellan = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(magellan->dev);
kfree(magellan);
}
/*
* magellan_connect() is the routine that is called when someone adds a
* new serio device that supports Magellan protocol and registers it as
* an input device.
*/
static int magellan_connect(struct serio *serio, struct serio_driver *drv)
{
struct magellan *magellan;
struct input_dev *input_dev;
int err = -ENOMEM;
int i;
magellan = kzalloc(sizeof(struct magellan), GFP_KERNEL);
input_dev = input_allocate_device();
if (!magellan || !input_dev)
goto fail1;
magellan->dev = input_dev;
snprintf(magellan->phys, sizeof(magellan->phys), "%s/input0", serio->phys);
input_dev->name = "LogiCad3D Magellan / SpaceMouse";
input_dev->phys = magellan->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_MAGELLAN;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (i = 0; i < 9; i++)
set_bit(magellan_buttons[i], input_dev->keybit);
for (i = 0; i < 6; i++)
input_set_abs_params(input_dev, magellan_axes[i], -360, 360, 0, 0);
serio_set_drvdata(serio, magellan);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(magellan->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(magellan);
return err;
}
/*
* The serio driver structure.
*/
static const struct serio_device_id magellan_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_MAGELLAN,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, magellan_serio_ids);
static struct serio_driver magellan_drv = {
.driver = {
.name = "magellan",
},
.description = DRIVER_DESC,
.id_table = magellan_serio_ids,
.interrupt = magellan_interrupt,
.connect = magellan_connect,
.disconnect = magellan_disconnect,
};
module_serio_driver(magellan_drv);
|
linux-master
|
drivers/input/joystick/magellan.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2005 Vojtech Pavlik
*/
/*
* Microsoft SideWinder joystick family driver for Linux
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/gameport.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "Microsoft SideWinder joystick family driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* These are really magic values. Changing them can make a problem go away,
* as well as break everything.
*/
#undef SW_DEBUG
#undef SW_DEBUG_DATA
#define SW_START 600 /* The time we wait for the first bit [600 us] */
#define SW_STROBE 60 /* Max time per bit [60 us] */
#define SW_TIMEOUT 6 /* Wait for everything to settle [6 ms] */
#define SW_KICK 45 /* Wait after A0 fall till kick [45 us] */
#define SW_END 8 /* Number of bits before end of packet to kick */
#define SW_FAIL 16 /* Number of packet read errors to fail and reinitialize */
#define SW_BAD 2 /* Number of packet read errors to switch off 3d Pro optimization */
#define SW_OK 64 /* Number of packet read successes to switch optimization back on */
#define SW_LENGTH 512 /* Max number of bits in a packet */
#ifdef SW_DEBUG
#define dbg(format, arg...) printk(KERN_DEBUG __FILE__ ": " format "\n" , ## arg)
#else
#define dbg(format, arg...) do {} while (0)
#endif
/*
* SideWinder joystick types ...
*/
#define SW_ID_3DP 0
#define SW_ID_GP 1
#define SW_ID_PP 2
#define SW_ID_FFP 3
#define SW_ID_FSP 4
#define SW_ID_FFW 5
/*
* Names, buttons, axes ...
*/
static char *sw_name[] = { "3D Pro", "GamePad", "Precision Pro", "Force Feedback Pro", "FreeStyle Pro",
"Force Feedback Wheel" };
static char sw_abs[][7] = {
{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
{ ABS_X, ABS_Y },
{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
{ ABS_X, ABS_Y, ABS_RZ, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y },
{ ABS_RX, ABS_RUDDER, ABS_THROTTLE }};
static char sw_bit[][7] = {
{ 10, 10, 9, 10, 1, 1 },
{ 1, 1 },
{ 10, 10, 6, 7, 1, 1 },
{ 10, 10, 6, 7, 1, 1 },
{ 10, 10, 6, 1, 1 },
{ 10, 7, 7, 1, 1 }};
static short sw_btn[][12] = {
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_THUMB2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_MODE },
{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START, BTN_MODE },
{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_SELECT },
{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_SELECT },
{ BTN_A, BTN_B, BTN_C, BTN_X, BTN_Y, BTN_Z, BTN_TL, BTN_TR, BTN_START, BTN_MODE, BTN_SELECT },
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_THUMB2, BTN_BASE, BTN_BASE2, BTN_BASE3, BTN_BASE4 }};
static struct {
int x;
int y;
} sw_hat_to_axis[] = {{ 0, 0}, { 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}};
struct sw {
struct gameport *gameport;
struct input_dev *dev[4];
char name[64];
char phys[4][32];
int length;
int type;
int bits;
int number;
int fail;
int ok;
int reads;
int bads;
};
/*
* sw_read_packet() is a function which reads either a data packet, or an
* identification packet from a SideWinder joystick. The protocol is very,
* very, very braindamaged. Microsoft patented it in US patent #5628686.
*/
static int sw_read_packet(struct gameport *gameport, unsigned char *buf, int length, int id)
{
unsigned long flags;
int timeout, bitout, sched, i, kick, start, strobe;
unsigned char pending, u, v;
i = -id; /* Don't care about data, only want ID */
timeout = id ? gameport_time(gameport, SW_TIMEOUT * 1000) : 0; /* Set up global timeout for ID packet */
kick = id ? gameport_time(gameport, SW_KICK) : 0; /* Set up kick timeout for ID packet */
start = gameport_time(gameport, SW_START);
strobe = gameport_time(gameport, SW_STROBE);
bitout = start;
pending = 0;
sched = 0;
local_irq_save(flags); /* Quiet, please */
gameport_trigger(gameport); /* Trigger */
v = gameport_read(gameport);
do {
bitout--;
u = v;
v = gameport_read(gameport);
} while (!(~v & u & 0x10) && (bitout > 0)); /* Wait for first falling edge on clock */
if (bitout > 0)
bitout = strobe; /* Extend time if not timed out */
while ((timeout > 0 || bitout > 0) && (i < length)) {
timeout--;
bitout--; /* Decrement timers */
sched--;
u = v;
v = gameport_read(gameport);
if ((~u & v & 0x10) && (bitout > 0)) { /* Rising edge on clock - data bit */
if (i >= 0) /* Want this data */
buf[i] = v >> 5; /* Store it */
i++; /* Advance index */
bitout = strobe; /* Extend timeout for next bit */
}
if (kick && (~v & u & 0x01)) { /* Falling edge on axis 0 */
sched = kick; /* Schedule second trigger */
kick = 0; /* Don't schedule next time on falling edge */
pending = 1; /* Mark schedule */
}
if (pending && sched < 0 && (i > -SW_END)) { /* Second trigger time */
gameport_trigger(gameport); /* Trigger */
bitout = start; /* Long bit timeout */
pending = 0; /* Unmark schedule */
timeout = 0; /* Switch from global to bit timeouts */
}
}
local_irq_restore(flags); /* Done - relax */
#ifdef SW_DEBUG_DATA
{
int j;
printk(KERN_DEBUG "sidewinder.c: Read %d triplets. [", i);
for (j = 0; j < i; j++) printk("%d", buf[j]);
printk("]\n");
}
#endif
return i;
}
/*
* sw_get_bits() and GB() compose bits from the triplet buffer into a __u64.
* Parameter 'pos' is bit number inside packet where to start at, 'num' is number
* of bits to be read, 'shift' is offset in the resulting __u64 to start at, bits
* is number of bits per triplet.
*/
#define GB(pos,num) sw_get_bits(buf, pos, num, sw->bits)
static __u64 sw_get_bits(unsigned char *buf, int pos, int num, char bits)
{
__u64 data = 0;
int tri = pos % bits; /* Start position */
int i = pos / bits;
int bit = 0;
while (num--) {
data |= (__u64)((buf[i] >> tri++) & 1) << bit++; /* Transfer bit */
if (tri == bits) {
i++; /* Next triplet */
tri = 0;
}
}
return data;
}
/*
* sw_init_digital() initializes a SideWinder 3D Pro joystick
* into digital mode.
*/
static void sw_init_digital(struct gameport *gameport)
{
static const int seq[] = { 140, 140+725, 140+300, 0 };
unsigned long flags;
int i, t;
local_irq_save(flags);
i = 0;
do {
gameport_trigger(gameport); /* Trigger */
t = gameport_time(gameport, SW_TIMEOUT * 1000);
while ((gameport_read(gameport) & 1) && t) t--; /* Wait for axis to fall back to 0 */
udelay(seq[i]); /* Delay magic time */
} while (seq[++i]);
gameport_trigger(gameport); /* Last trigger */
local_irq_restore(flags);
}
/*
* sw_parity() computes parity of __u64
*/
static int sw_parity(__u64 t)
{
int x = t ^ (t >> 32);
x ^= x >> 16;
x ^= x >> 8;
x ^= x >> 4;
x ^= x >> 2;
x ^= x >> 1;
return x & 1;
}
/*
* sw_ccheck() checks synchronization bits and computes checksum of nibbles.
*/
static int sw_check(__u64 t)
{
unsigned char sum = 0;
if ((t & 0x8080808080808080ULL) ^ 0x80) /* Sync */
return -1;
while (t) { /* Sum */
sum += t & 0xf;
t >>= 4;
}
return sum & 0xf;
}
/*
* sw_parse() analyzes SideWinder joystick data, and writes the results into
* the axes and buttons arrays.
*/
static int sw_parse(unsigned char *buf, struct sw *sw)
{
int hat, i, j;
struct input_dev *dev;
switch (sw->type) {
case SW_ID_3DP:
if (sw_check(GB(0,64)) || (hat = (GB(6,1) << 3) | GB(60,3)) > 8)
return -1;
dev = sw->dev[0];
input_report_abs(dev, ABS_X, (GB( 3,3) << 7) | GB(16,7));
input_report_abs(dev, ABS_Y, (GB( 0,3) << 7) | GB(24,7));
input_report_abs(dev, ABS_RZ, (GB(35,2) << 7) | GB(40,7));
input_report_abs(dev, ABS_THROTTLE, (GB(32,3) << 7) | GB(48,7));
input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
for (j = 0; j < 7; j++)
input_report_key(dev, sw_btn[SW_ID_3DP][j], !GB(j+8,1));
input_report_key(dev, BTN_BASE4, !GB(38,1));
input_report_key(dev, BTN_BASE5, !GB(37,1));
input_sync(dev);
return 0;
case SW_ID_GP:
for (i = 0; i < sw->number; i ++) {
if (sw_parity(GB(i*15,15)))
return -1;
input_report_abs(sw->dev[i], ABS_X, GB(i*15+3,1) - GB(i*15+2,1));
input_report_abs(sw->dev[i], ABS_Y, GB(i*15+0,1) - GB(i*15+1,1));
for (j = 0; j < 10; j++)
input_report_key(sw->dev[i], sw_btn[SW_ID_GP][j], !GB(i*15+j+4,1));
input_sync(sw->dev[i]);
}
return 0;
case SW_ID_PP:
case SW_ID_FFP:
if (!sw_parity(GB(0,48)) || (hat = GB(42,4)) > 8)
return -1;
dev = sw->dev[0];
input_report_abs(dev, ABS_X, GB( 9,10));
input_report_abs(dev, ABS_Y, GB(19,10));
input_report_abs(dev, ABS_RZ, GB(36, 6));
input_report_abs(dev, ABS_THROTTLE, GB(29, 7));
input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
for (j = 0; j < 9; j++)
input_report_key(dev, sw_btn[SW_ID_PP][j], !GB(j,1));
input_sync(dev);
return 0;
case SW_ID_FSP:
if (!sw_parity(GB(0,43)) || (hat = GB(28,4)) > 8)
return -1;
dev = sw->dev[0];
input_report_abs(dev, ABS_X, GB( 0,10));
input_report_abs(dev, ABS_Y, GB(16,10));
input_report_abs(dev, ABS_THROTTLE, GB(32, 6));
input_report_abs(dev, ABS_HAT0X, sw_hat_to_axis[hat].x);
input_report_abs(dev, ABS_HAT0Y, sw_hat_to_axis[hat].y);
for (j = 0; j < 6; j++)
input_report_key(dev, sw_btn[SW_ID_FSP][j], !GB(j+10,1));
input_report_key(dev, BTN_TR, !GB(26,1));
input_report_key(dev, BTN_START, !GB(27,1));
input_report_key(dev, BTN_MODE, !GB(38,1));
input_report_key(dev, BTN_SELECT, !GB(39,1));
input_sync(dev);
return 0;
case SW_ID_FFW:
if (!sw_parity(GB(0,33)))
return -1;
dev = sw->dev[0];
input_report_abs(dev, ABS_RX, GB( 0,10));
input_report_abs(dev, ABS_RUDDER, GB(10, 6));
input_report_abs(dev, ABS_THROTTLE, GB(16, 6));
for (j = 0; j < 8; j++)
input_report_key(dev, sw_btn[SW_ID_FFW][j], !GB(j+22,1));
input_sync(dev);
return 0;
}
return -1;
}
/*
* sw_read() reads SideWinder joystick data, and reinitializes
* the joystick in case of persistent problems. This is the function that is
* called from the generic code to poll the joystick.
*/
static int sw_read(struct sw *sw)
{
unsigned char buf[SW_LENGTH];
int i;
i = sw_read_packet(sw->gameport, buf, sw->length, 0);
if (sw->type == SW_ID_3DP && sw->length == 66 && i != 66) { /* Broken packet, try to fix */
if (i == 64 && !sw_check(sw_get_bits(buf,0,64,1))) { /* Last init failed, 1 bit mode */
printk(KERN_WARNING "sidewinder.c: Joystick in wrong mode on %s"
" - going to reinitialize.\n", sw->gameport->phys);
sw->fail = SW_FAIL; /* Reinitialize */
i = 128; /* Bogus value */
}
if (i < 66 && GB(0,64) == GB(i*3-66,64)) /* 1 == 3 */
i = 66; /* Everything is fine */
if (i < 66 && GB(0,64) == GB(66,64)) /* 1 == 2 */
i = 66; /* Everything is fine */
if (i < 66 && GB(i*3-132,64) == GB(i*3-66,64)) { /* 2 == 3 */
memmove(buf, buf + i - 22, 22); /* Move data */
i = 66; /* Carry on */
}
}
if (i == sw->length && !sw_parse(buf, sw)) { /* Parse data */
sw->fail = 0;
sw->ok++;
if (sw->type == SW_ID_3DP && sw->length == 66 /* Many packets OK */
&& sw->ok > SW_OK) {
printk(KERN_INFO "sidewinder.c: No more trouble on %s"
" - enabling optimization again.\n", sw->gameport->phys);
sw->length = 22;
}
return 0;
}
sw->ok = 0;
sw->fail++;
if (sw->type == SW_ID_3DP && sw->length == 22 && sw->fail > SW_BAD) { /* Consecutive bad packets */
printk(KERN_INFO "sidewinder.c: Many bit errors on %s"
" - disabling optimization.\n", sw->gameport->phys);
sw->length = 66;
}
if (sw->fail < SW_FAIL)
return -1; /* Not enough, don't reinitialize yet */
printk(KERN_WARNING "sidewinder.c: Too many bit errors on %s"
" - reinitializing joystick.\n", sw->gameport->phys);
if (!i && sw->type == SW_ID_3DP) { /* 3D Pro can be in analog mode */
mdelay(3 * SW_TIMEOUT);
sw_init_digital(sw->gameport);
}
mdelay(SW_TIMEOUT);
i = sw_read_packet(sw->gameport, buf, SW_LENGTH, 0); /* Read normal data packet */
mdelay(SW_TIMEOUT);
sw_read_packet(sw->gameport, buf, SW_LENGTH, i); /* Read ID packet, this initializes the stick */
sw->fail = SW_FAIL;
return -1;
}
static void sw_poll(struct gameport *gameport)
{
struct sw *sw = gameport_get_drvdata(gameport);
sw->reads++;
if (sw_read(sw))
sw->bads++;
}
static int sw_open(struct input_dev *dev)
{
struct sw *sw = input_get_drvdata(dev);
gameport_start_polling(sw->gameport);
return 0;
}
static void sw_close(struct input_dev *dev)
{
struct sw *sw = input_get_drvdata(dev);
gameport_stop_polling(sw->gameport);
}
/*
* sw_print_packet() prints the contents of a SideWinder packet.
*/
static void sw_print_packet(char *name, int length, unsigned char *buf, char bits)
{
int i;
printk(KERN_INFO "sidewinder.c: %s packet, %d bits. [", name, length);
for (i = (((length + 3) >> 2) - 1); i >= 0; i--)
printk("%x", (int)sw_get_bits(buf, i << 2, 4, bits));
printk("]\n");
}
/*
* sw_3dp_id() translates the 3DP id into a human legible string.
* Unfortunately I don't know how to do this for the other SW types.
*/
static void sw_3dp_id(unsigned char *buf, char *comment, size_t size)
{
int i;
char pnp[8], rev[9];
for (i = 0; i < 7; i++) /* ASCII PnP ID */
pnp[i] = sw_get_bits(buf, 24+8*i, 8, 1);
for (i = 0; i < 8; i++) /* ASCII firmware revision */
rev[i] = sw_get_bits(buf, 88+8*i, 8, 1);
pnp[7] = rev[8] = 0;
snprintf(comment, size, " [PnP %d.%02d id %s rev %s]",
(int) ((sw_get_bits(buf, 8, 6, 1) << 6) | /* Two 6-bit values */
sw_get_bits(buf, 16, 6, 1)) / 100,
(int) ((sw_get_bits(buf, 8, 6, 1) << 6) |
sw_get_bits(buf, 16, 6, 1)) % 100,
pnp, rev);
}
/*
* sw_guess_mode() checks the upper two button bits for toggling -
* indication of that the joystick is in 3-bit mode. This is documented
* behavior for 3DP ID packet, and for example the FSP does this in
* normal packets instead. Fun ...
*/
static int sw_guess_mode(unsigned char *buf, int len)
{
int i;
unsigned char xor = 0;
for (i = 1; i < len; i++)
xor |= (buf[i - 1] ^ buf[i]) & 6;
return !!xor * 2 + 1;
}
/*
* sw_connect() probes for SideWinder type joysticks.
*/
static int sw_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct sw *sw;
struct input_dev *input_dev;
int i, j, k, l;
int err = 0;
unsigned char *buf = NULL; /* [SW_LENGTH] */
unsigned char *idbuf = NULL; /* [SW_LENGTH] */
unsigned char m = 1;
char comment[40];
comment[0] = 0;
sw = kzalloc(sizeof(struct sw), GFP_KERNEL);
buf = kmalloc(SW_LENGTH, GFP_KERNEL);
idbuf = kmalloc(SW_LENGTH, GFP_KERNEL);
if (!sw || !buf || !idbuf) {
err = -ENOMEM;
goto fail1;
}
sw->gameport = gameport;
gameport_set_drvdata(gameport, sw);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
dbg("Init 0: Opened %s, io %#x, speed %d",
gameport->phys, gameport->io, gameport->speed);
i = sw_read_packet(gameport, buf, SW_LENGTH, 0); /* Read normal packet */
msleep(SW_TIMEOUT);
dbg("Init 1: Mode %d. Length %d.", m , i);
if (!i) { /* No data. 3d Pro analog mode? */
sw_init_digital(gameport); /* Switch to digital */
msleep(SW_TIMEOUT);
i = sw_read_packet(gameport, buf, SW_LENGTH, 0); /* Retry reading packet */
msleep(SW_TIMEOUT);
dbg("Init 1b: Length %d.", i);
if (!i) { /* No data -> FAIL */
err = -ENODEV;
goto fail2;
}
}
j = sw_read_packet(gameport, idbuf, SW_LENGTH, i); /* Read ID. This initializes the stick */
m |= sw_guess_mode(idbuf, j); /* ID packet should carry mode info [3DP] */
dbg("Init 2: Mode %d. ID Length %d.", m, j);
if (j <= 0) { /* Read ID failed. Happens in 1-bit mode on PP */
msleep(SW_TIMEOUT);
i = sw_read_packet(gameport, buf, SW_LENGTH, 0); /* Retry reading packet */
m |= sw_guess_mode(buf, i);
dbg("Init 2b: Mode %d. Length %d.", m, i);
if (!i) {
err = -ENODEV;
goto fail2;
}
msleep(SW_TIMEOUT);
j = sw_read_packet(gameport, idbuf, SW_LENGTH, i); /* Retry reading ID */
dbg("Init 2c: ID Length %d.", j);
}
sw->type = -1;
k = SW_FAIL; /* Try SW_FAIL times */
l = 0;
do {
k--;
msleep(SW_TIMEOUT);
i = sw_read_packet(gameport, buf, SW_LENGTH, 0); /* Read data packet */
dbg("Init 3: Mode %d. Length %d. Last %d. Tries %d.", m, i, l, k);
if (i > l) { /* Longer? As we can only lose bits, it makes */
/* no sense to try detection for a packet shorter */
l = i; /* than the previous one */
sw->number = 1;
sw->gameport = gameport;
sw->length = i;
sw->bits = m;
dbg("Init 3a: Case %d.\n", i * m);
switch (i * m) {
case 60:
sw->number++;
fallthrough;
case 45: /* Ambiguous packet length */
if (j <= 40) { /* ID length less or eq 40 -> FSP */
fallthrough;
case 43:
sw->type = SW_ID_FSP;
break;
}
sw->number++;
fallthrough;
case 30:
sw->number++;
fallthrough;
case 15:
sw->type = SW_ID_GP;
break;
case 33:
case 31:
sw->type = SW_ID_FFW;
break;
case 48: /* Ambiguous */
if (j == 14) { /* ID length 14*3 -> FFP */
sw->type = SW_ID_FFP;
sprintf(comment, " [AC %s]", sw_get_bits(idbuf,38,1,3) ? "off" : "on");
} else
sw->type = SW_ID_PP;
break;
case 66:
sw->bits = 3;
fallthrough;
case 198:
sw->length = 22;
fallthrough;
case 64:
sw->type = SW_ID_3DP;
if (j == 160)
sw_3dp_id(idbuf, comment, sizeof(comment));
break;
}
}
} while (k && sw->type == -1);
if (sw->type == -1) {
printk(KERN_WARNING "sidewinder.c: unknown joystick device detected "
"on %s, contact <[email protected]>\n", gameport->phys);
sw_print_packet("ID", j * 3, idbuf, 3);
sw_print_packet("Data", i * m, buf, m);
err = -ENODEV;
goto fail2;
}
#ifdef SW_DEBUG
sw_print_packet("ID", j * 3, idbuf, 3);
sw_print_packet("Data", i * m, buf, m);
#endif
gameport_set_poll_handler(gameport, sw_poll);
gameport_set_poll_interval(gameport, 20);
k = i;
l = j;
for (i = 0; i < sw->number; i++) {
int bits, code;
snprintf(sw->name, sizeof(sw->name),
"Microsoft SideWinder %s", sw_name[sw->type]);
snprintf(sw->phys[i], sizeof(sw->phys[i]),
"%s/input%d", gameport->phys, i);
sw->dev[i] = input_dev = input_allocate_device();
if (!input_dev) {
err = -ENOMEM;
goto fail3;
}
input_dev->name = sw->name;
input_dev->phys = sw->phys[i];
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_MICROSOFT;
input_dev->id.product = sw->type;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &gameport->dev;
input_set_drvdata(input_dev, sw);
input_dev->open = sw_open;
input_dev->close = sw_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
for (j = 0; (bits = sw_bit[sw->type][j]); j++) {
int min, max, fuzz, flat;
code = sw_abs[sw->type][j];
min = bits == 1 ? -1 : 0;
max = (1 << bits) - 1;
fuzz = (bits >> 1) >= 2 ? 1 << ((bits >> 1) - 2) : 0;
flat = code == ABS_THROTTLE || bits < 5 ?
0 : 1 << (bits - 5);
input_set_abs_params(input_dev, code,
min, max, fuzz, flat);
}
for (j = 0; (code = sw_btn[sw->type][j]); j++)
__set_bit(code, input_dev->keybit);
dbg("%s%s [%d-bit id %d data %d]\n", sw->name, comment, m, l, k);
err = input_register_device(sw->dev[i]);
if (err)
goto fail4;
}
out: kfree(buf);
kfree(idbuf);
return err;
fail4: input_free_device(sw->dev[i]);
fail3: while (--i >= 0)
input_unregister_device(sw->dev[i]);
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(sw);
goto out;
}
static void sw_disconnect(struct gameport *gameport)
{
struct sw *sw = gameport_get_drvdata(gameport);
int i;
for (i = 0; i < sw->number; i++)
input_unregister_device(sw->dev[i]);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(sw);
}
static struct gameport_driver sw_drv = {
.driver = {
.name = "sidewinder",
.owner = THIS_MODULE,
},
.description = DRIVER_DESC,
.connect = sw_connect,
.disconnect = sw_disconnect,
};
module_gameport_driver(sw_drv);
|
linux-master
|
drivers/input/joystick/sidewinder.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1998-2001 Vojtech Pavlik
*/
/*
* FP-Gaming Assassin 3D joystick driver for Linux
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/input.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "FP-Gaming Assassin 3D joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define A3D_MAX_START 600 /* 600 us */
#define A3D_MAX_STROBE 80 /* 80 us */
#define A3D_MAX_LENGTH 40 /* 40*3 bits */
#define A3D_MODE_A3D 1 /* Assassin 3D */
#define A3D_MODE_PAN 2 /* Panther */
#define A3D_MODE_OEM 3 /* Panther OEM version */
#define A3D_MODE_PXL 4 /* Panther XL */
static char *a3d_names[] = { NULL, "FP-Gaming Assassin 3D", "MadCatz Panther", "OEM Panther",
"MadCatz Panther XL", "MadCatz Panther XL w/ rudder" };
struct a3d {
struct gameport *gameport;
struct gameport *adc;
struct input_dev *dev;
int axes[4];
int buttons;
int mode;
int length;
int reads;
int bads;
char phys[32];
};
/*
* a3d_read_packet() reads an Assassin 3D packet.
*/
static int a3d_read_packet(struct gameport *gameport, int length, char *data)
{
unsigned long flags;
unsigned char u, v;
unsigned int t, s;
int i;
i = 0;
t = gameport_time(gameport, A3D_MAX_START);
s = gameport_time(gameport, A3D_MAX_STROBE);
local_irq_save(flags);
gameport_trigger(gameport);
v = gameport_read(gameport);
while (t > 0 && i < length) {
t--;
u = v; v = gameport_read(gameport);
if (~v & u & 0x10) {
data[i++] = v >> 5;
t = s;
}
}
local_irq_restore(flags);
return i;
}
/*
* a3d_csum() computes checksum of triplet packet
*/
static int a3d_csum(char *data, int count)
{
int i, csum = 0;
for (i = 0; i < count - 2; i++)
csum += data[i];
return (csum & 0x3f) != ((data[count - 2] << 3) | data[count - 1]);
}
static void a3d_read(struct a3d *a3d, unsigned char *data)
{
struct input_dev *dev = a3d->dev;
switch (a3d->mode) {
case A3D_MODE_A3D:
case A3D_MODE_OEM:
case A3D_MODE_PAN:
input_report_rel(dev, REL_X, ((data[5] << 6) | (data[6] << 3) | data[ 7]) - ((data[5] & 4) << 7));
input_report_rel(dev, REL_Y, ((data[8] << 6) | (data[9] << 3) | data[10]) - ((data[8] & 4) << 7));
input_report_key(dev, BTN_RIGHT, data[2] & 1);
input_report_key(dev, BTN_LEFT, data[3] & 2);
input_report_key(dev, BTN_MIDDLE, data[3] & 4);
input_sync(dev);
a3d->axes[0] = ((signed char)((data[11] << 6) | (data[12] << 3) | (data[13]))) + 128;
a3d->axes[1] = ((signed char)((data[14] << 6) | (data[15] << 3) | (data[16]))) + 128;
a3d->axes[2] = ((signed char)((data[17] << 6) | (data[18] << 3) | (data[19]))) + 128;
a3d->axes[3] = ((signed char)((data[20] << 6) | (data[21] << 3) | (data[22]))) + 128;
a3d->buttons = ((data[3] << 3) | data[4]) & 0xf;
break;
case A3D_MODE_PXL:
input_report_rel(dev, REL_X, ((data[ 9] << 6) | (data[10] << 3) | data[11]) - ((data[ 9] & 4) << 7));
input_report_rel(dev, REL_Y, ((data[12] << 6) | (data[13] << 3) | data[14]) - ((data[12] & 4) << 7));
input_report_key(dev, BTN_RIGHT, data[2] & 1);
input_report_key(dev, BTN_LEFT, data[3] & 2);
input_report_key(dev, BTN_MIDDLE, data[3] & 4);
input_report_key(dev, BTN_SIDE, data[7] & 2);
input_report_key(dev, BTN_EXTRA, data[7] & 4);
input_report_abs(dev, ABS_X, ((signed char)((data[15] << 6) | (data[16] << 3) | (data[17]))) + 128);
input_report_abs(dev, ABS_Y, ((signed char)((data[18] << 6) | (data[19] << 3) | (data[20]))) + 128);
input_report_abs(dev, ABS_RUDDER, ((signed char)((data[21] << 6) | (data[22] << 3) | (data[23]))) + 128);
input_report_abs(dev, ABS_THROTTLE, ((signed char)((data[24] << 6) | (data[25] << 3) | (data[26]))) + 128);
input_report_abs(dev, ABS_HAT0X, ( data[5] & 1) - ((data[5] >> 2) & 1));
input_report_abs(dev, ABS_HAT0Y, ((data[5] >> 1) & 1) - ((data[6] >> 2) & 1));
input_report_abs(dev, ABS_HAT1X, ((data[4] >> 1) & 1) - ( data[3] & 1));
input_report_abs(dev, ABS_HAT1Y, ((data[4] >> 2) & 1) - ( data[4] & 1));
input_report_key(dev, BTN_TRIGGER, data[8] & 1);
input_report_key(dev, BTN_THUMB, data[8] & 2);
input_report_key(dev, BTN_TOP, data[8] & 4);
input_report_key(dev, BTN_PINKIE, data[7] & 1);
input_sync(dev);
break;
}
}
/*
* a3d_poll() reads and analyzes A3D joystick data.
*/
static void a3d_poll(struct gameport *gameport)
{
struct a3d *a3d = gameport_get_drvdata(gameport);
unsigned char data[A3D_MAX_LENGTH];
a3d->reads++;
if (a3d_read_packet(a3d->gameport, a3d->length, data) != a3d->length ||
data[0] != a3d->mode || a3d_csum(data, a3d->length))
a3d->bads++;
else
a3d_read(a3d, data);
}
/*
* a3d_adc_cooked_read() copies the acis and button data to the
* callers arrays. It could do the read itself, but the caller could
* call this more than 50 times a second, which would use too much CPU.
*/
static int a3d_adc_cooked_read(struct gameport *gameport, int *axes, int *buttons)
{
struct a3d *a3d = gameport->port_data;
int i;
for (i = 0; i < 4; i++)
axes[i] = (a3d->axes[i] < 254) ? a3d->axes[i] : -1;
*buttons = a3d->buttons;
return 0;
}
/*
* a3d_adc_open() is the gameport open routine. It refuses to serve
* any but cooked data.
*/
static int a3d_adc_open(struct gameport *gameport, int mode)
{
struct a3d *a3d = gameport->port_data;
if (mode != GAMEPORT_MODE_COOKED)
return -1;
gameport_start_polling(a3d->gameport);
return 0;
}
/*
* a3d_adc_close() is a callback from the input close routine.
*/
static void a3d_adc_close(struct gameport *gameport)
{
struct a3d *a3d = gameport->port_data;
gameport_stop_polling(a3d->gameport);
}
/*
* a3d_open() is a callback from the input open routine.
*/
static int a3d_open(struct input_dev *dev)
{
struct a3d *a3d = input_get_drvdata(dev);
gameport_start_polling(a3d->gameport);
return 0;
}
/*
* a3d_close() is a callback from the input close routine.
*/
static void a3d_close(struct input_dev *dev)
{
struct a3d *a3d = input_get_drvdata(dev);
gameport_stop_polling(a3d->gameport);
}
/*
* a3d_connect() probes for A3D joysticks.
*/
static int a3d_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct a3d *a3d;
struct input_dev *input_dev;
struct gameport *adc;
unsigned char data[A3D_MAX_LENGTH];
int i;
int err;
a3d = kzalloc(sizeof(struct a3d), GFP_KERNEL);
input_dev = input_allocate_device();
if (!a3d || !input_dev) {
err = -ENOMEM;
goto fail1;
}
a3d->dev = input_dev;
a3d->gameport = gameport;
gameport_set_drvdata(gameport, a3d);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
i = a3d_read_packet(gameport, A3D_MAX_LENGTH, data);
if (!i || a3d_csum(data, i)) {
err = -ENODEV;
goto fail2;
}
a3d->mode = data[0];
if (!a3d->mode || a3d->mode > 5) {
printk(KERN_WARNING "a3d.c: Unknown A3D device detected "
"(%s, id=%d), contact <[email protected]>\n", gameport->phys, a3d->mode);
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, a3d_poll);
gameport_set_poll_interval(gameport, 20);
snprintf(a3d->phys, sizeof(a3d->phys), "%s/input0", gameport->phys);
input_dev->name = a3d_names[a3d->mode];
input_dev->phys = a3d->phys;
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_MADCATZ;
input_dev->id.product = a3d->mode;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &gameport->dev;
input_dev->open = a3d_open;
input_dev->close = a3d_close;
input_set_drvdata(input_dev, a3d);
if (a3d->mode == A3D_MODE_PXL) {
int axes[] = { ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER };
a3d->length = 33;
input_dev->evbit[0] |= BIT_MASK(EV_ABS) | BIT_MASK(EV_KEY) |
BIT_MASK(EV_REL);
input_dev->relbit[0] |= BIT_MASK(REL_X) | BIT_MASK(REL_Y);
input_dev->absbit[0] |= BIT_MASK(ABS_X) | BIT_MASK(ABS_Y) |
BIT_MASK(ABS_THROTTLE) | BIT_MASK(ABS_RUDDER) |
BIT_MASK(ABS_HAT0X) | BIT_MASK(ABS_HAT0Y) |
BIT_MASK(ABS_HAT1X) | BIT_MASK(ABS_HAT1Y);
input_dev->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_RIGHT) |
BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE) |
BIT_MASK(BTN_SIDE) | BIT_MASK(BTN_EXTRA);
input_dev->keybit[BIT_WORD(BTN_JOYSTICK)] |=
BIT_MASK(BTN_TRIGGER) | BIT_MASK(BTN_THUMB) |
BIT_MASK(BTN_TOP) | BIT_MASK(BTN_PINKIE);
a3d_read(a3d, data);
for (i = 0; i < 4; i++) {
if (i < 2)
input_set_abs_params(input_dev, axes[i],
48, input_abs_get_val(input_dev, axes[i]) * 2 - 48, 0, 8);
else
input_set_abs_params(input_dev, axes[i], 2, 253, 0, 0);
input_set_abs_params(input_dev, ABS_HAT0X + i, -1, 1, 0, 0);
}
} else {
a3d->length = 29;
input_dev->evbit[0] |= BIT_MASK(EV_KEY) | BIT_MASK(EV_REL);
input_dev->relbit[0] |= BIT_MASK(REL_X) | BIT_MASK(REL_Y);
input_dev->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_RIGHT) |
BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_MIDDLE);
a3d_read(a3d, data);
if (!(a3d->adc = adc = gameport_allocate_port()))
printk(KERN_ERR "a3d: Not enough memory for ADC port\n");
else {
adc->port_data = a3d;
adc->open = a3d_adc_open;
adc->close = a3d_adc_close;
adc->cooked_read = a3d_adc_cooked_read;
adc->fuzz = 1;
gameport_set_name(adc, a3d_names[a3d->mode]);
gameport_set_phys(adc, "%s/gameport0", gameport->phys);
adc->dev.parent = &gameport->dev;
gameport_register_port(adc);
}
}
err = input_register_device(a3d->dev);
if (err)
goto fail3;
return 0;
fail3: if (a3d->adc)
gameport_unregister_port(a3d->adc);
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
input_free_device(input_dev);
kfree(a3d);
return err;
}
static void a3d_disconnect(struct gameport *gameport)
{
struct a3d *a3d = gameport_get_drvdata(gameport);
input_unregister_device(a3d->dev);
if (a3d->adc)
gameport_unregister_port(a3d->adc);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(a3d);
}
static struct gameport_driver a3d_drv = {
.driver = {
.name = "adc",
.owner = THIS_MODULE,
},
.description = DRIVER_DESC,
.connect = a3d_connect,
.disconnect = a3d_disconnect,
};
module_gameport_driver(a3d_drv);
|
linux-master
|
drivers/input/joystick/a3d.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* Creative Labs Blaster GamePad Cobra driver for Linux
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/gameport.h>
#include <linux/input.h>
#include <linux/jiffies.h>
#define DRIVER_DESC "Creative Labs Blaster GamePad Cobra driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define COBRA_MAX_STROBE 45 /* 45 us max wait for first strobe */
#define COBRA_LENGTH 36
static int cobra_btn[] = { BTN_START, BTN_SELECT, BTN_TL, BTN_TR, BTN_X, BTN_Y, BTN_Z, BTN_A, BTN_B, BTN_C, BTN_TL2, BTN_TR2, 0 };
struct cobra {
struct gameport *gameport;
struct input_dev *dev[2];
int reads;
int bads;
unsigned char exists;
char phys[2][32];
};
static unsigned char cobra_read_packet(struct gameport *gameport, unsigned int *data)
{
unsigned long flags;
unsigned char u, v, w;
__u64 buf[2];
int r[2], t[2];
int i, j, ret;
int strobe = gameport_time(gameport, COBRA_MAX_STROBE);
for (i = 0; i < 2; i++) {
r[i] = buf[i] = 0;
t[i] = COBRA_MAX_STROBE;
}
local_irq_save(flags);
u = gameport_read(gameport);
do {
t[0]--; t[1]--;
v = gameport_read(gameport);
for (i = 0, w = u ^ v; i < 2 && w; i++, w >>= 2)
if (w & 0x30) {
if ((w & 0x30) < 0x30 && r[i] < COBRA_LENGTH && t[i] > 0) {
buf[i] |= (__u64)((w >> 5) & 1) << r[i]++;
t[i] = strobe;
u = v;
} else t[i] = 0;
}
} while (t[0] > 0 || t[1] > 0);
local_irq_restore(flags);
ret = 0;
for (i = 0; i < 2; i++) {
if (r[i] != COBRA_LENGTH) continue;
for (j = 0; j < COBRA_LENGTH && (buf[i] & 0x04104107f) ^ 0x041041040; j++)
buf[i] = (buf[i] >> 1) | ((__u64)(buf[i] & 1) << (COBRA_LENGTH - 1));
if (j < COBRA_LENGTH) ret |= (1 << i);
data[i] = ((buf[i] >> 7) & 0x000001f) | ((buf[i] >> 8) & 0x00003e0)
| ((buf[i] >> 9) & 0x0007c00) | ((buf[i] >> 10) & 0x00f8000)
| ((buf[i] >> 11) & 0x1f00000);
}
return ret;
}
static void cobra_poll(struct gameport *gameport)
{
struct cobra *cobra = gameport_get_drvdata(gameport);
struct input_dev *dev;
unsigned int data[2];
int i, j, r;
cobra->reads++;
if ((r = cobra_read_packet(gameport, data)) != cobra->exists) {
cobra->bads++;
return;
}
for (i = 0; i < 2; i++)
if (cobra->exists & r & (1 << i)) {
dev = cobra->dev[i];
input_report_abs(dev, ABS_X, ((data[i] >> 4) & 1) - ((data[i] >> 3) & 1));
input_report_abs(dev, ABS_Y, ((data[i] >> 2) & 1) - ((data[i] >> 1) & 1));
for (j = 0; cobra_btn[j]; j++)
input_report_key(dev, cobra_btn[j], data[i] & (0x20 << j));
input_sync(dev);
}
}
static int cobra_open(struct input_dev *dev)
{
struct cobra *cobra = input_get_drvdata(dev);
gameport_start_polling(cobra->gameport);
return 0;
}
static void cobra_close(struct input_dev *dev)
{
struct cobra *cobra = input_get_drvdata(dev);
gameport_stop_polling(cobra->gameport);
}
static int cobra_connect(struct gameport *gameport, struct gameport_driver *drv)
{
struct cobra *cobra;
struct input_dev *input_dev;
unsigned int data[2];
int i, j;
int err;
cobra = kzalloc(sizeof(struct cobra), GFP_KERNEL);
if (!cobra)
return -ENOMEM;
cobra->gameport = gameport;
gameport_set_drvdata(gameport, cobra);
err = gameport_open(gameport, drv, GAMEPORT_MODE_RAW);
if (err)
goto fail1;
cobra->exists = cobra_read_packet(gameport, data);
for (i = 0; i < 2; i++)
if ((cobra->exists >> i) & data[i] & 1) {
printk(KERN_WARNING "cobra.c: Device %d on %s has the Ext bit set. ID is: %d"
" Contact [email protected]\n", i, gameport->phys, (data[i] >> 2) & 7);
cobra->exists &= ~(1 << i);
}
if (!cobra->exists) {
err = -ENODEV;
goto fail2;
}
gameport_set_poll_handler(gameport, cobra_poll);
gameport_set_poll_interval(gameport, 20);
for (i = 0; i < 2; i++) {
if (~(cobra->exists >> i) & 1)
continue;
cobra->dev[i] = input_dev = input_allocate_device();
if (!input_dev) {
err = -ENOMEM;
goto fail3;
}
snprintf(cobra->phys[i], sizeof(cobra->phys[i]),
"%s/input%d", gameport->phys, i);
input_dev->name = "Creative Labs Blaster GamePad Cobra";
input_dev->phys = cobra->phys[i];
input_dev->id.bustype = BUS_GAMEPORT;
input_dev->id.vendor = GAMEPORT_ID_VENDOR_CREATIVE;
input_dev->id.product = 0x0008;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &gameport->dev;
input_set_drvdata(input_dev, cobra);
input_dev->open = cobra_open;
input_dev->close = cobra_close;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_set_abs_params(input_dev, ABS_X, -1, 1, 0, 0);
input_set_abs_params(input_dev, ABS_Y, -1, 1, 0, 0);
for (j = 0; cobra_btn[j]; j++)
set_bit(cobra_btn[j], input_dev->keybit);
err = input_register_device(cobra->dev[i]);
if (err)
goto fail4;
}
return 0;
fail4: input_free_device(cobra->dev[i]);
fail3: while (--i >= 0)
if (cobra->dev[i])
input_unregister_device(cobra->dev[i]);
fail2: gameport_close(gameport);
fail1: gameport_set_drvdata(gameport, NULL);
kfree(cobra);
return err;
}
static void cobra_disconnect(struct gameport *gameport)
{
struct cobra *cobra = gameport_get_drvdata(gameport);
int i;
for (i = 0; i < 2; i++)
if ((cobra->exists >> i) & 1)
input_unregister_device(cobra->dev[i]);
gameport_close(gameport);
gameport_set_drvdata(gameport, NULL);
kfree(cobra);
}
static struct gameport_driver cobra_drv = {
.driver = {
.name = "cobra",
},
.description = DRIVER_DESC,
.connect = cobra_connect,
.disconnect = cobra_disconnect,
};
module_gameport_driver(cobra_drv);
|
linux-master
|
drivers/input/joystick/cobra.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* SEGA Dreamcast controller driver
* Based on drivers/usb/iforce.c
*
* Copyright Yaegashi Takeshi, 2001
* Adrian McMenamin, 2008 - 2009
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/timer.h>
#include <linux/maple.h>
MODULE_AUTHOR("Adrian McMenamin <[email protected]>");
MODULE_DESCRIPTION("SEGA Dreamcast controller driver");
MODULE_LICENSE("GPL");
struct dc_pad {
struct input_dev *dev;
struct maple_device *mdev;
};
static void dc_pad_callback(struct mapleq *mq)
{
unsigned short buttons;
struct maple_device *mapledev = mq->dev;
struct dc_pad *pad = maple_get_drvdata(mapledev);
struct input_dev *dev = pad->dev;
unsigned char *res = mq->recvbuf->buf;
buttons = ~le16_to_cpup((__le16 *)(res + 8));
input_report_abs(dev, ABS_HAT0Y,
(buttons & 0x0010 ? -1 : 0) + (buttons & 0x0020 ? 1 : 0));
input_report_abs(dev, ABS_HAT0X,
(buttons & 0x0040 ? -1 : 0) + (buttons & 0x0080 ? 1 : 0));
input_report_abs(dev, ABS_HAT1Y,
(buttons & 0x1000 ? -1 : 0) + (buttons & 0x2000 ? 1 : 0));
input_report_abs(dev, ABS_HAT1X,
(buttons & 0x4000 ? -1 : 0) + (buttons & 0x8000 ? 1 : 0));
input_report_key(dev, BTN_C, buttons & 0x0001);
input_report_key(dev, BTN_B, buttons & 0x0002);
input_report_key(dev, BTN_A, buttons & 0x0004);
input_report_key(dev, BTN_START, buttons & 0x0008);
input_report_key(dev, BTN_Z, buttons & 0x0100);
input_report_key(dev, BTN_Y, buttons & 0x0200);
input_report_key(dev, BTN_X, buttons & 0x0400);
input_report_key(dev, BTN_SELECT, buttons & 0x0800);
input_report_abs(dev, ABS_GAS, res[10]);
input_report_abs(dev, ABS_BRAKE, res[11]);
input_report_abs(dev, ABS_X, res[12]);
input_report_abs(dev, ABS_Y, res[13]);
input_report_abs(dev, ABS_RX, res[14]);
input_report_abs(dev, ABS_RY, res[15]);
}
static int dc_pad_open(struct input_dev *dev)
{
struct dc_pad *pad = dev_get_platdata(&dev->dev);
maple_getcond_callback(pad->mdev, dc_pad_callback, HZ/20,
MAPLE_FUNC_CONTROLLER);
return 0;
}
static void dc_pad_close(struct input_dev *dev)
{
struct dc_pad *pad = dev_get_platdata(&dev->dev);
maple_getcond_callback(pad->mdev, dc_pad_callback, 0,
MAPLE_FUNC_CONTROLLER);
}
/* allow the controller to be used */
static int probe_maple_controller(struct device *dev)
{
static const short btn_bit[32] = {
BTN_C, BTN_B, BTN_A, BTN_START, -1, -1, -1, -1,
BTN_Z, BTN_Y, BTN_X, BTN_SELECT, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
};
static const short abs_bit[32] = {
-1, -1, -1, -1, ABS_HAT0Y, ABS_HAT0Y, ABS_HAT0X, ABS_HAT0X,
-1, -1, -1, -1, ABS_HAT1Y, ABS_HAT1Y, ABS_HAT1X, ABS_HAT1X,
ABS_GAS, ABS_BRAKE, ABS_X, ABS_Y, ABS_RX, ABS_RY, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1,
};
struct maple_device *mdev = to_maple_dev(dev);
struct maple_driver *mdrv = to_maple_driver(dev->driver);
int i, error;
struct dc_pad *pad;
struct input_dev *idev;
unsigned long data = be32_to_cpu(mdev->devinfo.function_data[0]);
pad = kzalloc(sizeof(struct dc_pad), GFP_KERNEL);
idev = input_allocate_device();
if (!pad || !idev) {
error = -ENOMEM;
goto fail;
}
pad->dev = idev;
pad->mdev = mdev;
idev->open = dc_pad_open;
idev->close = dc_pad_close;
for (i = 0; i < 32; i++) {
if (data & (1 << i)) {
if (btn_bit[i] >= 0)
__set_bit(btn_bit[i], idev->keybit);
else if (abs_bit[i] >= 0)
__set_bit(abs_bit[i], idev->absbit);
}
}
if (idev->keybit[BIT_WORD(BTN_JOYSTICK)])
idev->evbit[0] |= BIT_MASK(EV_KEY);
if (idev->absbit[0])
idev->evbit[0] |= BIT_MASK(EV_ABS);
for (i = ABS_X; i <= ABS_BRAKE; i++)
input_set_abs_params(idev, i, 0, 255, 0, 0);
for (i = ABS_HAT0X; i <= ABS_HAT3Y; i++)
input_set_abs_params(idev, i, 1, -1, 0, 0);
idev->dev.platform_data = pad;
idev->dev.parent = &mdev->dev;
idev->name = mdev->product_name;
idev->id.bustype = BUS_HOST;
error = input_register_device(idev);
if (error)
goto fail;
mdev->driver = mdrv;
maple_set_drvdata(mdev, pad);
return 0;
fail:
input_free_device(idev);
kfree(pad);
maple_set_drvdata(mdev, NULL);
return error;
}
static int remove_maple_controller(struct device *dev)
{
struct maple_device *mdev = to_maple_dev(dev);
struct dc_pad *pad = maple_get_drvdata(mdev);
mdev->callback = NULL;
input_unregister_device(pad->dev);
maple_set_drvdata(mdev, NULL);
kfree(pad);
return 0;
}
static struct maple_driver dc_pad_driver = {
.function = MAPLE_FUNC_CONTROLLER,
.drv = {
.name = "Dreamcast_controller",
.probe = probe_maple_controller,
.remove = remove_maple_controller,
},
};
static int __init dc_pad_init(void)
{
return maple_driver_register(&dc_pad_driver);
}
static void __exit dc_pad_exit(void)
{
maple_driver_unregister(&dc_pad_driver);
}
module_init(dc_pad_init);
module_exit(dc_pad_exit);
|
linux-master
|
drivers/input/joystick/maplecontrol.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* Logitech WingMan Warrior joystick driver for Linux
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Logitech WingMan Warrior joystick driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Constants.
*/
#define WARRIOR_MAX_LENGTH 16
static char warrior_lengths[] = { 0, 4, 12, 3, 4, 4, 0, 0 };
/*
* Per-Warrior data.
*/
struct warrior {
struct input_dev *dev;
int idx, len;
unsigned char data[WARRIOR_MAX_LENGTH];
char phys[32];
};
/*
* warrior_process_packet() decodes packets the driver receives from the
* Warrior. It updates the data accordingly.
*/
static void warrior_process_packet(struct warrior *warrior)
{
struct input_dev *dev = warrior->dev;
unsigned char *data = warrior->data;
if (!warrior->idx) return;
switch ((data[0] >> 4) & 7) {
case 1: /* Button data */
input_report_key(dev, BTN_TRIGGER, data[3] & 1);
input_report_key(dev, BTN_THUMB, (data[3] >> 1) & 1);
input_report_key(dev, BTN_TOP, (data[3] >> 2) & 1);
input_report_key(dev, BTN_TOP2, (data[3] >> 3) & 1);
break;
case 3: /* XY-axis info->data */
input_report_abs(dev, ABS_X, ((data[0] & 8) << 5) - (data[2] | ((data[0] & 4) << 5)));
input_report_abs(dev, ABS_Y, (data[1] | ((data[0] & 1) << 7)) - ((data[0] & 2) << 7));
break;
case 5: /* Throttle, spinner, hat info->data */
input_report_abs(dev, ABS_THROTTLE, (data[1] | ((data[0] & 1) << 7)) - ((data[0] & 2) << 7));
input_report_abs(dev, ABS_HAT0X, (data[3] & 2 ? 1 : 0) - (data[3] & 1 ? 1 : 0));
input_report_abs(dev, ABS_HAT0Y, (data[3] & 8 ? 1 : 0) - (data[3] & 4 ? 1 : 0));
input_report_rel(dev, REL_DIAL, (data[2] | ((data[0] & 4) << 5)) - ((data[0] & 8) << 5));
break;
}
input_sync(dev);
}
/*
* warrior_interrupt() is called by the low level driver when characters
* are ready for us. We then buffer them for further processing, or call the
* packet processing routine.
*/
static irqreturn_t warrior_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct warrior *warrior = serio_get_drvdata(serio);
if (data & 0x80) {
if (warrior->idx) warrior_process_packet(warrior);
warrior->idx = 0;
warrior->len = warrior_lengths[(data >> 4) & 7];
}
if (warrior->idx < warrior->len)
warrior->data[warrior->idx++] = data;
if (warrior->idx == warrior->len) {
if (warrior->idx) warrior_process_packet(warrior);
warrior->idx = 0;
warrior->len = 0;
}
return IRQ_HANDLED;
}
/*
* warrior_disconnect() is the opposite of warrior_connect()
*/
static void warrior_disconnect(struct serio *serio)
{
struct warrior *warrior = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(warrior->dev);
kfree(warrior);
}
/*
* warrior_connect() is the routine that is called when someone adds a
* new serio device. It looks for the Warrior, and if found, registers
* it as an input device.
*/
static int warrior_connect(struct serio *serio, struct serio_driver *drv)
{
struct warrior *warrior;
struct input_dev *input_dev;
int err = -ENOMEM;
warrior = kzalloc(sizeof(struct warrior), GFP_KERNEL);
input_dev = input_allocate_device();
if (!warrior || !input_dev)
goto fail1;
warrior->dev = input_dev;
snprintf(warrior->phys, sizeof(warrior->phys), "%s/input0", serio->phys);
input_dev->name = "Logitech WingMan Warrior";
input_dev->phys = warrior->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_WARRIOR;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL) |
BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_TRIGGER)] = BIT_MASK(BTN_TRIGGER) |
BIT_MASK(BTN_THUMB) | BIT_MASK(BTN_TOP) | BIT_MASK(BTN_TOP2);
input_dev->relbit[0] = BIT_MASK(REL_DIAL);
input_set_abs_params(input_dev, ABS_X, -64, 64, 0, 8);
input_set_abs_params(input_dev, ABS_Y, -64, 64, 0, 8);
input_set_abs_params(input_dev, ABS_THROTTLE, -112, 112, 0, 0);
input_set_abs_params(input_dev, ABS_HAT0X, -1, 1, 0, 0);
input_set_abs_params(input_dev, ABS_HAT0Y, -1, 1, 0, 0);
serio_set_drvdata(serio, warrior);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(warrior->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(warrior);
return err;
}
/*
* The serio driver structure.
*/
static const struct serio_device_id warrior_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_WARRIOR,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, warrior_serio_ids);
static struct serio_driver warrior_drv = {
.driver = {
.name = "warrior",
},
.description = DRIVER_DESC,
.id_table = warrior_serio_ids,
.interrupt = warrior_interrupt,
.connect = warrior_connect,
.disconnect = warrior_disconnect,
};
module_serio_driver(warrior_drv);
|
linux-master
|
drivers/input/joystick/warrior.c
|
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (C) 2021 Oleh Kravchenko <[email protected]>
*
* SparkFun Qwiic Joystick
* Product page:https://www.sparkfun.com/products/15168
* Firmware and hardware sources:https://github.com/sparkfun/Qwiic_Joystick
*/
#include <linux/bits.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/kernel.h>
#include <linux/module.h>
#define DRV_NAME "qwiic-joystick"
#define QWIIC_JSK_REG_VERS 1
#define QWIIC_JSK_REG_DATA 3
#define QWIIC_JSK_MAX_AXIS GENMASK(9, 0)
#define QWIIC_JSK_FUZZ 2
#define QWIIC_JSK_FLAT 2
#define QWIIC_JSK_POLL_INTERVAL 16
#define QWIIC_JSK_POLL_MIN 8
#define QWIIC_JSK_POLL_MAX 32
struct qwiic_jsk {
char phys[32];
struct input_dev *dev;
struct i2c_client *client;
};
struct qwiic_ver {
u8 major;
u8 minor;
};
struct qwiic_data {
__be16 x;
__be16 y;
u8 thumb;
};
static void qwiic_poll(struct input_dev *input)
{
struct qwiic_jsk *priv = input_get_drvdata(input);
struct qwiic_data data;
int err;
err = i2c_smbus_read_i2c_block_data(priv->client, QWIIC_JSK_REG_DATA,
sizeof(data), (u8 *)&data);
if (err != sizeof(data))
return;
input_report_abs(input, ABS_X, be16_to_cpu(data.x) >> 6);
input_report_abs(input, ABS_Y, be16_to_cpu(data.y) >> 6);
input_report_key(input, BTN_THUMBL, !data.thumb);
input_sync(input);
}
static int qwiic_probe(struct i2c_client *client)
{
struct qwiic_jsk *priv;
struct qwiic_ver vers;
int err;
err = i2c_smbus_read_i2c_block_data(client, QWIIC_JSK_REG_VERS,
sizeof(vers), (u8 *)&vers);
if (err < 0)
return err;
if (err != sizeof(vers))
return -EIO;
dev_dbg(&client->dev, "SparkFun Qwiic Joystick, FW: %u.%u\n",
vers.major, vers.minor);
priv = devm_kzalloc(&client->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->client = client;
snprintf(priv->phys, sizeof(priv->phys),
"i2c/%s", dev_name(&client->dev));
i2c_set_clientdata(client, priv);
priv->dev = devm_input_allocate_device(&client->dev);
if (!priv->dev)
return -ENOMEM;
priv->dev->id.bustype = BUS_I2C;
priv->dev->name = "SparkFun Qwiic Joystick";
priv->dev->phys = priv->phys;
input_set_drvdata(priv->dev, priv);
input_set_abs_params(priv->dev, ABS_X, 0, QWIIC_JSK_MAX_AXIS,
QWIIC_JSK_FUZZ, QWIIC_JSK_FLAT);
input_set_abs_params(priv->dev, ABS_Y, 0, QWIIC_JSK_MAX_AXIS,
QWIIC_JSK_FUZZ, QWIIC_JSK_FLAT);
input_set_capability(priv->dev, EV_KEY, BTN_THUMBL);
err = input_setup_polling(priv->dev, qwiic_poll);
if (err) {
dev_err(&client->dev, "failed to set up polling: %d\n", err);
return err;
}
input_set_poll_interval(priv->dev, QWIIC_JSK_POLL_INTERVAL);
input_set_min_poll_interval(priv->dev, QWIIC_JSK_POLL_MIN);
input_set_max_poll_interval(priv->dev, QWIIC_JSK_POLL_MAX);
err = input_register_device(priv->dev);
if (err) {
dev_err(&client->dev, "failed to register joystick: %d\n", err);
return err;
}
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id of_qwiic_match[] = {
{ .compatible = "sparkfun,qwiic-joystick", },
{ },
};
MODULE_DEVICE_TABLE(of, of_qwiic_match);
#endif /* CONFIG_OF */
static const struct i2c_device_id qwiic_id_table[] = {
{ KBUILD_MODNAME, 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, qwiic_id_table);
static struct i2c_driver qwiic_driver = {
.driver = {
.name = DRV_NAME,
.of_match_table = of_match_ptr(of_qwiic_match),
},
.id_table = qwiic_id_table,
.probe = qwiic_probe,
};
module_i2c_driver(qwiic_driver);
MODULE_AUTHOR("Oleh Kravchenko <[email protected]>");
MODULE_DESCRIPTION("SparkFun Qwiic Joystick driver");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/joystick/qwiic-joystick.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000-2002 Vojtech Pavlik <[email protected]>
* Copyright (c) 2001-2002, 2007 Johann Deneux <[email protected]>
*
* USB/RS232 I-Force joysticks and wheels.
*/
#include "iforce.h"
/*
* Set the magnitude of a constant force effect
* Return error code
*
* Note: caller must ensure exclusive access to device
*/
static int make_magnitude_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc, __s16 level)
{
unsigned char data[3];
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 2,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = HIFIX80(level);
iforce_send_packet(iforce, FF_CMD_MAGNITUDE, data);
iforce_dump_packet(iforce, "magnitude", FF_CMD_MAGNITUDE, data);
return 0;
}
/*
* Upload the component of an effect dealing with the period, phase and magnitude
*/
static int make_period_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc,
__s16 magnitude, __s16 offset, u16 period, u16 phase)
{
unsigned char data[7];
period = TIME_SCALE(period);
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 0x0c,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = HIFIX80(magnitude);
data[3] = HIFIX80(offset);
data[4] = HI(phase);
data[5] = LO(period);
data[6] = HI(period);
iforce_send_packet(iforce, FF_CMD_PERIOD, data);
return 0;
}
/*
* Uploads the part of an effect setting the envelope of the force
*/
static int make_envelope_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc,
u16 attack_duration, __s16 initial_level,
u16 fade_duration, __s16 final_level)
{
unsigned char data[8];
attack_duration = TIME_SCALE(attack_duration);
fade_duration = TIME_SCALE(fade_duration);
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 0x0e,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = LO(attack_duration);
data[3] = HI(attack_duration);
data[4] = HI(initial_level);
data[5] = LO(fade_duration);
data[6] = HI(fade_duration);
data[7] = HI(final_level);
iforce_send_packet(iforce, FF_CMD_ENVELOPE, data);
return 0;
}
/*
* Component of spring, friction, inertia... effects
*/
static int make_condition_modifier(struct iforce* iforce,
struct resource* mod_chunk, int no_alloc,
__u16 rsat, __u16 lsat, __s16 rk, __s16 lk, u16 db, __s16 center)
{
unsigned char data[10];
if (!no_alloc) {
mutex_lock(&iforce->mem_mutex);
if (allocate_resource(&(iforce->device_memory), mod_chunk, 8,
iforce->device_memory.start, iforce->device_memory.end, 2L,
NULL, NULL)) {
mutex_unlock(&iforce->mem_mutex);
return -ENOSPC;
}
mutex_unlock(&iforce->mem_mutex);
}
data[0] = LO(mod_chunk->start);
data[1] = HI(mod_chunk->start);
data[2] = (100 * rk) >> 15; /* Dangerous: the sign is extended by gcc on plateforms providing an arith shift */
data[3] = (100 * lk) >> 15; /* This code is incorrect on cpus lacking arith shift */
center = (500 * center) >> 15;
data[4] = LO(center);
data[5] = HI(center);
db = (1000 * db) >> 16;
data[6] = LO(db);
data[7] = HI(db);
data[8] = (100 * rsat) >> 16;
data[9] = (100 * lsat) >> 16;
iforce_send_packet(iforce, FF_CMD_CONDITION, data);
iforce_dump_packet(iforce, "condition", FF_CMD_CONDITION, data);
return 0;
}
static unsigned char find_button(struct iforce *iforce, signed short button)
{
int i;
for (i = 1; iforce->type->btn[i] >= 0; i++)
if (iforce->type->btn[i] == button)
return i + 1;
return 0;
}
/*
* Analyse the changes in an effect, and tell if we need to send an condition
* parameter packet
*/
static int need_condition_modifier(struct iforce *iforce,
struct ff_effect *old,
struct ff_effect *new)
{
int ret = 0;
int i;
if (new->type != FF_SPRING && new->type != FF_FRICTION) {
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
return 0;
}
for (i = 0; i < 2; i++) {
ret |= old->u.condition[i].right_saturation != new->u.condition[i].right_saturation
|| old->u.condition[i].left_saturation != new->u.condition[i].left_saturation
|| old->u.condition[i].right_coeff != new->u.condition[i].right_coeff
|| old->u.condition[i].left_coeff != new->u.condition[i].left_coeff
|| old->u.condition[i].deadband != new->u.condition[i].deadband
|| old->u.condition[i].center != new->u.condition[i].center;
}
return ret;
}
/*
* Analyse the changes in an effect, and tell if we need to send a magnitude
* parameter packet
*/
static int need_magnitude_modifier(struct iforce *iforce,
struct ff_effect *old,
struct ff_effect *effect)
{
if (effect->type != FF_CONSTANT) {
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
return 0;
}
return old->u.constant.level != effect->u.constant.level;
}
/*
* Analyse the changes in an effect, and tell if we need to send an envelope
* parameter packet
*/
static int need_envelope_modifier(struct iforce *iforce, struct ff_effect *old,
struct ff_effect *effect)
{
switch (effect->type) {
case FF_CONSTANT:
if (old->u.constant.envelope.attack_length != effect->u.constant.envelope.attack_length
|| old->u.constant.envelope.attack_level != effect->u.constant.envelope.attack_level
|| old->u.constant.envelope.fade_length != effect->u.constant.envelope.fade_length
|| old->u.constant.envelope.fade_level != effect->u.constant.envelope.fade_level)
return 1;
break;
case FF_PERIODIC:
if (old->u.periodic.envelope.attack_length != effect->u.periodic.envelope.attack_length
|| old->u.periodic.envelope.attack_level != effect->u.periodic.envelope.attack_level
|| old->u.periodic.envelope.fade_length != effect->u.periodic.envelope.fade_length
|| old->u.periodic.envelope.fade_level != effect->u.periodic.envelope.fade_level)
return 1;
break;
default:
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
}
return 0;
}
/*
* Analyse the changes in an effect, and tell if we need to send a periodic
* parameter effect
*/
static int need_period_modifier(struct iforce *iforce, struct ff_effect *old,
struct ff_effect *new)
{
if (new->type != FF_PERIODIC) {
dev_warn(&iforce->dev->dev, "bad effect type in %s\n",
__func__);
return 0;
}
return (old->u.periodic.period != new->u.periodic.period
|| old->u.periodic.magnitude != new->u.periodic.magnitude
|| old->u.periodic.offset != new->u.periodic.offset
|| old->u.periodic.phase != new->u.periodic.phase);
}
/*
* Analyse the changes in an effect, and tell if we need to send an effect
* packet
*/
static int need_core(struct ff_effect *old, struct ff_effect *new)
{
if (old->direction != new->direction
|| old->trigger.button != new->trigger.button
|| old->trigger.interval != new->trigger.interval
|| old->replay.length != new->replay.length
|| old->replay.delay != new->replay.delay)
return 1;
return 0;
}
/*
* Send the part common to all effects to the device
*/
static int make_core(struct iforce* iforce, u16 id, u16 mod_id1, u16 mod_id2,
u8 effect_type, u8 axes, u16 duration, u16 delay, u16 button,
u16 interval, u16 direction)
{
unsigned char data[14];
duration = TIME_SCALE(duration);
delay = TIME_SCALE(delay);
interval = TIME_SCALE(interval);
data[0] = LO(id);
data[1] = effect_type;
data[2] = LO(axes) | find_button(iforce, button);
data[3] = LO(duration);
data[4] = HI(duration);
data[5] = HI(direction);
data[6] = LO(interval);
data[7] = HI(interval);
data[8] = LO(mod_id1);
data[9] = HI(mod_id1);
data[10] = LO(mod_id2);
data[11] = HI(mod_id2);
data[12] = LO(delay);
data[13] = HI(delay);
/* Stop effect */
/* iforce_control_playback(iforce, id, 0);*/
iforce_send_packet(iforce, FF_CMD_EFFECT, data);
/* If needed, restart effect */
if (test_bit(FF_CORE_SHOULD_PLAY, iforce->core_effects[id].flags)) {
/* BUG: perhaps we should replay n times, instead of 1. But we do not know n */
iforce_control_playback(iforce, id, 1);
}
return 0;
}
/*
* Upload a periodic effect to the device
* See also iforce_upload_constant.
*/
int iforce_upload_periodic(struct iforce *iforce, struct ff_effect *effect, struct ff_effect *old)
{
u8 wave_code;
int core_id = effect->id;
struct iforce_core_effect* core_effect = iforce->core_effects + core_id;
struct resource* mod1_chunk = &(iforce->core_effects[core_id].mod1_chunk);
struct resource* mod2_chunk = &(iforce->core_effects[core_id].mod2_chunk);
int param1_err = 1;
int param2_err = 1;
int core_err = 0;
if (!old || need_period_modifier(iforce, old, effect)) {
param1_err = make_period_modifier(iforce, mod1_chunk,
old != NULL,
effect->u.periodic.magnitude, effect->u.periodic.offset,
effect->u.periodic.period, effect->u.periodic.phase);
if (param1_err)
return param1_err;
set_bit(FF_MOD1_IS_USED, core_effect->flags);
}
if (!old || need_envelope_modifier(iforce, old, effect)) {
param2_err = make_envelope_modifier(iforce, mod2_chunk,
old !=NULL,
effect->u.periodic.envelope.attack_length,
effect->u.periodic.envelope.attack_level,
effect->u.periodic.envelope.fade_length,
effect->u.periodic.envelope.fade_level);
if (param2_err)
return param2_err;
set_bit(FF_MOD2_IS_USED, core_effect->flags);
}
switch (effect->u.periodic.waveform) {
case FF_SQUARE: wave_code = 0x20; break;
case FF_TRIANGLE: wave_code = 0x21; break;
case FF_SINE: wave_code = 0x22; break;
case FF_SAW_UP: wave_code = 0x23; break;
case FF_SAW_DOWN: wave_code = 0x24; break;
default: wave_code = 0x20; break;
}
if (!old || need_core(old, effect)) {
core_err = make_core(iforce, effect->id,
mod1_chunk->start,
mod2_chunk->start,
wave_code,
0x20,
effect->replay.length,
effect->replay.delay,
effect->trigger.button,
effect->trigger.interval,
effect->direction);
}
/* If one of the parameter creation failed, we already returned an
* error code.
* If the core creation failed, we return its error code.
* Else: if one parameter at least was created, we return 0
* else we return 1;
*/
return core_err < 0 ? core_err : (param1_err && param2_err);
}
/*
* Upload a constant force effect
* Return value:
* <0 Error code
* 0 Ok, effect created or updated
* 1 effect did not change since last upload, and no packet was therefore sent
*/
int iforce_upload_constant(struct iforce *iforce, struct ff_effect *effect, struct ff_effect *old)
{
int core_id = effect->id;
struct iforce_core_effect* core_effect = iforce->core_effects + core_id;
struct resource* mod1_chunk = &(iforce->core_effects[core_id].mod1_chunk);
struct resource* mod2_chunk = &(iforce->core_effects[core_id].mod2_chunk);
int param1_err = 1;
int param2_err = 1;
int core_err = 0;
if (!old || need_magnitude_modifier(iforce, old, effect)) {
param1_err = make_magnitude_modifier(iforce, mod1_chunk,
old != NULL,
effect->u.constant.level);
if (param1_err)
return param1_err;
set_bit(FF_MOD1_IS_USED, core_effect->flags);
}
if (!old || need_envelope_modifier(iforce, old, effect)) {
param2_err = make_envelope_modifier(iforce, mod2_chunk,
old != NULL,
effect->u.constant.envelope.attack_length,
effect->u.constant.envelope.attack_level,
effect->u.constant.envelope.fade_length,
effect->u.constant.envelope.fade_level);
if (param2_err)
return param2_err;
set_bit(FF_MOD2_IS_USED, core_effect->flags);
}
if (!old || need_core(old, effect)) {
core_err = make_core(iforce, effect->id,
mod1_chunk->start,
mod2_chunk->start,
0x00,
0x20,
effect->replay.length,
effect->replay.delay,
effect->trigger.button,
effect->trigger.interval,
effect->direction);
}
/* If one of the parameter creation failed, we already returned an
* error code.
* If the core creation failed, we return its error code.
* Else: if one parameter at least was created, we return 0
* else we return 1;
*/
return core_err < 0 ? core_err : (param1_err && param2_err);
}
/*
* Upload an condition effect. Those are for example friction, inertia, springs...
*/
int iforce_upload_condition(struct iforce *iforce, struct ff_effect *effect, struct ff_effect *old)
{
int core_id = effect->id;
struct iforce_core_effect* core_effect = iforce->core_effects + core_id;
struct resource* mod1_chunk = &(core_effect->mod1_chunk);
struct resource* mod2_chunk = &(core_effect->mod2_chunk);
u8 type;
int param_err = 1;
int core_err = 0;
switch (effect->type) {
case FF_SPRING: type = 0x40; break;
case FF_DAMPER: type = 0x41; break;
default: return -1;
}
if (!old || need_condition_modifier(iforce, old, effect)) {
param_err = make_condition_modifier(iforce, mod1_chunk,
old != NULL,
effect->u.condition[0].right_saturation,
effect->u.condition[0].left_saturation,
effect->u.condition[0].right_coeff,
effect->u.condition[0].left_coeff,
effect->u.condition[0].deadband,
effect->u.condition[0].center);
if (param_err)
return param_err;
set_bit(FF_MOD1_IS_USED, core_effect->flags);
param_err = make_condition_modifier(iforce, mod2_chunk,
old != NULL,
effect->u.condition[1].right_saturation,
effect->u.condition[1].left_saturation,
effect->u.condition[1].right_coeff,
effect->u.condition[1].left_coeff,
effect->u.condition[1].deadband,
effect->u.condition[1].center);
if (param_err)
return param_err;
set_bit(FF_MOD2_IS_USED, core_effect->flags);
}
if (!old || need_core(old, effect)) {
core_err = make_core(iforce, effect->id,
mod1_chunk->start, mod2_chunk->start,
type, 0xc0,
effect->replay.length, effect->replay.delay,
effect->trigger.button, effect->trigger.interval,
effect->direction);
}
/* If the parameter creation failed, we already returned an
* error code.
* If the core creation failed, we return its error code.
* Else: if a parameter was created, we return 0
* else we return 1;
*/
return core_err < 0 ? core_err : param_err;
}
|
linux-master
|
drivers/input/joystick/iforce/iforce-ff.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000-2002 Vojtech Pavlik <[email protected]>
* Copyright (c) 2001-2002, 2007 Johann Deneux <[email protected]>
*
* USB/RS232 I-Force joysticks and wheels.
*/
#include <linux/usb.h>
#include "iforce.h"
struct iforce_usb {
struct iforce iforce;
struct usb_device *usbdev;
struct usb_interface *intf;
struct urb *irq, *out;
u8 data_in[IFORCE_MAX_LENGTH] ____cacheline_aligned;
u8 data_out[IFORCE_MAX_LENGTH] ____cacheline_aligned;
};
static void __iforce_usb_xmit(struct iforce *iforce)
{
struct iforce_usb *iforce_usb = container_of(iforce, struct iforce_usb,
iforce);
int n, c;
unsigned long flags;
spin_lock_irqsave(&iforce->xmit_lock, flags);
if (iforce->xmit.head == iforce->xmit.tail) {
iforce_clear_xmit_and_wake(iforce);
spin_unlock_irqrestore(&iforce->xmit_lock, flags);
return;
}
((char *)iforce_usb->out->transfer_buffer)[0] = iforce->xmit.buf[iforce->xmit.tail];
XMIT_INC(iforce->xmit.tail, 1);
n = iforce->xmit.buf[iforce->xmit.tail];
XMIT_INC(iforce->xmit.tail, 1);
iforce_usb->out->transfer_buffer_length = n + 1;
iforce_usb->out->dev = iforce_usb->usbdev;
/* Copy rest of data then */
c = CIRC_CNT_TO_END(iforce->xmit.head, iforce->xmit.tail, XMIT_SIZE);
if (n < c) c=n;
memcpy(iforce_usb->out->transfer_buffer + 1,
&iforce->xmit.buf[iforce->xmit.tail],
c);
if (n != c) {
memcpy(iforce_usb->out->transfer_buffer + 1 + c,
&iforce->xmit.buf[0],
n-c);
}
XMIT_INC(iforce->xmit.tail, n);
if ( (n=usb_submit_urb(iforce_usb->out, GFP_ATOMIC)) ) {
dev_warn(&iforce_usb->intf->dev,
"usb_submit_urb failed %d\n", n);
iforce_clear_xmit_and_wake(iforce);
}
/* The IFORCE_XMIT_RUNNING bit is not cleared here. That's intended.
* As long as the urb completion handler is not called, the transmiting
* is considered to be running */
spin_unlock_irqrestore(&iforce->xmit_lock, flags);
}
static void iforce_usb_xmit(struct iforce *iforce)
{
if (!test_and_set_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags))
__iforce_usb_xmit(iforce);
}
static int iforce_usb_get_id(struct iforce *iforce, u8 id,
u8 *response_data, size_t *response_len)
{
struct iforce_usb *iforce_usb = container_of(iforce, struct iforce_usb,
iforce);
u8 *buf;
int status;
buf = kmalloc(IFORCE_MAX_LENGTH, GFP_KERNEL);
if (!buf)
return -ENOMEM;
status = usb_control_msg(iforce_usb->usbdev,
usb_rcvctrlpipe(iforce_usb->usbdev, 0),
id,
USB_TYPE_VENDOR | USB_DIR_IN |
USB_RECIP_INTERFACE,
0, 0, buf, IFORCE_MAX_LENGTH, 1000);
if (status < 0) {
dev_err(&iforce_usb->intf->dev,
"usb_submit_urb failed: %d\n", status);
} else if (buf[0] != id) {
status = -EIO;
} else {
memcpy(response_data, buf, status);
*response_len = status;
status = 0;
}
kfree(buf);
return status;
}
static int iforce_usb_start_io(struct iforce *iforce)
{
struct iforce_usb *iforce_usb = container_of(iforce, struct iforce_usb,
iforce);
if (usb_submit_urb(iforce_usb->irq, GFP_KERNEL))
return -EIO;
return 0;
}
static void iforce_usb_stop_io(struct iforce *iforce)
{
struct iforce_usb *iforce_usb = container_of(iforce, struct iforce_usb,
iforce);
usb_kill_urb(iforce_usb->irq);
usb_kill_urb(iforce_usb->out);
}
static const struct iforce_xport_ops iforce_usb_xport_ops = {
.xmit = iforce_usb_xmit,
.get_id = iforce_usb_get_id,
.start_io = iforce_usb_start_io,
.stop_io = iforce_usb_stop_io,
};
static void iforce_usb_irq(struct urb *urb)
{
struct iforce_usb *iforce_usb = urb->context;
struct iforce *iforce = &iforce_usb->iforce;
struct device *dev = &iforce_usb->intf->dev;
int status;
switch (urb->status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dev_dbg(dev, "%s - urb shutting down with status: %d\n",
__func__, urb->status);
return;
default:
dev_dbg(dev, "%s - urb has status of: %d\n",
__func__, urb->status);
goto exit;
}
iforce_process_packet(iforce, iforce_usb->data_in[0],
iforce_usb->data_in + 1, urb->actual_length - 1);
exit:
status = usb_submit_urb(urb, GFP_ATOMIC);
if (status)
dev_err(dev, "%s - usb_submit_urb failed with result %d\n",
__func__, status);
}
static void iforce_usb_out(struct urb *urb)
{
struct iforce_usb *iforce_usb = urb->context;
struct iforce *iforce = &iforce_usb->iforce;
if (urb->status) {
dev_dbg(&iforce_usb->intf->dev, "urb->status %d, exiting\n",
urb->status);
iforce_clear_xmit_and_wake(iforce);
return;
}
__iforce_usb_xmit(iforce);
wake_up_all(&iforce->wait);
}
static int iforce_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct usb_host_interface *interface;
struct usb_endpoint_descriptor *epirq, *epout;
struct iforce_usb *iforce_usb;
int err = -ENOMEM;
interface = intf->cur_altsetting;
if (interface->desc.bNumEndpoints < 2)
return -ENODEV;
epirq = &interface->endpoint[0].desc;
if (!usb_endpoint_is_int_in(epirq))
return -ENODEV;
epout = &interface->endpoint[1].desc;
if (!usb_endpoint_is_int_out(epout))
return -ENODEV;
iforce_usb = kzalloc(sizeof(*iforce_usb), GFP_KERNEL);
if (!iforce_usb)
goto fail;
iforce_usb->irq = usb_alloc_urb(0, GFP_KERNEL);
if (!iforce_usb->irq)
goto fail;
iforce_usb->out = usb_alloc_urb(0, GFP_KERNEL);
if (!iforce_usb->out)
goto fail;
iforce_usb->iforce.xport_ops = &iforce_usb_xport_ops;
iforce_usb->usbdev = dev;
iforce_usb->intf = intf;
usb_fill_int_urb(iforce_usb->irq, dev,
usb_rcvintpipe(dev, epirq->bEndpointAddress),
iforce_usb->data_in, sizeof(iforce_usb->data_in),
iforce_usb_irq, iforce_usb, epirq->bInterval);
usb_fill_int_urb(iforce_usb->out, dev,
usb_sndintpipe(dev, epout->bEndpointAddress),
iforce_usb->data_out, sizeof(iforce_usb->data_out),
iforce_usb_out, iforce_usb, epout->bInterval);
err = iforce_init_device(&intf->dev, BUS_USB, &iforce_usb->iforce);
if (err)
goto fail;
usb_set_intfdata(intf, iforce_usb);
return 0;
fail:
if (iforce_usb) {
usb_free_urb(iforce_usb->irq);
usb_free_urb(iforce_usb->out);
kfree(iforce_usb);
}
return err;
}
static void iforce_usb_disconnect(struct usb_interface *intf)
{
struct iforce_usb *iforce_usb = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
input_unregister_device(iforce_usb->iforce.dev);
usb_free_urb(iforce_usb->irq);
usb_free_urb(iforce_usb->out);
kfree(iforce_usb);
}
static const struct usb_device_id iforce_usb_ids[] = {
{ USB_DEVICE(0x044f, 0xa01c) }, /* Thrustmaster Motor Sport GT */
{ USB_DEVICE(0x046d, 0xc281) }, /* Logitech WingMan Force */
{ USB_DEVICE(0x046d, 0xc291) }, /* Logitech WingMan Formula Force */
{ USB_DEVICE(0x05ef, 0x020a) }, /* AVB Top Shot Pegasus */
{ USB_DEVICE(0x05ef, 0x8884) }, /* AVB Mag Turbo Force */
{ USB_DEVICE(0x05ef, 0x8888) }, /* AVB Top Shot FFB Racing Wheel */
{ USB_DEVICE(0x061c, 0xc0a4) }, /* ACT LABS Force RS */
{ USB_DEVICE(0x061c, 0xc084) }, /* ACT LABS Force RS */
{ USB_DEVICE(0x06a3, 0xff04) }, /* Saitek R440 Force Wheel */
{ USB_DEVICE(0x06f8, 0x0001) }, /* Guillemot Race Leader Force Feedback */
{ USB_DEVICE(0x06f8, 0x0003) }, /* Guillemot Jet Leader Force Feedback */
{ USB_DEVICE(0x06f8, 0x0004) }, /* Guillemot Force Feedback Racing Wheel */
{ USB_DEVICE(0x06f8, 0xa302) }, /* Guillemot Jet Leader 3D */
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, iforce_usb_ids);
struct usb_driver iforce_usb_driver = {
.name = "iforce",
.probe = iforce_usb_probe,
.disconnect = iforce_usb_disconnect,
.id_table = iforce_usb_ids,
};
module_usb_driver(iforce_usb_driver);
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>, Johann Deneux <[email protected]>");
MODULE_DESCRIPTION("USB I-Force joysticks and wheels driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/joystick/iforce/iforce-usb.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000-2001 Vojtech Pavlik <[email protected]>
* Copyright (c) 2001, 2007 Johann Deneux <[email protected]>
*
* USB/RS232 I-Force joysticks and wheels.
*/
#include <linux/serio.h>
#include "iforce.h"
struct iforce_serio {
struct iforce iforce;
struct serio *serio;
int idx, pkt, len, id;
u8 csum;
u8 expect_packet;
u8 cmd_response[IFORCE_MAX_LENGTH];
u8 cmd_response_len;
u8 data_in[IFORCE_MAX_LENGTH];
};
static void iforce_serio_xmit(struct iforce *iforce)
{
struct iforce_serio *iforce_serio = container_of(iforce,
struct iforce_serio,
iforce);
unsigned char cs;
int i;
unsigned long flags;
if (test_and_set_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags)) {
set_bit(IFORCE_XMIT_AGAIN, iforce->xmit_flags);
return;
}
spin_lock_irqsave(&iforce->xmit_lock, flags);
again:
if (iforce->xmit.head == iforce->xmit.tail) {
iforce_clear_xmit_and_wake(iforce);
spin_unlock_irqrestore(&iforce->xmit_lock, flags);
return;
}
cs = 0x2b;
serio_write(iforce_serio->serio, 0x2b);
serio_write(iforce_serio->serio, iforce->xmit.buf[iforce->xmit.tail]);
cs ^= iforce->xmit.buf[iforce->xmit.tail];
XMIT_INC(iforce->xmit.tail, 1);
for (i=iforce->xmit.buf[iforce->xmit.tail]; i >= 0; --i) {
serio_write(iforce_serio->serio,
iforce->xmit.buf[iforce->xmit.tail]);
cs ^= iforce->xmit.buf[iforce->xmit.tail];
XMIT_INC(iforce->xmit.tail, 1);
}
serio_write(iforce_serio->serio, cs);
if (test_and_clear_bit(IFORCE_XMIT_AGAIN, iforce->xmit_flags))
goto again;
iforce_clear_xmit_and_wake(iforce);
spin_unlock_irqrestore(&iforce->xmit_lock, flags);
}
static int iforce_serio_get_id(struct iforce *iforce, u8 id,
u8 *response_data, size_t *response_len)
{
struct iforce_serio *iforce_serio = container_of(iforce,
struct iforce_serio,
iforce);
iforce_serio->expect_packet = HI(FF_CMD_QUERY);
iforce_serio->cmd_response_len = 0;
iforce_send_packet(iforce, FF_CMD_QUERY, &id);
wait_event_interruptible_timeout(iforce->wait,
!iforce_serio->expect_packet, HZ);
if (iforce_serio->expect_packet) {
iforce_serio->expect_packet = 0;
return -ETIMEDOUT;
}
if (iforce_serio->cmd_response[0] != id)
return -EIO;
memcpy(response_data, iforce_serio->cmd_response,
iforce_serio->cmd_response_len);
*response_len = iforce_serio->cmd_response_len;
return 0;
}
static int iforce_serio_start_io(struct iforce *iforce)
{
/* No special handling required */
return 0;
}
static void iforce_serio_stop_io(struct iforce *iforce)
{
//TODO: Wait for the last packets to be sent
}
static const struct iforce_xport_ops iforce_serio_xport_ops = {
.xmit = iforce_serio_xmit,
.get_id = iforce_serio_get_id,
.start_io = iforce_serio_start_io,
.stop_io = iforce_serio_stop_io,
};
static void iforce_serio_write_wakeup(struct serio *serio)
{
struct iforce *iforce = serio_get_drvdata(serio);
iforce_serio_xmit(iforce);
}
static irqreturn_t iforce_serio_irq(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct iforce_serio *iforce_serio = serio_get_drvdata(serio);
struct iforce *iforce = &iforce_serio->iforce;
if (!iforce_serio->pkt) {
if (data == 0x2b)
iforce_serio->pkt = 1;
goto out;
}
if (!iforce_serio->id) {
if (data > 3 && data != 0xff)
iforce_serio->pkt = 0;
else
iforce_serio->id = data;
goto out;
}
if (!iforce_serio->len) {
if (data > IFORCE_MAX_LENGTH) {
iforce_serio->pkt = 0;
iforce_serio->id = 0;
} else {
iforce_serio->len = data;
}
goto out;
}
if (iforce_serio->idx < iforce_serio->len) {
iforce_serio->data_in[iforce_serio->idx++] = data;
iforce_serio->csum += data;
goto out;
}
if (iforce_serio->idx == iforce_serio->len) {
/* Handle command completion */
if (iforce_serio->expect_packet == iforce_serio->id) {
iforce_serio->expect_packet = 0;
memcpy(iforce_serio->cmd_response,
iforce_serio->data_in, IFORCE_MAX_LENGTH);
iforce_serio->cmd_response_len = iforce_serio->len;
/* Signal that command is done */
wake_up_all(&iforce->wait);
} else if (likely(iforce->type)) {
iforce_process_packet(iforce, iforce_serio->id,
iforce_serio->data_in,
iforce_serio->len);
}
iforce_serio->pkt = 0;
iforce_serio->id = 0;
iforce_serio->len = 0;
iforce_serio->idx = 0;
iforce_serio->csum = 0;
}
out:
return IRQ_HANDLED;
}
static int iforce_serio_connect(struct serio *serio, struct serio_driver *drv)
{
struct iforce_serio *iforce_serio;
int err;
iforce_serio = kzalloc(sizeof(*iforce_serio), GFP_KERNEL);
if (!iforce_serio)
return -ENOMEM;
iforce_serio->iforce.xport_ops = &iforce_serio_xport_ops;
iforce_serio->serio = serio;
serio_set_drvdata(serio, iforce_serio);
err = serio_open(serio, drv);
if (err)
goto fail1;
err = iforce_init_device(&serio->dev, BUS_RS232, &iforce_serio->iforce);
if (err)
goto fail2;
return 0;
fail2: serio_close(serio);
fail1: serio_set_drvdata(serio, NULL);
kfree(iforce_serio);
return err;
}
static void iforce_serio_disconnect(struct serio *serio)
{
struct iforce_serio *iforce_serio = serio_get_drvdata(serio);
input_unregister_device(iforce_serio->iforce.dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
kfree(iforce_serio);
}
static const struct serio_device_id iforce_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_IFORCE,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, iforce_serio_ids);
struct serio_driver iforce_serio_drv = {
.driver = {
.name = "iforce",
},
.description = "RS232 I-Force joysticks and wheels driver",
.id_table = iforce_serio_ids,
.write_wakeup = iforce_serio_write_wakeup,
.interrupt = iforce_serio_irq,
.connect = iforce_serio_connect,
.disconnect = iforce_serio_disconnect,
};
module_serio_driver(iforce_serio_drv);
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>, Johann Deneux <[email protected]>");
MODULE_DESCRIPTION("RS232 I-Force joysticks and wheels driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/joystick/iforce/iforce-serio.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000-2002 Vojtech Pavlik <[email protected]>
* Copyright (c) 2001-2002, 2007 Johann Deneux <[email protected]>
*
* USB/RS232 I-Force joysticks and wheels.
*/
#include <asm/unaligned.h>
#include "iforce.h"
static struct {
__s32 x;
__s32 y;
} iforce_hat_to_axis[16] = {{ 0,-1}, { 1,-1}, { 1, 0}, { 1, 1}, { 0, 1}, {-1, 1}, {-1, 0}, {-1,-1}};
void iforce_dump_packet(struct iforce *iforce, char *msg, u16 cmd, unsigned char *data)
{
dev_dbg(iforce->dev->dev.parent, "%s %s cmd = %04x, data = %*ph\n",
__func__, msg, cmd, LO(cmd), data);
}
/*
* Send a packet of bytes to the device
*/
int iforce_send_packet(struct iforce *iforce, u16 cmd, unsigned char* data)
{
/* Copy data to buffer */
int n = LO(cmd);
int c;
int empty;
int head, tail;
unsigned long flags;
/*
* Update head and tail of xmit buffer
*/
spin_lock_irqsave(&iforce->xmit_lock, flags);
head = iforce->xmit.head;
tail = iforce->xmit.tail;
if (CIRC_SPACE(head, tail, XMIT_SIZE) < n+2) {
dev_warn(&iforce->dev->dev,
"not enough space in xmit buffer to send new packet\n");
spin_unlock_irqrestore(&iforce->xmit_lock, flags);
return -1;
}
empty = head == tail;
XMIT_INC(iforce->xmit.head, n+2);
/*
* Store packet in xmit buffer
*/
iforce->xmit.buf[head] = HI(cmd);
XMIT_INC(head, 1);
iforce->xmit.buf[head] = LO(cmd);
XMIT_INC(head, 1);
c = CIRC_SPACE_TO_END(head, tail, XMIT_SIZE);
if (n < c) c=n;
memcpy(&iforce->xmit.buf[head],
data,
c);
if (n != c) {
memcpy(&iforce->xmit.buf[0],
data + c,
n - c);
}
XMIT_INC(head, n);
spin_unlock_irqrestore(&iforce->xmit_lock, flags);
/*
* If necessary, start the transmission
*/
if (empty)
iforce->xport_ops->xmit(iforce);
return 0;
}
EXPORT_SYMBOL(iforce_send_packet);
/* Start or stop an effect */
int iforce_control_playback(struct iforce* iforce, u16 id, unsigned int value)
{
unsigned char data[3];
data[0] = LO(id);
data[1] = (value > 0) ? ((value > 1) ? 0x41 : 0x01) : 0;
data[2] = LO(value);
return iforce_send_packet(iforce, FF_CMD_PLAY, data);
}
/* Mark an effect that was being updated as ready. That means it can be updated
* again */
static int mark_core_as_ready(struct iforce *iforce, unsigned short addr)
{
int i;
if (!iforce->dev->ff)
return 0;
for (i = 0; i < iforce->dev->ff->max_effects; ++i) {
if (test_bit(FF_CORE_IS_USED, iforce->core_effects[i].flags) &&
(iforce->core_effects[i].mod1_chunk.start == addr ||
iforce->core_effects[i].mod2_chunk.start == addr)) {
clear_bit(FF_CORE_UPDATE, iforce->core_effects[i].flags);
return 0;
}
}
dev_warn(&iforce->dev->dev, "unused effect %04x updated !!!\n", addr);
return -1;
}
static void iforce_report_hats_buttons(struct iforce *iforce, u8 *data)
{
struct input_dev *dev = iforce->dev;
int i;
input_report_abs(dev, ABS_HAT0X, iforce_hat_to_axis[data[6] >> 4].x);
input_report_abs(dev, ABS_HAT0Y, iforce_hat_to_axis[data[6] >> 4].y);
for (i = 0; iforce->type->btn[i] >= 0; i++)
input_report_key(dev, iforce->type->btn[i],
data[(i >> 3) + 5] & (1 << (i & 7)));
/* If there are untouched bits left, interpret them as the second hat */
if (i <= 8) {
u8 btns = data[6];
if (test_bit(ABS_HAT1X, dev->absbit)) {
if (btns & BIT(3))
input_report_abs(dev, ABS_HAT1X, -1);
else if (btns & BIT(1))
input_report_abs(dev, ABS_HAT1X, 1);
else
input_report_abs(dev, ABS_HAT1X, 0);
}
if (test_bit(ABS_HAT1Y, dev->absbit)) {
if (btns & BIT(0))
input_report_abs(dev, ABS_HAT1Y, -1);
else if (btns & BIT(2))
input_report_abs(dev, ABS_HAT1Y, 1);
else
input_report_abs(dev, ABS_HAT1Y, 0);
}
}
}
void iforce_process_packet(struct iforce *iforce,
u8 packet_id, u8 *data, size_t len)
{
struct input_dev *dev = iforce->dev;
int i, j;
switch (packet_id) {
case 0x01: /* joystick position data */
input_report_abs(dev, ABS_X,
(__s16) get_unaligned_le16(data));
input_report_abs(dev, ABS_Y,
(__s16) get_unaligned_le16(data + 2));
input_report_abs(dev, ABS_THROTTLE, 255 - data[4]);
if (len >= 8 && test_bit(ABS_RUDDER ,dev->absbit))
input_report_abs(dev, ABS_RUDDER, (__s8)data[7]);
iforce_report_hats_buttons(iforce, data);
input_sync(dev);
break;
case 0x03: /* wheel position data */
input_report_abs(dev, ABS_WHEEL,
(__s16) get_unaligned_le16(data));
input_report_abs(dev, ABS_GAS, 255 - data[2]);
input_report_abs(dev, ABS_BRAKE, 255 - data[3]);
iforce_report_hats_buttons(iforce, data);
input_sync(dev);
break;
case 0x02: /* status report */
input_report_key(dev, BTN_DEAD, data[0] & 0x02);
input_sync(dev);
/* Check if an effect was just started or stopped */
i = data[1] & 0x7f;
if (data[1] & 0x80) {
if (!test_and_set_bit(FF_CORE_IS_PLAYED, iforce->core_effects[i].flags)) {
/* Report play event */
input_report_ff_status(dev, i, FF_STATUS_PLAYING);
}
} else if (test_and_clear_bit(FF_CORE_IS_PLAYED, iforce->core_effects[i].flags)) {
/* Report stop event */
input_report_ff_status(dev, i, FF_STATUS_STOPPED);
}
for (j = 3; j < len; j += 2)
mark_core_as_ready(iforce, get_unaligned_le16(data + j));
break;
}
}
EXPORT_SYMBOL(iforce_process_packet);
|
linux-master
|
drivers/input/joystick/iforce/iforce-packets.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000-2002 Vojtech Pavlik <[email protected]>
* Copyright (c) 2001-2002, 2007 Johann Deneux <[email protected]>
*
* USB/RS232 I-Force joysticks and wheels.
*/
#include <asm/unaligned.h>
#include "iforce.h"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>, Johann Deneux <[email protected]>");
MODULE_DESCRIPTION("Core I-Force joysticks and wheels driver");
MODULE_LICENSE("GPL");
static signed short btn_joystick[] =
{ BTN_TRIGGER, BTN_TOP, BTN_THUMB, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_BASE5, BTN_A,
BTN_B, BTN_C, BTN_DEAD, -1 };
static signed short btn_joystick_avb[] =
{ BTN_TRIGGER, BTN_THUMB, BTN_TOP, BTN_TOP2, BTN_BASE,
BTN_BASE2, BTN_BASE3, BTN_BASE4, BTN_DEAD, -1 };
static signed short btn_wheel[] =
{ BTN_GEAR_DOWN, BTN_GEAR_UP, BTN_BASE, BTN_BASE2, BTN_BASE3,
BTN_BASE4, BTN_BASE5, BTN_BASE6, -1 };
static signed short abs_joystick[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short abs_joystick_rudder[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short abs_avb_pegasus[] =
{ ABS_X, ABS_Y, ABS_THROTTLE, ABS_RUDDER, ABS_HAT0X, ABS_HAT0Y,
ABS_HAT1X, ABS_HAT1Y, -1 };
static signed short abs_wheel[] =
{ ABS_WHEEL, ABS_GAS, ABS_BRAKE, ABS_HAT0X, ABS_HAT0Y, -1 };
static signed short ff_iforce[] =
{ FF_PERIODIC, FF_CONSTANT, FF_SPRING, FF_DAMPER,
FF_SQUARE, FF_TRIANGLE, FF_SINE, FF_SAW_UP, FF_SAW_DOWN, FF_GAIN,
FF_AUTOCENTER, -1 };
static struct iforce_device iforce_device[] = {
{ 0x044f, 0xa01c, "Thrustmaster Motor Sport GT", btn_wheel, abs_wheel, ff_iforce },
{ 0x046d, 0xc281, "Logitech WingMan Force", btn_joystick, abs_joystick, ff_iforce },
{ 0x046d, 0xc291, "Logitech WingMan Formula Force", btn_wheel, abs_wheel, ff_iforce },
{ 0x05ef, 0x020a, "AVB Top Shot Pegasus", btn_joystick_avb, abs_avb_pegasus, ff_iforce },
{ 0x05ef, 0x8884, "AVB Mag Turbo Force", btn_wheel, abs_wheel, ff_iforce },
{ 0x05ef, 0x8886, "Boeder Force Feedback Wheel", btn_wheel, abs_wheel, ff_iforce },
{ 0x05ef, 0x8888, "AVB Top Shot Force Feedback Racing Wheel", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x061c, 0xc0a4, "ACT LABS Force RS", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x061c, 0xc084, "ACT LABS Force RS", btn_wheel, abs_wheel, ff_iforce },
{ 0x06a3, 0xff04, "Saitek R440 Force Wheel", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x06f8, 0x0001, "Guillemot Race Leader Force Feedback", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x06f8, 0x0001, "Guillemot Jet Leader Force Feedback", btn_joystick, abs_joystick_rudder, ff_iforce },
{ 0x06f8, 0x0004, "Guillemot Force Feedback Racing Wheel", btn_wheel, abs_wheel, ff_iforce }, //?
{ 0x06f8, 0xa302, "Guillemot Jet Leader 3D", btn_joystick, abs_joystick, ff_iforce }, //?
{ 0x06d6, 0x29bc, "Trust Force Feedback Race Master", btn_wheel, abs_wheel, ff_iforce },
{ 0x0000, 0x0000, "Unknown I-Force Device [%04x:%04x]", btn_joystick, abs_joystick, ff_iforce }
};
static int iforce_playback(struct input_dev *dev, int effect_id, int value)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect_id];
if (value > 0)
set_bit(FF_CORE_SHOULD_PLAY, core_effect->flags);
else
clear_bit(FF_CORE_SHOULD_PLAY, core_effect->flags);
iforce_control_playback(iforce, effect_id, value);
return 0;
}
static void iforce_set_gain(struct input_dev *dev, u16 gain)
{
struct iforce *iforce = input_get_drvdata(dev);
unsigned char data[3];
data[0] = gain >> 9;
iforce_send_packet(iforce, FF_CMD_GAIN, data);
}
static void iforce_set_autocenter(struct input_dev *dev, u16 magnitude)
{
struct iforce *iforce = input_get_drvdata(dev);
unsigned char data[3];
data[0] = 0x03;
data[1] = magnitude >> 9;
iforce_send_packet(iforce, FF_CMD_AUTOCENTER, data);
data[0] = 0x04;
data[1] = 0x01;
iforce_send_packet(iforce, FF_CMD_AUTOCENTER, data);
}
/*
* Function called when an ioctl is performed on the event dev entry.
* It uploads an effect to the device
*/
static int iforce_upload_effect(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect->id];
int ret;
if (__test_and_set_bit(FF_CORE_IS_USED, core_effect->flags)) {
/* Check the effect is not already being updated */
if (test_bit(FF_CORE_UPDATE, core_effect->flags))
return -EAGAIN;
}
/*
* Upload the effect
*/
switch (effect->type) {
case FF_PERIODIC:
ret = iforce_upload_periodic(iforce, effect, old);
break;
case FF_CONSTANT:
ret = iforce_upload_constant(iforce, effect, old);
break;
case FF_SPRING:
case FF_DAMPER:
ret = iforce_upload_condition(iforce, effect, old);
break;
default:
return -EINVAL;
}
if (ret == 0) {
/* A packet was sent, forbid new updates until we are notified
* that the packet was updated
*/
set_bit(FF_CORE_UPDATE, core_effect->flags);
}
return ret;
}
/*
* Erases an effect: it frees the effect id and mark as unused the memory
* allocated for the parameters
*/
static int iforce_erase_effect(struct input_dev *dev, int effect_id)
{
struct iforce *iforce = input_get_drvdata(dev);
struct iforce_core_effect *core_effect = &iforce->core_effects[effect_id];
int err = 0;
if (test_bit(FF_MOD1_IS_USED, core_effect->flags))
err = release_resource(&core_effect->mod1_chunk);
if (!err && test_bit(FF_MOD2_IS_USED, core_effect->flags))
err = release_resource(&core_effect->mod2_chunk);
/* TODO: remember to change that if more FF_MOD* bits are added */
core_effect->flags[0] = 0;
return err;
}
static int iforce_open(struct input_dev *dev)
{
struct iforce *iforce = input_get_drvdata(dev);
iforce->xport_ops->start_io(iforce);
if (test_bit(EV_FF, dev->evbit)) {
/* Enable force feedback */
iforce_send_packet(iforce, FF_CMD_ENABLE, "\004");
}
return 0;
}
static void iforce_close(struct input_dev *dev)
{
struct iforce *iforce = input_get_drvdata(dev);
int i;
if (test_bit(EV_FF, dev->evbit)) {
/* Check: no effects should be present in memory */
for (i = 0; i < dev->ff->max_effects; i++) {
if (test_bit(FF_CORE_IS_USED, iforce->core_effects[i].flags)) {
dev_warn(&dev->dev,
"%s: Device still owns effects\n",
__func__);
break;
}
}
/* Disable force feedback playback */
iforce_send_packet(iforce, FF_CMD_ENABLE, "\001");
/* Wait for the command to complete */
wait_event_interruptible(iforce->wait,
!test_bit(IFORCE_XMIT_RUNNING, iforce->xmit_flags));
}
iforce->xport_ops->stop_io(iforce);
}
int iforce_init_device(struct device *parent, u16 bustype,
struct iforce *iforce)
{
struct input_dev *input_dev;
struct ff_device *ff;
u8 c[] = "CEOV";
u8 buf[IFORCE_MAX_LENGTH];
size_t len;
int i, error;
int ff_effects = 0;
input_dev = input_allocate_device();
if (!input_dev)
return -ENOMEM;
init_waitqueue_head(&iforce->wait);
spin_lock_init(&iforce->xmit_lock);
mutex_init(&iforce->mem_mutex);
iforce->xmit.buf = iforce->xmit_data;
iforce->dev = input_dev;
/*
* Input device fields.
*/
input_dev->id.bustype = bustype;
input_dev->dev.parent = parent;
input_set_drvdata(input_dev, iforce);
input_dev->name = "Unknown I-Force device";
input_dev->open = iforce_open;
input_dev->close = iforce_close;
/*
* On-device memory allocation.
*/
iforce->device_memory.name = "I-Force device effect memory";
iforce->device_memory.start = 0;
iforce->device_memory.end = 200;
iforce->device_memory.flags = IORESOURCE_MEM;
iforce->device_memory.parent = NULL;
iforce->device_memory.child = NULL;
iforce->device_memory.sibling = NULL;
/*
* Wait until device ready - until it sends its first response.
*/
for (i = 0; i < 20; i++)
if (!iforce_get_id_packet(iforce, 'O', buf, &len))
break;
if (i == 20) { /* 5 seconds */
dev_err(&input_dev->dev,
"Timeout waiting for response from device.\n");
error = -ENODEV;
goto fail;
}
/*
* Get device info.
*/
if (!iforce_get_id_packet(iforce, 'M', buf, &len) && len >= 3)
input_dev->id.vendor = get_unaligned_le16(buf + 1);
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet M\n");
if (!iforce_get_id_packet(iforce, 'P', buf, &len) && len >= 3)
input_dev->id.product = get_unaligned_le16(buf + 1);
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet P\n");
if (!iforce_get_id_packet(iforce, 'B', buf, &len) && len >= 3)
iforce->device_memory.end = get_unaligned_le16(buf + 1);
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet B\n");
if (!iforce_get_id_packet(iforce, 'N', buf, &len) && len >= 2)
ff_effects = buf[1];
else
dev_warn(&iforce->dev->dev, "Device does not respond to id packet N\n");
/* Check if the device can store more effects than the driver can really handle */
if (ff_effects > IFORCE_EFFECTS_MAX) {
dev_warn(&iforce->dev->dev, "Limiting number of effects to %d (device reports %d)\n",
IFORCE_EFFECTS_MAX, ff_effects);
ff_effects = IFORCE_EFFECTS_MAX;
}
/*
* Display additional info.
*/
for (i = 0; c[i]; i++)
if (!iforce_get_id_packet(iforce, c[i], buf, &len))
iforce_dump_packet(iforce, "info",
(FF_CMD_QUERY & 0xff00) | len, buf);
/*
* Disable spring, enable force feedback.
*/
iforce_set_autocenter(input_dev, 0);
/*
* Find appropriate device entry
*/
for (i = 0; iforce_device[i].idvendor; i++)
if (iforce_device[i].idvendor == input_dev->id.vendor &&
iforce_device[i].idproduct == input_dev->id.product)
break;
iforce->type = iforce_device + i;
input_dev->name = iforce->type->name;
/*
* Set input device bitfields and ranges.
*/
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS) |
BIT_MASK(EV_FF_STATUS);
for (i = 0; iforce->type->btn[i] >= 0; i++)
set_bit(iforce->type->btn[i], input_dev->keybit);
for (i = 0; iforce->type->abs[i] >= 0; i++) {
signed short t = iforce->type->abs[i];
switch (t) {
case ABS_X:
case ABS_Y:
case ABS_WHEEL:
input_set_abs_params(input_dev, t, -1920, 1920, 16, 128);
set_bit(t, input_dev->ffbit);
break;
case ABS_THROTTLE:
case ABS_GAS:
case ABS_BRAKE:
input_set_abs_params(input_dev, t, 0, 255, 0, 0);
break;
case ABS_RUDDER:
input_set_abs_params(input_dev, t, -128, 127, 0, 0);
break;
case ABS_HAT0X:
case ABS_HAT0Y:
case ABS_HAT1X:
case ABS_HAT1Y:
input_set_abs_params(input_dev, t, -1, 1, 0, 0);
break;
}
}
if (ff_effects) {
for (i = 0; iforce->type->ff[i] >= 0; i++)
set_bit(iforce->type->ff[i], input_dev->ffbit);
error = input_ff_create(input_dev, ff_effects);
if (error)
goto fail;
ff = input_dev->ff;
ff->upload = iforce_upload_effect;
ff->erase = iforce_erase_effect;
ff->set_gain = iforce_set_gain;
ff->set_autocenter = iforce_set_autocenter;
ff->playback = iforce_playback;
}
/*
* Register input device.
*/
error = input_register_device(iforce->dev);
if (error)
goto fail;
return 0;
fail: input_free_device(input_dev);
return error;
}
EXPORT_SYMBOL(iforce_init_device);
|
linux-master
|
drivers/input/joystick/iforce/iforce-main.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* linux/drivers/input/keyboard/omap-keypad.c
*
* OMAP Keypad Driver
*
* Copyright (C) 2003 Nokia Corporation
* Written by Timo Teräs <[email protected]>
*
* Added support for H2 & H3 Keypad
* Copyright (C) 2004 Texas Instruments
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/types.h>
#include <linux/input.h>
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/mutex.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/platform_data/gpio-omap.h>
#include <linux/platform_data/keypad-omap.h>
#include <linux/soc/ti/omap1-io.h>
#undef NEW_BOARD_LEARNING_MODE
static void omap_kp_tasklet(unsigned long);
static void omap_kp_timer(struct timer_list *);
static unsigned char keypad_state[8];
static DEFINE_MUTEX(kp_enable_mutex);
static int kp_enable = 1;
static int kp_cur_group = -1;
struct omap_kp {
struct input_dev *input;
struct timer_list timer;
int irq;
unsigned int rows;
unsigned int cols;
unsigned long delay;
unsigned int debounce;
unsigned short keymap[];
};
static DECLARE_TASKLET_DISABLED_OLD(kp_tasklet, omap_kp_tasklet);
static unsigned int *row_gpios;
static unsigned int *col_gpios;
static irqreturn_t omap_kp_interrupt(int irq, void *dev_id)
{
/* disable keyboard interrupt and schedule for handling */
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
tasklet_schedule(&kp_tasklet);
return IRQ_HANDLED;
}
static void omap_kp_timer(struct timer_list *unused)
{
tasklet_schedule(&kp_tasklet);
}
static void omap_kp_scan_keypad(struct omap_kp *omap_kp, unsigned char *state)
{
int col = 0;
/* disable keyboard interrupt and schedule for handling */
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
/* read the keypad status */
omap_writew(0xff, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBC);
for (col = 0; col < omap_kp->cols; col++) {
omap_writew(~(1 << col) & 0xff,
OMAP1_MPUIO_BASE + OMAP_MPUIO_KBC);
udelay(omap_kp->delay);
state[col] = ~omap_readw(OMAP1_MPUIO_BASE +
OMAP_MPUIO_KBR_LATCH) & 0xff;
}
omap_writew(0x00, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBC);
udelay(2);
}
static void omap_kp_tasklet(unsigned long data)
{
struct omap_kp *omap_kp_data = (struct omap_kp *) data;
unsigned short *keycodes = omap_kp_data->input->keycode;
unsigned int row_shift = get_count_order(omap_kp_data->cols);
unsigned char new_state[8], changed, key_down = 0;
int col, row;
/* check for any changes */
omap_kp_scan_keypad(omap_kp_data, new_state);
/* check for changes and print those */
for (col = 0; col < omap_kp_data->cols; col++) {
changed = new_state[col] ^ keypad_state[col];
key_down |= new_state[col];
if (changed == 0)
continue;
for (row = 0; row < omap_kp_data->rows; row++) {
int key;
if (!(changed & (1 << row)))
continue;
#ifdef NEW_BOARD_LEARNING_MODE
printk(KERN_INFO "omap-keypad: key %d-%d %s\n", col,
row, (new_state[col] & (1 << row)) ?
"pressed" : "released");
#else
key = keycodes[MATRIX_SCAN_CODE(row, col, row_shift)];
if (!(kp_cur_group == (key & GROUP_MASK) ||
kp_cur_group == -1))
continue;
kp_cur_group = key & GROUP_MASK;
input_report_key(omap_kp_data->input, key & ~GROUP_MASK,
new_state[col] & (1 << row));
#endif
}
}
input_sync(omap_kp_data->input);
memcpy(keypad_state, new_state, sizeof(keypad_state));
if (key_down) {
/* some key is pressed - keep irq disabled and use timer
* to poll the keypad */
mod_timer(&omap_kp_data->timer, jiffies + HZ / 20);
} else {
/* enable interrupts */
omap_writew(0, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
kp_cur_group = -1;
}
}
static ssize_t omap_kp_enable_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%u\n", kp_enable);
}
static ssize_t omap_kp_enable_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct omap_kp *omap_kp = dev_get_drvdata(dev);
int state;
if (sscanf(buf, "%u", &state) != 1)
return -EINVAL;
if ((state != 1) && (state != 0))
return -EINVAL;
mutex_lock(&kp_enable_mutex);
if (state != kp_enable) {
if (state)
enable_irq(omap_kp->irq);
else
disable_irq(omap_kp->irq);
kp_enable = state;
}
mutex_unlock(&kp_enable_mutex);
return strnlen(buf, count);
}
static DEVICE_ATTR(enable, S_IRUGO | S_IWUSR, omap_kp_enable_show, omap_kp_enable_store);
static int omap_kp_probe(struct platform_device *pdev)
{
struct omap_kp *omap_kp;
struct input_dev *input_dev;
struct omap_kp_platform_data *pdata = dev_get_platdata(&pdev->dev);
int i, col_idx, row_idx, ret;
unsigned int row_shift, keycodemax;
if (!pdata->rows || !pdata->cols || !pdata->keymap_data) {
printk(KERN_ERR "No rows, cols or keymap_data from pdata\n");
return -EINVAL;
}
row_shift = get_count_order(pdata->cols);
keycodemax = pdata->rows << row_shift;
omap_kp = kzalloc(struct_size(omap_kp, keymap, keycodemax), GFP_KERNEL);
input_dev = input_allocate_device();
if (!omap_kp || !input_dev) {
kfree(omap_kp);
input_free_device(input_dev);
return -ENOMEM;
}
platform_set_drvdata(pdev, omap_kp);
omap_kp->input = input_dev;
/* Disable the interrupt for the MPUIO keyboard */
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
if (pdata->delay)
omap_kp->delay = pdata->delay;
if (pdata->row_gpios && pdata->col_gpios) {
row_gpios = pdata->row_gpios;
col_gpios = pdata->col_gpios;
}
omap_kp->rows = pdata->rows;
omap_kp->cols = pdata->cols;
col_idx = 0;
row_idx = 0;
timer_setup(&omap_kp->timer, omap_kp_timer, 0);
/* get the irq and init timer*/
kp_tasklet.data = (unsigned long) omap_kp;
tasklet_enable(&kp_tasklet);
ret = device_create_file(&pdev->dev, &dev_attr_enable);
if (ret < 0)
goto err2;
/* setup input device */
input_dev->name = "omap-keypad";
input_dev->phys = "omap-keypad/input0";
input_dev->dev.parent = &pdev->dev;
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
if (pdata->rep)
__set_bit(EV_REP, input_dev->evbit);
ret = matrix_keypad_build_keymap(pdata->keymap_data, NULL,
pdata->rows, pdata->cols,
omap_kp->keymap, input_dev);
if (ret < 0)
goto err3;
ret = input_register_device(omap_kp->input);
if (ret < 0) {
printk(KERN_ERR "Unable to register omap-keypad input device\n");
goto err3;
}
if (pdata->dbounce)
omap_writew(0xff, OMAP1_MPUIO_BASE + OMAP_MPUIO_GPIO_DEBOUNCING);
/* scan current status and enable interrupt */
omap_kp_scan_keypad(omap_kp, keypad_state);
omap_kp->irq = platform_get_irq(pdev, 0);
if (omap_kp->irq >= 0) {
if (request_irq(omap_kp->irq, omap_kp_interrupt, 0,
"omap-keypad", omap_kp) < 0)
goto err4;
}
omap_writew(0, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
return 0;
err4:
input_unregister_device(omap_kp->input);
input_dev = NULL;
err3:
device_remove_file(&pdev->dev, &dev_attr_enable);
err2:
for (i = row_idx - 1; i >= 0; i--)
gpio_free(row_gpios[i]);
for (i = col_idx - 1; i >= 0; i--)
gpio_free(col_gpios[i]);
kfree(omap_kp);
input_free_device(input_dev);
return -EINVAL;
}
static int omap_kp_remove(struct platform_device *pdev)
{
struct omap_kp *omap_kp = platform_get_drvdata(pdev);
/* disable keypad interrupt handling */
tasklet_disable(&kp_tasklet);
omap_writew(1, OMAP1_MPUIO_BASE + OMAP_MPUIO_KBD_MASKIT);
free_irq(omap_kp->irq, omap_kp);
timer_shutdown_sync(&omap_kp->timer);
tasklet_kill(&kp_tasklet);
/* unregister everything */
input_unregister_device(omap_kp->input);
kfree(omap_kp);
return 0;
}
static struct platform_driver omap_kp_driver = {
.probe = omap_kp_probe,
.remove = omap_kp_remove,
.driver = {
.name = "omap-keypad",
},
};
module_platform_driver(omap_kp_driver);
MODULE_AUTHOR("Timo Teräs");
MODULE_DESCRIPTION("OMAP Keypad Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:omap-keypad");
|
linux-master
|
drivers/input/keyboard/omap-keypad.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* D-Link DIR-685 router I2C-based Touchkeys input driver
* Copyright (C) 2017 Linus Walleij <[email protected]>
*
* This is a one-off touchkey controller based on the Cypress Semiconductor
* CY8C214 MCU with some firmware in its internal 8KB flash. The circuit
* board inside the router is named E119921
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/bitops.h>
struct dir685_touchkeys {
struct device *dev;
struct i2c_client *client;
struct input_dev *input;
unsigned long cur_key;
u16 codes[7];
};
static irqreturn_t dir685_tk_irq_thread(int irq, void *data)
{
struct dir685_touchkeys *tk = data;
const int num_bits = min_t(int, ARRAY_SIZE(tk->codes), 16);
unsigned long changed;
u8 buf[6];
unsigned long key;
int i;
int err;
memset(buf, 0, sizeof(buf));
err = i2c_master_recv(tk->client, buf, sizeof(buf));
if (err != sizeof(buf)) {
dev_err(tk->dev, "short read %d\n", err);
return IRQ_HANDLED;
}
dev_dbg(tk->dev, "IN: %*ph\n", (int)sizeof(buf), buf);
key = be16_to_cpup((__be16 *) &buf[4]);
/* Figure out if any bits went high or low since last message */
changed = tk->cur_key ^ key;
for_each_set_bit(i, &changed, num_bits) {
dev_dbg(tk->dev, "key %d is %s\n", i,
test_bit(i, &key) ? "down" : "up");
input_report_key(tk->input, tk->codes[i], test_bit(i, &key));
}
/* Store currently down keys */
tk->cur_key = key;
input_sync(tk->input);
return IRQ_HANDLED;
}
static int dir685_tk_probe(struct i2c_client *client)
{
static const u8 bl_data[] = { 0xa7, 0x40 };
struct device *dev = &client->dev;
struct dir685_touchkeys *tk;
int err;
int i;
tk = devm_kzalloc(&client->dev, sizeof(*tk), GFP_KERNEL);
if (!tk)
return -ENOMEM;
tk->input = devm_input_allocate_device(dev);
if (!tk->input)
return -ENOMEM;
tk->client = client;
tk->dev = dev;
tk->input->keycodesize = sizeof(u16);
tk->input->keycodemax = ARRAY_SIZE(tk->codes);
tk->input->keycode = tk->codes;
tk->codes[0] = KEY_UP;
tk->codes[1] = KEY_DOWN;
tk->codes[2] = KEY_LEFT;
tk->codes[3] = KEY_RIGHT;
tk->codes[4] = KEY_ENTER;
tk->codes[5] = KEY_WPS_BUTTON;
/*
* This key appears in the vendor driver, but I have
* not been able to activate it.
*/
tk->codes[6] = KEY_RESERVED;
__set_bit(EV_KEY, tk->input->evbit);
for (i = 0; i < ARRAY_SIZE(tk->codes); i++)
__set_bit(tk->codes[i], tk->input->keybit);
__clear_bit(KEY_RESERVED, tk->input->keybit);
tk->input->name = "D-Link DIR-685 touchkeys";
tk->input->id.bustype = BUS_I2C;
err = input_register_device(tk->input);
if (err)
return err;
/* Set the brightness to max level */
err = i2c_master_send(client, bl_data, sizeof(bl_data));
if (err != sizeof(bl_data))
dev_warn(tk->dev, "error setting brightness level\n");
if (!client->irq) {
dev_err(dev, "no IRQ on the I2C device\n");
return -ENODEV;
}
err = devm_request_threaded_irq(dev, client->irq,
NULL, dir685_tk_irq_thread,
IRQF_ONESHOT,
"dir685-tk", tk);
if (err) {
dev_err(dev, "can't request IRQ\n");
return err;
}
return 0;
}
static const struct i2c_device_id dir685_tk_id[] = {
{ "dir685tk", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, dir685_tk_id);
#ifdef CONFIG_OF
static const struct of_device_id dir685_tk_of_match[] = {
{ .compatible = "dlink,dir685-touchkeys" },
{},
};
MODULE_DEVICE_TABLE(of, dir685_tk_of_match);
#endif
static struct i2c_driver dir685_tk_i2c_driver = {
.driver = {
.name = "dlink-dir685-touchkeys",
.of_match_table = of_match_ptr(dir685_tk_of_match),
},
.probe = dir685_tk_probe,
.id_table = dir685_tk_id,
};
module_i2c_driver(dir685_tk_i2c_driver);
MODULE_AUTHOR("Linus Walleij <[email protected]>");
MODULE_DESCRIPTION("D-Link DIR-685 touchkeys driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/dlink-dir685-touchkeys.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Keypad driver for Analog Devices ADP5520 MFD PMICs
*
* Copyright 2009 Analog Devices Inc.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/mfd/adp5520.h>
#include <linux/slab.h>
#include <linux/device.h>
struct adp5520_keys {
struct input_dev *input;
struct notifier_block notifier;
struct device *master;
unsigned short keycode[ADP5520_KEYMAPSIZE];
};
static void adp5520_keys_report_event(struct adp5520_keys *dev,
unsigned short keymask, int value)
{
int i;
for (i = 0; i < ADP5520_MAXKEYS; i++)
if (keymask & (1 << i))
input_report_key(dev->input, dev->keycode[i], value);
input_sync(dev->input);
}
static int adp5520_keys_notifier(struct notifier_block *nb,
unsigned long event, void *data)
{
struct adp5520_keys *dev;
uint8_t reg_val_lo, reg_val_hi;
unsigned short keymask;
dev = container_of(nb, struct adp5520_keys, notifier);
if (event & ADP5520_KP_INT) {
adp5520_read(dev->master, ADP5520_KP_INT_STAT_1, ®_val_lo);
adp5520_read(dev->master, ADP5520_KP_INT_STAT_2, ®_val_hi);
keymask = (reg_val_hi << 8) | reg_val_lo;
/* Read twice to clear */
adp5520_read(dev->master, ADP5520_KP_INT_STAT_1, ®_val_lo);
adp5520_read(dev->master, ADP5520_KP_INT_STAT_2, ®_val_hi);
keymask |= (reg_val_hi << 8) | reg_val_lo;
adp5520_keys_report_event(dev, keymask, 1);
}
if (event & ADP5520_KR_INT) {
adp5520_read(dev->master, ADP5520_KR_INT_STAT_1, ®_val_lo);
adp5520_read(dev->master, ADP5520_KR_INT_STAT_2, ®_val_hi);
keymask = (reg_val_hi << 8) | reg_val_lo;
/* Read twice to clear */
adp5520_read(dev->master, ADP5520_KR_INT_STAT_1, ®_val_lo);
adp5520_read(dev->master, ADP5520_KR_INT_STAT_2, ®_val_hi);
keymask |= (reg_val_hi << 8) | reg_val_lo;
adp5520_keys_report_event(dev, keymask, 0);
}
return 0;
}
static int adp5520_keys_probe(struct platform_device *pdev)
{
struct adp5520_keys_platform_data *pdata = dev_get_platdata(&pdev->dev);
struct input_dev *input;
struct adp5520_keys *dev;
int ret, i;
unsigned char en_mask, ctl_mask = 0;
if (pdev->id != ID_ADP5520) {
dev_err(&pdev->dev, "only ADP5520 supports Keypad\n");
return -EINVAL;
}
if (!pdata) {
dev_err(&pdev->dev, "missing platform data\n");
return -EINVAL;
}
if (!(pdata->rows_en_mask && pdata->cols_en_mask))
return -EINVAL;
dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
if (!dev) {
dev_err(&pdev->dev, "failed to alloc memory\n");
return -ENOMEM;
}
input = devm_input_allocate_device(&pdev->dev);
if (!input)
return -ENOMEM;
dev->master = pdev->dev.parent;
dev->input = input;
input->name = pdev->name;
input->phys = "adp5520-keys/input0";
input->dev.parent = &pdev->dev;
input->id.bustype = BUS_I2C;
input->id.vendor = 0x0001;
input->id.product = 0x5520;
input->id.version = 0x0001;
input->keycodesize = sizeof(dev->keycode[0]);
input->keycodemax = pdata->keymapsize;
input->keycode = dev->keycode;
memcpy(dev->keycode, pdata->keymap,
pdata->keymapsize * input->keycodesize);
/* setup input device */
__set_bit(EV_KEY, input->evbit);
if (pdata->repeat)
__set_bit(EV_REP, input->evbit);
for (i = 0; i < input->keycodemax; i++)
__set_bit(dev->keycode[i], input->keybit);
__clear_bit(KEY_RESERVED, input->keybit);
ret = input_register_device(input);
if (ret) {
dev_err(&pdev->dev, "unable to register input device\n");
return ret;
}
en_mask = pdata->rows_en_mask | pdata->cols_en_mask;
ret = adp5520_set_bits(dev->master, ADP5520_GPIO_CFG_1, en_mask);
if (en_mask & ADP5520_COL_C3)
ctl_mask |= ADP5520_C3_MODE;
if (en_mask & ADP5520_ROW_R3)
ctl_mask |= ADP5520_R3_MODE;
if (ctl_mask)
ret |= adp5520_set_bits(dev->master, ADP5520_LED_CONTROL,
ctl_mask);
ret |= adp5520_set_bits(dev->master, ADP5520_GPIO_PULLUP,
pdata->rows_en_mask);
if (ret) {
dev_err(&pdev->dev, "failed to write\n");
return -EIO;
}
dev->notifier.notifier_call = adp5520_keys_notifier;
ret = adp5520_register_notifier(dev->master, &dev->notifier,
ADP5520_KP_IEN | ADP5520_KR_IEN);
if (ret) {
dev_err(&pdev->dev, "failed to register notifier\n");
return ret;
}
platform_set_drvdata(pdev, dev);
return 0;
}
static int adp5520_keys_remove(struct platform_device *pdev)
{
struct adp5520_keys *dev = platform_get_drvdata(pdev);
adp5520_unregister_notifier(dev->master, &dev->notifier,
ADP5520_KP_IEN | ADP5520_KR_IEN);
return 0;
}
static struct platform_driver adp5520_keys_driver = {
.driver = {
.name = "adp5520-keys",
},
.probe = adp5520_keys_probe,
.remove = adp5520_keys_remove,
};
module_platform_driver(adp5520_keys_driver);
MODULE_AUTHOR("Michael Hennerich <[email protected]>");
MODULE_DESCRIPTION("Keys ADP5520 Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:adp5520-keys");
|
linux-master
|
drivers/input/keyboard/adp5520-keys.c
|
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved.
*/
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/regmap.h>
#include <linux/of.h>
#include <linux/input/matrix_keypad.h>
#define PM8XXX_MAX_ROWS 18
#define PM8XXX_MAX_COLS 8
#define PM8XXX_ROW_SHIFT 3
#define PM8XXX_MATRIX_MAX_SIZE (PM8XXX_MAX_ROWS * PM8XXX_MAX_COLS)
#define PM8XXX_MIN_ROWS 5
#define PM8XXX_MIN_COLS 5
#define MAX_SCAN_DELAY 128
#define MIN_SCAN_DELAY 1
/* in nanoseconds */
#define MAX_ROW_HOLD_DELAY 122000
#define MIN_ROW_HOLD_DELAY 30500
#define MAX_DEBOUNCE_TIME 20
#define MIN_DEBOUNCE_TIME 5
#define KEYP_CTRL 0x148
#define KEYP_CTRL_EVNTS BIT(0)
#define KEYP_CTRL_EVNTS_MASK 0x3
#define KEYP_CTRL_SCAN_COLS_SHIFT 5
#define KEYP_CTRL_SCAN_COLS_MIN 5
#define KEYP_CTRL_SCAN_COLS_BITS 0x3
#define KEYP_CTRL_SCAN_ROWS_SHIFT 2
#define KEYP_CTRL_SCAN_ROWS_MIN 5
#define KEYP_CTRL_SCAN_ROWS_BITS 0x7
#define KEYP_CTRL_KEYP_EN BIT(7)
#define KEYP_SCAN 0x149
#define KEYP_SCAN_READ_STATE BIT(0)
#define KEYP_SCAN_DBOUNCE_SHIFT 1
#define KEYP_SCAN_PAUSE_SHIFT 3
#define KEYP_SCAN_ROW_HOLD_SHIFT 6
#define KEYP_TEST 0x14A
#define KEYP_TEST_CLEAR_RECENT_SCAN BIT(6)
#define KEYP_TEST_CLEAR_OLD_SCAN BIT(5)
#define KEYP_TEST_READ_RESET BIT(4)
#define KEYP_TEST_DTEST_EN BIT(3)
#define KEYP_TEST_ABORT_READ BIT(0)
#define KEYP_TEST_DBG_SELECT_SHIFT 1
/* bits of these registers represent
* '0' for key press
* '1' for key release
*/
#define KEYP_RECENT_DATA 0x14B
#define KEYP_OLD_DATA 0x14C
#define KEYP_CLOCK_FREQ 32768
/**
* struct pmic8xxx_kp - internal keypad data structure
* @num_cols: number of columns of keypad
* @num_rows: number of row of keypad
* @input: input device pointer for keypad
* @regmap: regmap handle
* @key_sense_irq: key press/release irq number
* @key_stuck_irq: key stuck notification irq number
* @keycodes: array to hold the key codes
* @dev: parent device pointer
* @keystate: present key press/release state
* @stuckstate: present state when key stuck irq
* @ctrl_reg: control register value
*/
struct pmic8xxx_kp {
unsigned int num_rows;
unsigned int num_cols;
struct input_dev *input;
struct regmap *regmap;
int key_sense_irq;
int key_stuck_irq;
unsigned short keycodes[PM8XXX_MATRIX_MAX_SIZE];
struct device *dev;
u16 keystate[PM8XXX_MAX_ROWS];
u16 stuckstate[PM8XXX_MAX_ROWS];
u8 ctrl_reg;
};
static u8 pmic8xxx_col_state(struct pmic8xxx_kp *kp, u8 col)
{
/* all keys pressed on that particular row? */
if (col == 0x00)
return 1 << kp->num_cols;
else
return col & ((1 << kp->num_cols) - 1);
}
/*
* Synchronous read protocol for RevB0 onwards:
*
* 1. Write '1' to ReadState bit in KEYP_SCAN register
* 2. Wait 2*32KHz clocks, so that HW can successfully enter read mode
* synchronously
* 3. Read rows in old array first if events are more than one
* 4. Read rows in recent array
* 5. Wait 4*32KHz clocks
* 6. Write '0' to ReadState bit of KEYP_SCAN register so that hw can
* synchronously exit read mode.
*/
static int pmic8xxx_chk_sync_read(struct pmic8xxx_kp *kp)
{
int rc;
unsigned int scan_val;
rc = regmap_read(kp->regmap, KEYP_SCAN, &scan_val);
if (rc < 0) {
dev_err(kp->dev, "Error reading KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
scan_val |= 0x1;
rc = regmap_write(kp->regmap, KEYP_SCAN, scan_val);
if (rc < 0) {
dev_err(kp->dev, "Error writing KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
/* 2 * 32KHz clocks */
udelay((2 * DIV_ROUND_UP(USEC_PER_SEC, KEYP_CLOCK_FREQ)) + 1);
return rc;
}
static int pmic8xxx_kp_read_data(struct pmic8xxx_kp *kp, u16 *state,
u16 data_reg, int read_rows)
{
int rc, row;
unsigned int val;
for (row = 0; row < read_rows; row++) {
rc = regmap_read(kp->regmap, data_reg, &val);
if (rc)
return rc;
dev_dbg(kp->dev, "%d = %d\n", row, val);
state[row] = pmic8xxx_col_state(kp, val);
}
return 0;
}
static int pmic8xxx_kp_read_matrix(struct pmic8xxx_kp *kp, u16 *new_state,
u16 *old_state)
{
int rc, read_rows;
unsigned int scan_val;
if (kp->num_rows < PM8XXX_MIN_ROWS)
read_rows = PM8XXX_MIN_ROWS;
else
read_rows = kp->num_rows;
pmic8xxx_chk_sync_read(kp);
if (old_state) {
rc = pmic8xxx_kp_read_data(kp, old_state, KEYP_OLD_DATA,
read_rows);
if (rc < 0) {
dev_err(kp->dev,
"Error reading KEYP_OLD_DATA, rc=%d\n", rc);
return rc;
}
}
rc = pmic8xxx_kp_read_data(kp, new_state, KEYP_RECENT_DATA,
read_rows);
if (rc < 0) {
dev_err(kp->dev,
"Error reading KEYP_RECENT_DATA, rc=%d\n", rc);
return rc;
}
/* 4 * 32KHz clocks */
udelay((4 * DIV_ROUND_UP(USEC_PER_SEC, KEYP_CLOCK_FREQ)) + 1);
rc = regmap_read(kp->regmap, KEYP_SCAN, &scan_val);
if (rc < 0) {
dev_err(kp->dev, "Error reading KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
scan_val &= 0xFE;
rc = regmap_write(kp->regmap, KEYP_SCAN, scan_val);
if (rc < 0)
dev_err(kp->dev, "Error writing KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
static void __pmic8xxx_kp_scan_matrix(struct pmic8xxx_kp *kp, u16 *new_state,
u16 *old_state)
{
int row, col, code;
for (row = 0; row < kp->num_rows; row++) {
int bits_changed = new_state[row] ^ old_state[row];
if (!bits_changed)
continue;
for (col = 0; col < kp->num_cols; col++) {
if (!(bits_changed & (1 << col)))
continue;
dev_dbg(kp->dev, "key [%d:%d] %s\n", row, col,
!(new_state[row] & (1 << col)) ?
"pressed" : "released");
code = MATRIX_SCAN_CODE(row, col, PM8XXX_ROW_SHIFT);
input_event(kp->input, EV_MSC, MSC_SCAN, code);
input_report_key(kp->input,
kp->keycodes[code],
!(new_state[row] & (1 << col)));
input_sync(kp->input);
}
}
}
static bool pmic8xxx_detect_ghost_keys(struct pmic8xxx_kp *kp, u16 *new_state)
{
int row, found_first = -1;
u16 check, row_state;
check = 0;
for (row = 0; row < kp->num_rows; row++) {
row_state = (~new_state[row]) &
((1 << kp->num_cols) - 1);
if (hweight16(row_state) > 1) {
if (found_first == -1)
found_first = row;
if (check & row_state) {
dev_dbg(kp->dev, "detected ghost key on row[%d]"
" and row[%d]\n", found_first, row);
return true;
}
}
check |= row_state;
}
return false;
}
static int pmic8xxx_kp_scan_matrix(struct pmic8xxx_kp *kp, unsigned int events)
{
u16 new_state[PM8XXX_MAX_ROWS];
u16 old_state[PM8XXX_MAX_ROWS];
int rc;
switch (events) {
case 0x1:
rc = pmic8xxx_kp_read_matrix(kp, new_state, NULL);
if (rc < 0)
return rc;
/* detecting ghost key is not an error */
if (pmic8xxx_detect_ghost_keys(kp, new_state))
return 0;
__pmic8xxx_kp_scan_matrix(kp, new_state, kp->keystate);
memcpy(kp->keystate, new_state, sizeof(new_state));
break;
case 0x3: /* two events - eventcounter is gray-coded */
rc = pmic8xxx_kp_read_matrix(kp, new_state, old_state);
if (rc < 0)
return rc;
__pmic8xxx_kp_scan_matrix(kp, old_state, kp->keystate);
__pmic8xxx_kp_scan_matrix(kp, new_state, old_state);
memcpy(kp->keystate, new_state, sizeof(new_state));
break;
case 0x2:
dev_dbg(kp->dev, "Some key events were lost\n");
rc = pmic8xxx_kp_read_matrix(kp, new_state, old_state);
if (rc < 0)
return rc;
__pmic8xxx_kp_scan_matrix(kp, old_state, kp->keystate);
__pmic8xxx_kp_scan_matrix(kp, new_state, old_state);
memcpy(kp->keystate, new_state, sizeof(new_state));
break;
default:
rc = -EINVAL;
}
return rc;
}
/*
* NOTE: We are reading recent and old data registers blindly
* whenever key-stuck interrupt happens, because events counter doesn't
* get updated when this interrupt happens due to key stuck doesn't get
* considered as key state change.
*
* We are not using old data register contents after they are being read
* because it might report the key which was pressed before the key being stuck
* as stuck key because it's pressed status is stored in the old data
* register.
*/
static irqreturn_t pmic8xxx_kp_stuck_irq(int irq, void *data)
{
u16 new_state[PM8XXX_MAX_ROWS];
u16 old_state[PM8XXX_MAX_ROWS];
int rc;
struct pmic8xxx_kp *kp = data;
rc = pmic8xxx_kp_read_matrix(kp, new_state, old_state);
if (rc < 0) {
dev_err(kp->dev, "failed to read keypad matrix\n");
return IRQ_HANDLED;
}
__pmic8xxx_kp_scan_matrix(kp, new_state, kp->stuckstate);
return IRQ_HANDLED;
}
static irqreturn_t pmic8xxx_kp_irq(int irq, void *data)
{
struct pmic8xxx_kp *kp = data;
unsigned int ctrl_val, events;
int rc;
rc = regmap_read(kp->regmap, KEYP_CTRL, &ctrl_val);
if (rc < 0) {
dev_err(kp->dev, "failed to read keyp_ctrl register\n");
return IRQ_HANDLED;
}
events = ctrl_val & KEYP_CTRL_EVNTS_MASK;
rc = pmic8xxx_kp_scan_matrix(kp, events);
if (rc < 0)
dev_err(kp->dev, "failed to scan matrix\n");
return IRQ_HANDLED;
}
static int pmic8xxx_kpd_init(struct pmic8xxx_kp *kp,
struct platform_device *pdev)
{
const struct device_node *of_node = pdev->dev.of_node;
unsigned int scan_delay_ms;
unsigned int row_hold_ns;
unsigned int debounce_ms;
int bits, rc, cycles;
u8 scan_val = 0, ctrl_val = 0;
static const u8 row_bits[] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7, 7,
};
/* Find column bits */
if (kp->num_cols < KEYP_CTRL_SCAN_COLS_MIN)
bits = 0;
else
bits = kp->num_cols - KEYP_CTRL_SCAN_COLS_MIN;
ctrl_val = (bits & KEYP_CTRL_SCAN_COLS_BITS) <<
KEYP_CTRL_SCAN_COLS_SHIFT;
/* Find row bits */
if (kp->num_rows < KEYP_CTRL_SCAN_ROWS_MIN)
bits = 0;
else
bits = row_bits[kp->num_rows - KEYP_CTRL_SCAN_ROWS_MIN];
ctrl_val |= (bits << KEYP_CTRL_SCAN_ROWS_SHIFT);
rc = regmap_write(kp->regmap, KEYP_CTRL, ctrl_val);
if (rc < 0) {
dev_err(kp->dev, "Error writing KEYP_CTRL reg, rc=%d\n", rc);
return rc;
}
if (of_property_read_u32(of_node, "scan-delay", &scan_delay_ms))
scan_delay_ms = MIN_SCAN_DELAY;
if (scan_delay_ms > MAX_SCAN_DELAY || scan_delay_ms < MIN_SCAN_DELAY ||
!is_power_of_2(scan_delay_ms)) {
dev_err(&pdev->dev, "invalid keypad scan time supplied\n");
return -EINVAL;
}
if (of_property_read_u32(of_node, "row-hold", &row_hold_ns))
row_hold_ns = MIN_ROW_HOLD_DELAY;
if (row_hold_ns > MAX_ROW_HOLD_DELAY ||
row_hold_ns < MIN_ROW_HOLD_DELAY ||
((row_hold_ns % MIN_ROW_HOLD_DELAY) != 0)) {
dev_err(&pdev->dev, "invalid keypad row hold time supplied\n");
return -EINVAL;
}
if (of_property_read_u32(of_node, "debounce", &debounce_ms))
debounce_ms = MIN_DEBOUNCE_TIME;
if (((debounce_ms % 5) != 0) ||
debounce_ms > MAX_DEBOUNCE_TIME ||
debounce_ms < MIN_DEBOUNCE_TIME) {
dev_err(&pdev->dev, "invalid debounce time supplied\n");
return -EINVAL;
}
bits = (debounce_ms / 5) - 1;
scan_val |= (bits << KEYP_SCAN_DBOUNCE_SHIFT);
bits = fls(scan_delay_ms) - 1;
scan_val |= (bits << KEYP_SCAN_PAUSE_SHIFT);
/* Row hold time is a multiple of 32KHz cycles. */
cycles = (row_hold_ns * KEYP_CLOCK_FREQ) / NSEC_PER_SEC;
scan_val |= (cycles << KEYP_SCAN_ROW_HOLD_SHIFT);
rc = regmap_write(kp->regmap, KEYP_SCAN, scan_val);
if (rc)
dev_err(kp->dev, "Error writing KEYP_SCAN reg, rc=%d\n", rc);
return rc;
}
static int pmic8xxx_kp_enable(struct pmic8xxx_kp *kp)
{
int rc;
kp->ctrl_reg |= KEYP_CTRL_KEYP_EN;
rc = regmap_write(kp->regmap, KEYP_CTRL, kp->ctrl_reg);
if (rc < 0)
dev_err(kp->dev, "Error writing KEYP_CTRL reg, rc=%d\n", rc);
return rc;
}
static int pmic8xxx_kp_disable(struct pmic8xxx_kp *kp)
{
int rc;
kp->ctrl_reg &= ~KEYP_CTRL_KEYP_EN;
rc = regmap_write(kp->regmap, KEYP_CTRL, kp->ctrl_reg);
if (rc < 0)
return rc;
return rc;
}
static int pmic8xxx_kp_open(struct input_dev *dev)
{
struct pmic8xxx_kp *kp = input_get_drvdata(dev);
return pmic8xxx_kp_enable(kp);
}
static void pmic8xxx_kp_close(struct input_dev *dev)
{
struct pmic8xxx_kp *kp = input_get_drvdata(dev);
pmic8xxx_kp_disable(kp);
}
/*
* keypad controller should be initialized in the following sequence
* only, otherwise it might get into FSM stuck state.
*
* - Initialize keypad control parameters, like no. of rows, columns,
* timing values etc.,
* - configure rows and column gpios pull up/down.
* - set irq edge type.
* - enable the keypad controller.
*/
static int pmic8xxx_kp_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
unsigned int rows, cols;
bool repeat;
bool wakeup;
struct pmic8xxx_kp *kp;
int rc;
unsigned int ctrl_val;
rc = matrix_keypad_parse_properties(&pdev->dev, &rows, &cols);
if (rc)
return rc;
if (cols > PM8XXX_MAX_COLS || rows > PM8XXX_MAX_ROWS ||
cols < PM8XXX_MIN_COLS) {
dev_err(&pdev->dev, "invalid platform data\n");
return -EINVAL;
}
repeat = !of_property_read_bool(np, "linux,input-no-autorepeat");
wakeup = of_property_read_bool(np, "wakeup-source") ||
/* legacy name */
of_property_read_bool(np, "linux,keypad-wakeup");
kp = devm_kzalloc(&pdev->dev, sizeof(*kp), GFP_KERNEL);
if (!kp)
return -ENOMEM;
kp->regmap = dev_get_regmap(pdev->dev.parent, NULL);
if (!kp->regmap)
return -ENODEV;
platform_set_drvdata(pdev, kp);
kp->num_rows = rows;
kp->num_cols = cols;
kp->dev = &pdev->dev;
kp->input = devm_input_allocate_device(&pdev->dev);
if (!kp->input) {
dev_err(&pdev->dev, "unable to allocate input device\n");
return -ENOMEM;
}
kp->key_sense_irq = platform_get_irq(pdev, 0);
if (kp->key_sense_irq < 0)
return kp->key_sense_irq;
kp->key_stuck_irq = platform_get_irq(pdev, 1);
if (kp->key_stuck_irq < 0)
return kp->key_stuck_irq;
kp->input->name = "PMIC8XXX keypad";
kp->input->phys = "pmic8xxx_keypad/input0";
kp->input->id.bustype = BUS_I2C;
kp->input->id.version = 0x0001;
kp->input->id.product = 0x0001;
kp->input->id.vendor = 0x0001;
kp->input->open = pmic8xxx_kp_open;
kp->input->close = pmic8xxx_kp_close;
rc = matrix_keypad_build_keymap(NULL, NULL,
PM8XXX_MAX_ROWS, PM8XXX_MAX_COLS,
kp->keycodes, kp->input);
if (rc) {
dev_err(&pdev->dev, "failed to build keymap\n");
return rc;
}
if (repeat)
__set_bit(EV_REP, kp->input->evbit);
input_set_capability(kp->input, EV_MSC, MSC_SCAN);
input_set_drvdata(kp->input, kp);
/* initialize keypad state */
memset(kp->keystate, 0xff, sizeof(kp->keystate));
memset(kp->stuckstate, 0xff, sizeof(kp->stuckstate));
rc = pmic8xxx_kpd_init(kp, pdev);
if (rc < 0) {
dev_err(&pdev->dev, "unable to initialize keypad controller\n");
return rc;
}
rc = devm_request_any_context_irq(&pdev->dev, kp->key_sense_irq,
pmic8xxx_kp_irq, IRQF_TRIGGER_RISING, "pmic-keypad",
kp);
if (rc < 0) {
dev_err(&pdev->dev, "failed to request keypad sense irq\n");
return rc;
}
rc = devm_request_any_context_irq(&pdev->dev, kp->key_stuck_irq,
pmic8xxx_kp_stuck_irq, IRQF_TRIGGER_RISING,
"pmic-keypad-stuck", kp);
if (rc < 0) {
dev_err(&pdev->dev, "failed to request keypad stuck irq\n");
return rc;
}
rc = regmap_read(kp->regmap, KEYP_CTRL, &ctrl_val);
if (rc < 0) {
dev_err(&pdev->dev, "failed to read KEYP_CTRL register\n");
return rc;
}
kp->ctrl_reg = ctrl_val;
rc = input_register_device(kp->input);
if (rc < 0) {
dev_err(&pdev->dev, "unable to register keypad input device\n");
return rc;
}
device_init_wakeup(&pdev->dev, wakeup);
return 0;
}
static int pmic8xxx_kp_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct pmic8xxx_kp *kp = platform_get_drvdata(pdev);
struct input_dev *input_dev = kp->input;
if (device_may_wakeup(dev)) {
enable_irq_wake(kp->key_sense_irq);
} else {
mutex_lock(&input_dev->mutex);
if (input_device_enabled(input_dev))
pmic8xxx_kp_disable(kp);
mutex_unlock(&input_dev->mutex);
}
return 0;
}
static int pmic8xxx_kp_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct pmic8xxx_kp *kp = platform_get_drvdata(pdev);
struct input_dev *input_dev = kp->input;
if (device_may_wakeup(dev)) {
disable_irq_wake(kp->key_sense_irq);
} else {
mutex_lock(&input_dev->mutex);
if (input_device_enabled(input_dev))
pmic8xxx_kp_enable(kp);
mutex_unlock(&input_dev->mutex);
}
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(pm8xxx_kp_pm_ops,
pmic8xxx_kp_suspend, pmic8xxx_kp_resume);
static const struct of_device_id pm8xxx_match_table[] = {
{ .compatible = "qcom,pm8058-keypad" },
{ .compatible = "qcom,pm8921-keypad" },
{ }
};
MODULE_DEVICE_TABLE(of, pm8xxx_match_table);
static struct platform_driver pmic8xxx_kp_driver = {
.probe = pmic8xxx_kp_probe,
.driver = {
.name = "pm8xxx-keypad",
.pm = pm_sleep_ptr(&pm8xxx_kp_pm_ops),
.of_match_table = pm8xxx_match_table,
},
};
module_platform_driver(pmic8xxx_kp_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("PMIC8XXX keypad driver");
MODULE_ALIAS("platform:pmic8xxx_keypad");
MODULE_AUTHOR("Trilok Soni <[email protected]>");
|
linux-master
|
drivers/input/keyboard/pmic8xxx-keypad.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000-2001 Vojtech Pavlik
*
* Based on the work of:
* Hamish Macdonald
*/
/*
* Amiga keyboard driver for Linux/m68k
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/keyboard.h>
#include <linux/platform_device.h>
#include <asm/amigaints.h>
#include <asm/amigahw.h>
#include <asm/irq.h>
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION("Amiga keyboard driver");
MODULE_LICENSE("GPL");
#ifdef CONFIG_HW_CONSOLE
static unsigned char amikbd_keycode[0x78] __initdata = {
[0] = KEY_GRAVE,
[1] = KEY_1,
[2] = KEY_2,
[3] = KEY_3,
[4] = KEY_4,
[5] = KEY_5,
[6] = KEY_6,
[7] = KEY_7,
[8] = KEY_8,
[9] = KEY_9,
[10] = KEY_0,
[11] = KEY_MINUS,
[12] = KEY_EQUAL,
[13] = KEY_BACKSLASH,
[15] = KEY_KP0,
[16] = KEY_Q,
[17] = KEY_W,
[18] = KEY_E,
[19] = KEY_R,
[20] = KEY_T,
[21] = KEY_Y,
[22] = KEY_U,
[23] = KEY_I,
[24] = KEY_O,
[25] = KEY_P,
[26] = KEY_LEFTBRACE,
[27] = KEY_RIGHTBRACE,
[29] = KEY_KP1,
[30] = KEY_KP2,
[31] = KEY_KP3,
[32] = KEY_A,
[33] = KEY_S,
[34] = KEY_D,
[35] = KEY_F,
[36] = KEY_G,
[37] = KEY_H,
[38] = KEY_J,
[39] = KEY_K,
[40] = KEY_L,
[41] = KEY_SEMICOLON,
[42] = KEY_APOSTROPHE,
[43] = KEY_BACKSLASH,
[45] = KEY_KP4,
[46] = KEY_KP5,
[47] = KEY_KP6,
[48] = KEY_102ND,
[49] = KEY_Z,
[50] = KEY_X,
[51] = KEY_C,
[52] = KEY_V,
[53] = KEY_B,
[54] = KEY_N,
[55] = KEY_M,
[56] = KEY_COMMA,
[57] = KEY_DOT,
[58] = KEY_SLASH,
[60] = KEY_KPDOT,
[61] = KEY_KP7,
[62] = KEY_KP8,
[63] = KEY_KP9,
[64] = KEY_SPACE,
[65] = KEY_BACKSPACE,
[66] = KEY_TAB,
[67] = KEY_KPENTER,
[68] = KEY_ENTER,
[69] = KEY_ESC,
[70] = KEY_DELETE,
[74] = KEY_KPMINUS,
[76] = KEY_UP,
[77] = KEY_DOWN,
[78] = KEY_RIGHT,
[79] = KEY_LEFT,
[80] = KEY_F1,
[81] = KEY_F2,
[82] = KEY_F3,
[83] = KEY_F4,
[84] = KEY_F5,
[85] = KEY_F6,
[86] = KEY_F7,
[87] = KEY_F8,
[88] = KEY_F9,
[89] = KEY_F10,
[90] = KEY_KPLEFTPAREN,
[91] = KEY_KPRIGHTPAREN,
[92] = KEY_KPSLASH,
[93] = KEY_KPASTERISK,
[94] = KEY_KPPLUS,
[95] = KEY_HELP,
[96] = KEY_LEFTSHIFT,
[97] = KEY_RIGHTSHIFT,
[98] = KEY_CAPSLOCK,
[99] = KEY_LEFTCTRL,
[100] = KEY_LEFTALT,
[101] = KEY_RIGHTALT,
[102] = KEY_LEFTMETA,
[103] = KEY_RIGHTMETA
};
static void __init amikbd_init_console_keymaps(void)
{
/* We can spare 512 bytes on stack for temp_map in init path. */
unsigned short temp_map[NR_KEYS];
int i, j;
for (i = 0; i < MAX_NR_KEYMAPS; i++) {
if (!key_maps[i])
continue;
memset(temp_map, 0, sizeof(temp_map));
for (j = 0; j < 0x78; j++) {
if (!amikbd_keycode[j])
continue;
temp_map[j] = key_maps[i][amikbd_keycode[j]];
}
for (j = 0; j < NR_KEYS; j++) {
if (!temp_map[j])
temp_map[j] = 0xf200;
}
memcpy(key_maps[i], temp_map, sizeof(temp_map));
}
}
#else /* !CONFIG_HW_CONSOLE */
static inline void amikbd_init_console_keymaps(void) {}
#endif /* !CONFIG_HW_CONSOLE */
static const char *amikbd_messages[8] = {
[0] = KERN_ALERT "amikbd: Ctrl-Amiga-Amiga reset warning!!\n",
[1] = KERN_WARNING "amikbd: keyboard lost sync\n",
[2] = KERN_WARNING "amikbd: keyboard buffer overflow\n",
[3] = KERN_WARNING "amikbd: keyboard controller failure\n",
[4] = KERN_ERR "amikbd: keyboard selftest failure\n",
[5] = KERN_INFO "amikbd: initiate power-up key stream\n",
[6] = KERN_INFO "amikbd: terminate power-up key stream\n",
[7] = KERN_WARNING "amikbd: keyboard interrupt\n"
};
static irqreturn_t amikbd_interrupt(int irq, void *data)
{
struct input_dev *dev = data;
unsigned char scancode, down;
scancode = ~ciaa.sdr; /* get and invert scancode (keyboard is active low) */
ciaa.cra |= 0x40; /* switch SP pin to output for handshake */
udelay(85); /* wait until 85 us have expired */
ciaa.cra &= ~0x40; /* switch CIA serial port to input mode */
down = !(scancode & 1); /* lowest bit is release bit */
scancode >>= 1;
if (scancode < 0x78) { /* scancodes < 0x78 are keys */
if (scancode == 98) { /* CapsLock is a toggle switch key on Amiga */
input_report_key(dev, scancode, 1);
input_report_key(dev, scancode, 0);
} else {
input_report_key(dev, scancode, down);
}
input_sync(dev);
} else /* scancodes >= 0x78 are error codes */
printk(amikbd_messages[scancode - 0x78]);
return IRQ_HANDLED;
}
static int __init amikbd_probe(struct platform_device *pdev)
{
struct input_dev *dev;
int i, err;
dev = devm_input_allocate_device(&pdev->dev);
if (!dev) {
dev_err(&pdev->dev, "Not enough memory for input device\n");
return -ENOMEM;
}
dev->name = pdev->name;
dev->phys = "amikbd/input0";
dev->id.bustype = BUS_AMIGA;
dev->id.vendor = 0x0001;
dev->id.product = 0x0001;
dev->id.version = 0x0100;
dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
for (i = 0; i < 0x78; i++)
set_bit(i, dev->keybit);
amikbd_init_console_keymaps();
ciaa.cra &= ~0x41; /* serial data in, turn off TA */
err = devm_request_irq(&pdev->dev, IRQ_AMIGA_CIAA_SP, amikbd_interrupt,
0, "amikbd", dev);
if (err)
return err;
err = input_register_device(dev);
if (err)
return err;
platform_set_drvdata(pdev, dev);
return 0;
}
static struct platform_driver amikbd_driver = {
.driver = {
.name = "amiga-keyboard",
},
};
module_platform_driver_probe(amikbd_driver, amikbd_probe);
MODULE_ALIAS("platform:amiga-keyboard");
|
linux-master
|
drivers/input/keyboard/amikbd.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Stowaway keyboard driver for Linux
*/
/*
* Copyright (c) 2006 Marek Vasut
*
* Based on Newton keyboard driver for Linux
* by Justin Cormack
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Stowaway keyboard driver"
MODULE_AUTHOR("Marek Vasut <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define SKBD_KEY_MASK 0x7f
#define SKBD_RELEASE 0x80
static unsigned char skbd_keycode[128] = {
KEY_1, KEY_2, KEY_3, KEY_Z, KEY_4, KEY_5, KEY_6, KEY_7,
0, KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T, KEY_Y, KEY_GRAVE,
KEY_X, KEY_A, KEY_S, KEY_D, KEY_F, KEY_G, KEY_H, KEY_SPACE,
KEY_CAPSLOCK, KEY_TAB, KEY_LEFTCTRL, 0, 0, 0, 0, 0,
0, 0, 0, KEY_LEFTALT, 0, 0, 0, 0,
0, 0, 0, 0, KEY_C, KEY_V, KEY_B, KEY_N,
KEY_MINUS, KEY_EQUAL, KEY_BACKSPACE, KEY_HOME, KEY_8, KEY_9, KEY_0, KEY_ESC,
KEY_LEFTBRACE, KEY_RIGHTBRACE, KEY_BACKSLASH, KEY_END, KEY_U, KEY_I, KEY_O, KEY_P,
KEY_APOSTROPHE, KEY_ENTER, KEY_PAGEUP,0, KEY_J, KEY_K, KEY_L, KEY_SEMICOLON,
KEY_SLASH, KEY_UP, KEY_PAGEDOWN, 0,KEY_M, KEY_COMMA, KEY_DOT, KEY_INSERT,
KEY_DELETE, KEY_LEFT, KEY_DOWN, KEY_RIGHT, 0, 0, 0,
KEY_LEFTSHIFT, KEY_RIGHTSHIFT, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7,
KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, 0, 0, 0
};
struct skbd {
unsigned char keycode[128];
struct input_dev *dev;
struct serio *serio;
char phys[32];
};
static irqreturn_t skbd_interrupt(struct serio *serio, unsigned char data,
unsigned int flags)
{
struct skbd *skbd = serio_get_drvdata(serio);
struct input_dev *dev = skbd->dev;
if (skbd->keycode[data & SKBD_KEY_MASK]) {
input_report_key(dev, skbd->keycode[data & SKBD_KEY_MASK],
!(data & SKBD_RELEASE));
input_sync(dev);
}
return IRQ_HANDLED;
}
static int skbd_connect(struct serio *serio, struct serio_driver *drv)
{
struct skbd *skbd;
struct input_dev *input_dev;
int err = -ENOMEM;
int i;
skbd = kzalloc(sizeof(struct skbd), GFP_KERNEL);
input_dev = input_allocate_device();
if (!skbd || !input_dev)
goto fail1;
skbd->serio = serio;
skbd->dev = input_dev;
snprintf(skbd->phys, sizeof(skbd->phys), "%s/input0", serio->phys);
memcpy(skbd->keycode, skbd_keycode, sizeof(skbd->keycode));
input_dev->name = "Stowaway Keyboard";
input_dev->phys = skbd->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_STOWAWAY;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
input_dev->keycode = skbd->keycode;
input_dev->keycodesize = sizeof(unsigned char);
input_dev->keycodemax = ARRAY_SIZE(skbd_keycode);
for (i = 0; i < ARRAY_SIZE(skbd_keycode); i++)
set_bit(skbd_keycode[i], input_dev->keybit);
clear_bit(0, input_dev->keybit);
serio_set_drvdata(serio, skbd);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(skbd->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(skbd);
return err;
}
static void skbd_disconnect(struct serio *serio)
{
struct skbd *skbd = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(skbd->dev);
kfree(skbd);
}
static const struct serio_device_id skbd_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_STOWAWAY,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, skbd_serio_ids);
static struct serio_driver skbd_drv = {
.driver = {
.name = "stowaway",
},
.description = DRIVER_DESC,
.id_table = skbd_serio_ids,
.interrupt = skbd_interrupt,
.connect = skbd_connect,
.disconnect = skbd_disconnect,
};
module_serio_driver(skbd_drv);
|
linux-master
|
drivers/input/keyboard/stowaway.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Cypress StreetFighter Touchkey Driver
*
* Copyright (c) 2021 Yassine Oudjana <[email protected]>
*/
#include <linux/bitmap.h>
#include <linux/bitops.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/pm.h>
#include <linux/regulator/consumer.h>
#define CYPRESS_SF_DEV_NAME "cypress-sf"
#define CYPRESS_SF_REG_BUTTON_STATUS 0x4a
struct cypress_sf_data {
struct i2c_client *client;
struct input_dev *input_dev;
struct regulator_bulk_data regulators[2];
u32 *keycodes;
unsigned long keystates;
int num_keys;
};
static irqreturn_t cypress_sf_irq_handler(int irq, void *devid)
{
struct cypress_sf_data *touchkey = devid;
unsigned long keystates, changed;
bool new_state;
int val, key;
val = i2c_smbus_read_byte_data(touchkey->client,
CYPRESS_SF_REG_BUTTON_STATUS);
if (val < 0) {
dev_err(&touchkey->client->dev,
"Failed to read button status: %d", val);
return IRQ_NONE;
}
keystates = val;
bitmap_xor(&changed, &keystates, &touchkey->keystates,
touchkey->num_keys);
for_each_set_bit(key, &changed, touchkey->num_keys) {
new_state = keystates & BIT(key);
dev_dbg(&touchkey->client->dev,
"Key %d changed to %d", key, new_state);
input_report_key(touchkey->input_dev,
touchkey->keycodes[key], new_state);
}
input_sync(touchkey->input_dev);
touchkey->keystates = keystates;
return IRQ_HANDLED;
}
static void cypress_sf_disable_regulators(void *arg)
{
struct cypress_sf_data *touchkey = arg;
regulator_bulk_disable(ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
}
static int cypress_sf_probe(struct i2c_client *client)
{
struct cypress_sf_data *touchkey;
int key, error;
touchkey = devm_kzalloc(&client->dev, sizeof(*touchkey), GFP_KERNEL);
if (!touchkey)
return -ENOMEM;
touchkey->client = client;
i2c_set_clientdata(client, touchkey);
touchkey->regulators[0].supply = "vdd";
touchkey->regulators[1].supply = "avdd";
error = devm_regulator_bulk_get(&client->dev,
ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
if (error) {
dev_err(&client->dev, "Failed to get regulators: %d\n", error);
return error;
}
touchkey->num_keys = device_property_read_u32_array(&client->dev,
"linux,keycodes",
NULL, 0);
if (touchkey->num_keys < 0) {
/* Default key count */
touchkey->num_keys = 2;
}
touchkey->keycodes = devm_kcalloc(&client->dev,
touchkey->num_keys,
sizeof(*touchkey->keycodes),
GFP_KERNEL);
if (!touchkey->keycodes)
return -ENOMEM;
error = device_property_read_u32_array(&client->dev, "linux,keycodes",
touchkey->keycodes,
touchkey->num_keys);
if (error) {
dev_warn(&client->dev,
"Failed to read keycodes: %d, using defaults\n",
error);
/* Default keycodes */
touchkey->keycodes[0] = KEY_BACK;
touchkey->keycodes[1] = KEY_MENU;
}
error = regulator_bulk_enable(ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
if (error) {
dev_err(&client->dev,
"Failed to enable regulators: %d\n", error);
return error;
}
error = devm_add_action_or_reset(&client->dev,
cypress_sf_disable_regulators,
touchkey);
if (error)
return error;
touchkey->input_dev = devm_input_allocate_device(&client->dev);
if (!touchkey->input_dev) {
dev_err(&client->dev, "Failed to allocate input device\n");
return -ENOMEM;
}
touchkey->input_dev->name = CYPRESS_SF_DEV_NAME;
touchkey->input_dev->id.bustype = BUS_I2C;
for (key = 0; key < touchkey->num_keys; ++key)
input_set_capability(touchkey->input_dev,
EV_KEY, touchkey->keycodes[key]);
error = input_register_device(touchkey->input_dev);
if (error) {
dev_err(&client->dev,
"Failed to register input device: %d\n", error);
return error;
}
error = devm_request_threaded_irq(&client->dev, client->irq,
NULL, cypress_sf_irq_handler,
IRQF_ONESHOT,
CYPRESS_SF_DEV_NAME, touchkey);
if (error) {
dev_err(&client->dev,
"Failed to register threaded irq: %d", error);
return error;
}
return 0;
};
static int cypress_sf_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct cypress_sf_data *touchkey = i2c_get_clientdata(client);
int error;
disable_irq(client->irq);
error = regulator_bulk_disable(ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
if (error) {
dev_err(dev, "Failed to disable regulators: %d", error);
enable_irq(client->irq);
return error;
}
return 0;
}
static int cypress_sf_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct cypress_sf_data *touchkey = i2c_get_clientdata(client);
int error;
error = regulator_bulk_enable(ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
if (error) {
dev_err(dev, "Failed to enable regulators: %d", error);
return error;
}
enable_irq(client->irq);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(cypress_sf_pm_ops,
cypress_sf_suspend, cypress_sf_resume);
static struct i2c_device_id cypress_sf_id_table[] = {
{ CYPRESS_SF_DEV_NAME, 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, cypress_sf_id_table);
#ifdef CONFIG_OF
static const struct of_device_id cypress_sf_of_match[] = {
{ .compatible = "cypress,sf3155", },
{ },
};
MODULE_DEVICE_TABLE(of, cypress_sf_of_match);
#endif
static struct i2c_driver cypress_sf_driver = {
.driver = {
.name = CYPRESS_SF_DEV_NAME,
.pm = pm_sleep_ptr(&cypress_sf_pm_ops),
.of_match_table = of_match_ptr(cypress_sf_of_match),
},
.id_table = cypress_sf_id_table,
.probe = cypress_sf_probe,
};
module_i2c_driver(cypress_sf_driver);
MODULE_AUTHOR("Yassine Oudjana <[email protected]>");
MODULE_DESCRIPTION("Cypress StreetFighter Touchkey Driver");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/keyboard/cypress-sf.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* File: drivers/input/keyboard/adp5588_keys.c
* Description: keypad driver for ADP5588 and ADP5587
* I2C QWERTY Keypad and IO Expander
* Bugs: Enter bugs at http://blackfin.uclinux.org/
*
* Copyright (C) 2008-2010 Analog Devices Inc.
*/
#include <linux/bits.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/gpio/consumer.h>
#include <linux/gpio/driver.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/ktime.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/pinctrl/pinconf-generic.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
#include <linux/timekeeping.h>
#define DEV_ID 0x00 /* Device ID */
#define CFG 0x01 /* Configuration Register1 */
#define INT_STAT 0x02 /* Interrupt Status Register */
#define KEY_LCK_EC_STAT 0x03 /* Key Lock and Event Counter Register */
#define KEY_EVENTA 0x04 /* Key Event Register A */
#define KEY_EVENTB 0x05 /* Key Event Register B */
#define KEY_EVENTC 0x06 /* Key Event Register C */
#define KEY_EVENTD 0x07 /* Key Event Register D */
#define KEY_EVENTE 0x08 /* Key Event Register E */
#define KEY_EVENTF 0x09 /* Key Event Register F */
#define KEY_EVENTG 0x0A /* Key Event Register G */
#define KEY_EVENTH 0x0B /* Key Event Register H */
#define KEY_EVENTI 0x0C /* Key Event Register I */
#define KEY_EVENTJ 0x0D /* Key Event Register J */
#define KP_LCK_TMR 0x0E /* Keypad Lock1 to Lock2 Timer */
#define UNLOCK1 0x0F /* Unlock Key1 */
#define UNLOCK2 0x10 /* Unlock Key2 */
#define GPIO_INT_STAT1 0x11 /* GPIO Interrupt Status */
#define GPIO_INT_STAT2 0x12 /* GPIO Interrupt Status */
#define GPIO_INT_STAT3 0x13 /* GPIO Interrupt Status */
#define GPIO_DAT_STAT1 0x14 /* GPIO Data Status, Read twice to clear */
#define GPIO_DAT_STAT2 0x15 /* GPIO Data Status, Read twice to clear */
#define GPIO_DAT_STAT3 0x16 /* GPIO Data Status, Read twice to clear */
#define GPIO_DAT_OUT1 0x17 /* GPIO DATA OUT */
#define GPIO_DAT_OUT2 0x18 /* GPIO DATA OUT */
#define GPIO_DAT_OUT3 0x19 /* GPIO DATA OUT */
#define GPIO_INT_EN1 0x1A /* GPIO Interrupt Enable */
#define GPIO_INT_EN2 0x1B /* GPIO Interrupt Enable */
#define GPIO_INT_EN3 0x1C /* GPIO Interrupt Enable */
#define KP_GPIO1 0x1D /* Keypad or GPIO Selection */
#define KP_GPIO2 0x1E /* Keypad or GPIO Selection */
#define KP_GPIO3 0x1F /* Keypad or GPIO Selection */
#define GPI_EM1 0x20 /* GPI Event Mode 1 */
#define GPI_EM2 0x21 /* GPI Event Mode 2 */
#define GPI_EM3 0x22 /* GPI Event Mode 3 */
#define GPIO_DIR1 0x23 /* GPIO Data Direction */
#define GPIO_DIR2 0x24 /* GPIO Data Direction */
#define GPIO_DIR3 0x25 /* GPIO Data Direction */
#define GPIO_INT_LVL1 0x26 /* GPIO Edge/Level Detect */
#define GPIO_INT_LVL2 0x27 /* GPIO Edge/Level Detect */
#define GPIO_INT_LVL3 0x28 /* GPIO Edge/Level Detect */
#define DEBOUNCE_DIS1 0x29 /* Debounce Disable */
#define DEBOUNCE_DIS2 0x2A /* Debounce Disable */
#define DEBOUNCE_DIS3 0x2B /* Debounce Disable */
#define GPIO_PULL1 0x2C /* GPIO Pull Disable */
#define GPIO_PULL2 0x2D /* GPIO Pull Disable */
#define GPIO_PULL3 0x2E /* GPIO Pull Disable */
#define CMP_CFG_STAT 0x30 /* Comparator Configuration and Status Register */
#define CMP_CONFG_SENS1 0x31 /* Sensor1 Comparator Configuration Register */
#define CMP_CONFG_SENS2 0x32 /* L2 Light Sensor Reference Level, Output Falling for Sensor 1 */
#define CMP1_LVL2_TRIP 0x33 /* L2 Light Sensor Hysteresis (Active when Output Rising) for Sensor 1 */
#define CMP1_LVL2_HYS 0x34 /* L3 Light Sensor Reference Level, Output Falling For Sensor 1 */
#define CMP1_LVL3_TRIP 0x35 /* L3 Light Sensor Hysteresis (Active when Output Rising) For Sensor 1 */
#define CMP1_LVL3_HYS 0x36 /* Sensor 2 Comparator Configuration Register */
#define CMP2_LVL2_TRIP 0x37 /* L2 Light Sensor Reference Level, Output Falling for Sensor 2 */
#define CMP2_LVL2_HYS 0x38 /* L2 Light Sensor Hysteresis (Active when Output Rising) for Sensor 2 */
#define CMP2_LVL3_TRIP 0x39 /* L3 Light Sensor Reference Level, Output Falling For Sensor 2 */
#define CMP2_LVL3_HYS 0x3A /* L3 Light Sensor Hysteresis (Active when Output Rising) For Sensor 2 */
#define CMP1_ADC_DAT_R1 0x3B /* Comparator 1 ADC data Register1 */
#define CMP1_ADC_DAT_R2 0x3C /* Comparator 1 ADC data Register2 */
#define CMP2_ADC_DAT_R1 0x3D /* Comparator 2 ADC data Register1 */
#define CMP2_ADC_DAT_R2 0x3E /* Comparator 2 ADC data Register2 */
#define ADP5588_DEVICE_ID_MASK 0xF
/* Configuration Register1 */
#define ADP5588_AUTO_INC BIT(7)
#define ADP5588_GPIEM_CFG BIT(6)
#define ADP5588_OVR_FLOW_M BIT(5)
#define ADP5588_INT_CFG BIT(4)
#define ADP5588_OVR_FLOW_IEN BIT(3)
#define ADP5588_K_LCK_IM BIT(2)
#define ADP5588_GPI_IEN BIT(1)
#define ADP5588_KE_IEN BIT(0)
/* Interrupt Status Register */
#define ADP5588_CMP2_INT BIT(5)
#define ADP5588_CMP1_INT BIT(4)
#define ADP5588_OVR_FLOW_INT BIT(3)
#define ADP5588_K_LCK_INT BIT(2)
#define ADP5588_GPI_INT BIT(1)
#define ADP5588_KE_INT BIT(0)
/* Key Lock and Event Counter Register */
#define ADP5588_K_LCK_EN BIT(6)
#define ADP5588_LCK21 0x30
#define ADP5588_KEC GENMASK(3, 0)
#define ADP5588_MAXGPIO 18
#define ADP5588_BANK(offs) ((offs) >> 3)
#define ADP5588_BIT(offs) (1u << ((offs) & 0x7))
/* Put one of these structures in i2c_board_info platform_data */
/*
* 128 so it fits matrix-keymap maximum number of keys when the full
* 10cols * 8rows are used.
*/
#define ADP5588_KEYMAPSIZE 128
#define GPI_PIN_ROW0 97
#define GPI_PIN_ROW1 98
#define GPI_PIN_ROW2 99
#define GPI_PIN_ROW3 100
#define GPI_PIN_ROW4 101
#define GPI_PIN_ROW5 102
#define GPI_PIN_ROW6 103
#define GPI_PIN_ROW7 104
#define GPI_PIN_COL0 105
#define GPI_PIN_COL1 106
#define GPI_PIN_COL2 107
#define GPI_PIN_COL3 108
#define GPI_PIN_COL4 109
#define GPI_PIN_COL5 110
#define GPI_PIN_COL6 111
#define GPI_PIN_COL7 112
#define GPI_PIN_COL8 113
#define GPI_PIN_COL9 114
#define GPI_PIN_ROW_BASE GPI_PIN_ROW0
#define GPI_PIN_ROW_END GPI_PIN_ROW7
#define GPI_PIN_COL_BASE GPI_PIN_COL0
#define GPI_PIN_COL_END GPI_PIN_COL9
#define GPI_PIN_BASE GPI_PIN_ROW_BASE
#define GPI_PIN_END GPI_PIN_COL_END
#define ADP5588_ROWS_MAX (GPI_PIN_ROW7 - GPI_PIN_ROW0 + 1)
#define ADP5588_COLS_MAX (GPI_PIN_COL9 - GPI_PIN_COL0 + 1)
#define ADP5588_GPIMAPSIZE_MAX (GPI_PIN_END - GPI_PIN_BASE + 1)
/* Key Event Register xy */
#define KEY_EV_PRESSED BIT(7)
#define KEY_EV_MASK GENMASK(6, 0)
#define KP_SEL(x) (BIT(x) - 1) /* 2^x-1 */
#define KEYP_MAX_EVENT 10
/*
* Early pre 4.0 Silicon required to delay readout by at least 25ms,
* since the Event Counter Register updated 25ms after the interrupt
* asserted.
*/
#define WA_DELAYED_READOUT_REVID(rev) ((rev) < 4)
#define WA_DELAYED_READOUT_TIME 25
#define ADP5588_INVALID_HWIRQ (~0UL)
struct adp5588_kpad {
struct i2c_client *client;
struct input_dev *input;
ktime_t irq_time;
unsigned long delay;
u32 row_shift;
u32 rows;
u32 cols;
u32 unlock_keys[2];
int nkeys_unlock;
unsigned short keycode[ADP5588_KEYMAPSIZE];
unsigned char gpiomap[ADP5588_MAXGPIO];
struct gpio_chip gc;
struct mutex gpio_lock; /* Protect cached dir, dat_out */
u8 dat_out[3];
u8 dir[3];
u8 int_en[3];
u8 irq_mask[3];
u8 pull_dis[3];
};
static int adp5588_read(struct i2c_client *client, u8 reg)
{
int ret = i2c_smbus_read_byte_data(client, reg);
if (ret < 0)
dev_err(&client->dev, "Read Error\n");
return ret;
}
static int adp5588_write(struct i2c_client *client, u8 reg, u8 val)
{
return i2c_smbus_write_byte_data(client, reg, val);
}
static int adp5588_gpio_get_value(struct gpio_chip *chip, unsigned int off)
{
struct adp5588_kpad *kpad = gpiochip_get_data(chip);
unsigned int bank = ADP5588_BANK(kpad->gpiomap[off]);
unsigned int bit = ADP5588_BIT(kpad->gpiomap[off]);
int val;
mutex_lock(&kpad->gpio_lock);
if (kpad->dir[bank] & bit)
val = kpad->dat_out[bank];
else
val = adp5588_read(kpad->client, GPIO_DAT_STAT1 + bank);
mutex_unlock(&kpad->gpio_lock);
return !!(val & bit);
}
static void adp5588_gpio_set_value(struct gpio_chip *chip,
unsigned int off, int val)
{
struct adp5588_kpad *kpad = gpiochip_get_data(chip);
unsigned int bank = ADP5588_BANK(kpad->gpiomap[off]);
unsigned int bit = ADP5588_BIT(kpad->gpiomap[off]);
mutex_lock(&kpad->gpio_lock);
if (val)
kpad->dat_out[bank] |= bit;
else
kpad->dat_out[bank] &= ~bit;
adp5588_write(kpad->client, GPIO_DAT_OUT1 + bank, kpad->dat_out[bank]);
mutex_unlock(&kpad->gpio_lock);
}
static int adp5588_gpio_set_config(struct gpio_chip *chip, unsigned int off,
unsigned long config)
{
struct adp5588_kpad *kpad = gpiochip_get_data(chip);
unsigned int bank = ADP5588_BANK(kpad->gpiomap[off]);
unsigned int bit = ADP5588_BIT(kpad->gpiomap[off]);
bool pull_disable;
int ret;
switch (pinconf_to_config_param(config)) {
case PIN_CONFIG_BIAS_PULL_UP:
pull_disable = false;
break;
case PIN_CONFIG_BIAS_DISABLE:
pull_disable = true;
break;
default:
return -ENOTSUPP;
}
mutex_lock(&kpad->gpio_lock);
if (pull_disable)
kpad->pull_dis[bank] |= bit;
else
kpad->pull_dis[bank] &= bit;
ret = adp5588_write(kpad->client, GPIO_PULL1 + bank,
kpad->pull_dis[bank]);
mutex_unlock(&kpad->gpio_lock);
return ret;
}
static int adp5588_gpio_direction_input(struct gpio_chip *chip, unsigned int off)
{
struct adp5588_kpad *kpad = gpiochip_get_data(chip);
unsigned int bank = ADP5588_BANK(kpad->gpiomap[off]);
unsigned int bit = ADP5588_BIT(kpad->gpiomap[off]);
int ret;
mutex_lock(&kpad->gpio_lock);
kpad->dir[bank] &= ~bit;
ret = adp5588_write(kpad->client, GPIO_DIR1 + bank, kpad->dir[bank]);
mutex_unlock(&kpad->gpio_lock);
return ret;
}
static int adp5588_gpio_direction_output(struct gpio_chip *chip,
unsigned int off, int val)
{
struct adp5588_kpad *kpad = gpiochip_get_data(chip);
unsigned int bank = ADP5588_BANK(kpad->gpiomap[off]);
unsigned int bit = ADP5588_BIT(kpad->gpiomap[off]);
int ret;
mutex_lock(&kpad->gpio_lock);
kpad->dir[bank] |= bit;
if (val)
kpad->dat_out[bank] |= bit;
else
kpad->dat_out[bank] &= ~bit;
ret = adp5588_write(kpad->client, GPIO_DAT_OUT1 + bank,
kpad->dat_out[bank]);
if (ret)
goto out_unlock;
ret = adp5588_write(kpad->client, GPIO_DIR1 + bank, kpad->dir[bank]);
out_unlock:
mutex_unlock(&kpad->gpio_lock);
return ret;
}
static int adp5588_build_gpiomap(struct adp5588_kpad *kpad)
{
bool pin_used[ADP5588_MAXGPIO];
int n_unused = 0;
int i;
memset(pin_used, 0, sizeof(pin_used));
for (i = 0; i < kpad->rows; i++)
pin_used[i] = true;
for (i = 0; i < kpad->cols; i++)
pin_used[i + GPI_PIN_COL_BASE - GPI_PIN_BASE] = true;
for (i = 0; i < ADP5588_MAXGPIO; i++)
if (!pin_used[i])
kpad->gpiomap[n_unused++] = i;
return n_unused;
}
static void adp5588_irq_bus_lock(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct adp5588_kpad *kpad = gpiochip_get_data(gc);
mutex_lock(&kpad->gpio_lock);
}
static void adp5588_irq_bus_sync_unlock(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct adp5588_kpad *kpad = gpiochip_get_data(gc);
int i;
for (i = 0; i <= ADP5588_BANK(ADP5588_MAXGPIO); i++) {
if (kpad->int_en[i] ^ kpad->irq_mask[i]) {
kpad->int_en[i] = kpad->irq_mask[i];
adp5588_write(kpad->client, GPI_EM1 + i, kpad->int_en[i]);
}
}
mutex_unlock(&kpad->gpio_lock);
}
static void adp5588_irq_mask(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct adp5588_kpad *kpad = gpiochip_get_data(gc);
irq_hw_number_t hwirq = irqd_to_hwirq(d);
unsigned long real_irq = kpad->gpiomap[hwirq];
kpad->irq_mask[ADP5588_BANK(real_irq)] &= ~ADP5588_BIT(real_irq);
gpiochip_disable_irq(gc, hwirq);
}
static void adp5588_irq_unmask(struct irq_data *d)
{
struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
struct adp5588_kpad *kpad = gpiochip_get_data(gc);
irq_hw_number_t hwirq = irqd_to_hwirq(d);
unsigned long real_irq = kpad->gpiomap[hwirq];
gpiochip_enable_irq(gc, hwirq);
kpad->irq_mask[ADP5588_BANK(real_irq)] |= ADP5588_BIT(real_irq);
}
static int adp5588_irq_set_type(struct irq_data *d, unsigned int type)
{
if (!(type & IRQ_TYPE_EDGE_BOTH))
return -EINVAL;
irq_set_handler_locked(d, handle_edge_irq);
return 0;
}
static const struct irq_chip adp5588_irq_chip = {
.name = "adp5588",
.irq_mask = adp5588_irq_mask,
.irq_unmask = adp5588_irq_unmask,
.irq_bus_lock = adp5588_irq_bus_lock,
.irq_bus_sync_unlock = adp5588_irq_bus_sync_unlock,
.irq_set_type = adp5588_irq_set_type,
.flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_IMMUTABLE,
GPIOCHIP_IRQ_RESOURCE_HELPERS,
};
static int adp5588_gpio_add(struct adp5588_kpad *kpad)
{
struct device *dev = &kpad->client->dev;
struct gpio_irq_chip *girq;
int i, error;
kpad->gc.ngpio = adp5588_build_gpiomap(kpad);
if (kpad->gc.ngpio == 0) {
dev_info(dev, "No unused gpios left to export\n");
return 0;
}
kpad->gc.parent = &kpad->client->dev;
kpad->gc.direction_input = adp5588_gpio_direction_input;
kpad->gc.direction_output = adp5588_gpio_direction_output;
kpad->gc.get = adp5588_gpio_get_value;
kpad->gc.set = adp5588_gpio_set_value;
kpad->gc.set_config = adp5588_gpio_set_config;
kpad->gc.can_sleep = 1;
kpad->gc.base = -1;
kpad->gc.label = kpad->client->name;
kpad->gc.owner = THIS_MODULE;
girq = &kpad->gc.irq;
gpio_irq_chip_set_chip(girq, &adp5588_irq_chip);
girq->handler = handle_bad_irq;
girq->threaded = true;
mutex_init(&kpad->gpio_lock);
error = devm_gpiochip_add_data(dev, &kpad->gc, kpad);
if (error) {
dev_err(dev, "gpiochip_add failed: %d\n", error);
return error;
}
for (i = 0; i <= ADP5588_BANK(ADP5588_MAXGPIO); i++) {
kpad->dat_out[i] = adp5588_read(kpad->client,
GPIO_DAT_OUT1 + i);
kpad->dir[i] = adp5588_read(kpad->client, GPIO_DIR1 + i);
kpad->pull_dis[i] = adp5588_read(kpad->client, GPIO_PULL1 + i);
}
return 0;
}
static unsigned long adp5588_gpiomap_get_hwirq(struct device *dev,
const u8 *map, unsigned int gpio,
unsigned int ngpios)
{
unsigned int hwirq;
for (hwirq = 0; hwirq < ngpios; hwirq++)
if (map[hwirq] == gpio)
return hwirq;
/* should never happen */
dev_warn_ratelimited(dev, "could not find the hwirq for gpio(%u)\n", gpio);
return ADP5588_INVALID_HWIRQ;
}
static void adp5588_gpio_irq_handle(struct adp5588_kpad *kpad, int key_val,
int key_press)
{
unsigned int irq, gpio = key_val - GPI_PIN_BASE, irq_type;
struct i2c_client *client = kpad->client;
struct irq_data *irqd;
unsigned long hwirq;
hwirq = adp5588_gpiomap_get_hwirq(&client->dev, kpad->gpiomap,
gpio, kpad->gc.ngpio);
if (hwirq == ADP5588_INVALID_HWIRQ) {
dev_err(&client->dev, "Could not get hwirq for key(%u)\n", key_val);
return;
}
irq = irq_find_mapping(kpad->gc.irq.domain, hwirq);
if (!irq)
return;
irqd = irq_get_irq_data(irq);
if (!irqd) {
dev_err(&client->dev, "Could not get irq(%u) data\n", irq);
return;
}
irq_type = irqd_get_trigger_type(irqd);
/*
* Default is active low which means key_press is asserted on
* the falling edge.
*/
if ((irq_type & IRQ_TYPE_EDGE_RISING && !key_press) ||
(irq_type & IRQ_TYPE_EDGE_FALLING && key_press))
handle_nested_irq(irq);
}
static void adp5588_report_events(struct adp5588_kpad *kpad, int ev_cnt)
{
int i;
for (i = 0; i < ev_cnt; i++) {
int key = adp5588_read(kpad->client, KEY_EVENTA + i);
int key_val = key & KEY_EV_MASK;
int key_press = key & KEY_EV_PRESSED;
if (key_val >= GPI_PIN_BASE && key_val <= GPI_PIN_END) {
/* gpio line used as IRQ source */
adp5588_gpio_irq_handle(kpad, key_val, key_press);
} else {
int row = (key_val - 1) / ADP5588_COLS_MAX;
int col = (key_val - 1) % ADP5588_COLS_MAX;
int code = MATRIX_SCAN_CODE(row, col, kpad->row_shift);
dev_dbg_ratelimited(&kpad->client->dev,
"report key(%d) r(%d) c(%d) code(%d)\n",
key_val, row, col, kpad->keycode[code]);
input_report_key(kpad->input,
kpad->keycode[code], key_press);
}
}
}
static irqreturn_t adp5588_hard_irq(int irq, void *handle)
{
struct adp5588_kpad *kpad = handle;
kpad->irq_time = ktime_get();
return IRQ_WAKE_THREAD;
}
static irqreturn_t adp5588_thread_irq(int irq, void *handle)
{
struct adp5588_kpad *kpad = handle;
struct i2c_client *client = kpad->client;
ktime_t target_time, now;
unsigned long delay;
int status, ev_cnt;
/*
* Readout needs to wait for at least 25ms after the notification
* for REVID < 4.
*/
if (kpad->delay) {
target_time = ktime_add_ms(kpad->irq_time, kpad->delay);
now = ktime_get();
if (ktime_before(now, target_time)) {
delay = ktime_to_us(ktime_sub(target_time, now));
usleep_range(delay, delay + 1000);
}
}
status = adp5588_read(client, INT_STAT);
if (status & ADP5588_OVR_FLOW_INT) /* Unlikely and should never happen */
dev_err(&client->dev, "Event Overflow Error\n");
if (status & ADP5588_KE_INT) {
ev_cnt = adp5588_read(client, KEY_LCK_EC_STAT) & ADP5588_KEC;
if (ev_cnt) {
adp5588_report_events(kpad, ev_cnt);
input_sync(kpad->input);
}
}
adp5588_write(client, INT_STAT, status); /* Status is W1C */
return IRQ_HANDLED;
}
static int adp5588_setup(struct adp5588_kpad *kpad)
{
struct i2c_client *client = kpad->client;
int i, ret;
ret = adp5588_write(client, KP_GPIO1, KP_SEL(kpad->rows));
if (ret)
return ret;
ret = adp5588_write(client, KP_GPIO2, KP_SEL(kpad->cols) & 0xFF);
if (ret)
return ret;
ret = adp5588_write(client, KP_GPIO3, KP_SEL(kpad->cols) >> 8);
if (ret)
return ret;
for (i = 0; i < kpad->nkeys_unlock; i++) {
ret = adp5588_write(client, UNLOCK1 + i, kpad->unlock_keys[i]);
if (ret)
return ret;
}
if (kpad->nkeys_unlock) {
ret = adp5588_write(client, KEY_LCK_EC_STAT, ADP5588_K_LCK_EN);
if (ret)
return ret;
}
for (i = 0; i < KEYP_MAX_EVENT; i++) {
ret = adp5588_read(client, KEY_EVENTA);
if (ret)
return ret;
}
ret = adp5588_write(client, INT_STAT,
ADP5588_CMP2_INT | ADP5588_CMP1_INT |
ADP5588_OVR_FLOW_INT | ADP5588_K_LCK_INT |
ADP5588_GPI_INT | ADP5588_KE_INT); /* Status is W1C */
if (ret)
return ret;
return adp5588_write(client, CFG, ADP5588_INT_CFG |
ADP5588_OVR_FLOW_IEN | ADP5588_KE_IEN);
}
static int adp5588_fw_parse(struct adp5588_kpad *kpad)
{
struct i2c_client *client = kpad->client;
int ret, i;
ret = matrix_keypad_parse_properties(&client->dev, &kpad->rows,
&kpad->cols);
if (ret)
return ret;
if (kpad->rows > ADP5588_ROWS_MAX || kpad->cols > ADP5588_COLS_MAX) {
dev_err(&client->dev, "Invalid nr of rows(%u) or cols(%u)\n",
kpad->rows, kpad->cols);
return -EINVAL;
}
ret = matrix_keypad_build_keymap(NULL, NULL, kpad->rows, kpad->cols,
kpad->keycode, kpad->input);
if (ret)
return ret;
kpad->row_shift = get_count_order(kpad->cols);
if (device_property_read_bool(&client->dev, "autorepeat"))
__set_bit(EV_REP, kpad->input->evbit);
kpad->nkeys_unlock = device_property_count_u32(&client->dev,
"adi,unlock-keys");
if (kpad->nkeys_unlock <= 0) {
/* so that we don't end up enabling key lock */
kpad->nkeys_unlock = 0;
return 0;
}
if (kpad->nkeys_unlock > ARRAY_SIZE(kpad->unlock_keys)) {
dev_err(&client->dev, "number of unlock keys(%d) > (%zu)\n",
kpad->nkeys_unlock, ARRAY_SIZE(kpad->unlock_keys));
return -EINVAL;
}
ret = device_property_read_u32_array(&client->dev, "adi,unlock-keys",
kpad->unlock_keys,
kpad->nkeys_unlock);
if (ret)
return ret;
for (i = 0; i < kpad->nkeys_unlock; i++) {
/*
* Even though it should be possible (as stated in the datasheet)
* to use GPIs (which are part of the keys event) as unlock keys,
* it was not working at all and was leading to overflow events
* at some point. Hence, for now, let's just allow keys which are
* part of keypad matrix to be used and if a reliable way of
* using GPIs is found, this condition can be removed/lightened.
*/
if (kpad->unlock_keys[i] >= kpad->cols * kpad->rows) {
dev_err(&client->dev, "Invalid unlock key(%d)\n",
kpad->unlock_keys[i]);
return -EINVAL;
}
/*
* Firmware properties keys start from 0 but on the device they
* start from 1.
*/
kpad->unlock_keys[i] += 1;
}
return 0;
}
static int adp5588_probe(struct i2c_client *client)
{
struct adp5588_kpad *kpad;
struct input_dev *input;
struct gpio_desc *gpio;
unsigned int revid;
int ret;
int error;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev, "SMBUS Byte Data not Supported\n");
return -EIO;
}
kpad = devm_kzalloc(&client->dev, sizeof(*kpad), GFP_KERNEL);
if (!kpad)
return -ENOMEM;
input = devm_input_allocate_device(&client->dev);
if (!input)
return -ENOMEM;
kpad->client = client;
kpad->input = input;
error = adp5588_fw_parse(kpad);
if (error)
return error;
error = devm_regulator_get_enable(&client->dev, "vcc");
if (error)
return error;
gpio = devm_gpiod_get_optional(&client->dev, "reset", GPIOD_OUT_HIGH);
if (IS_ERR(gpio))
return PTR_ERR(gpio);
if (gpio) {
fsleep(30);
gpiod_set_value_cansleep(gpio, 0);
fsleep(60);
}
ret = adp5588_read(client, DEV_ID);
if (ret < 0)
return ret;
revid = ret & ADP5588_DEVICE_ID_MASK;
if (WA_DELAYED_READOUT_REVID(revid))
kpad->delay = msecs_to_jiffies(WA_DELAYED_READOUT_TIME);
input->name = client->name;
input->phys = "adp5588-keys/input0";
input_set_drvdata(input, kpad);
input->id.bustype = BUS_I2C;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = revid;
error = input_register_device(input);
if (error) {
dev_err(&client->dev, "unable to register input device: %d\n",
error);
return error;
}
error = adp5588_setup(kpad);
if (error)
return error;
error = adp5588_gpio_add(kpad);
if (error)
return error;
error = devm_request_threaded_irq(&client->dev, client->irq,
adp5588_hard_irq, adp5588_thread_irq,
IRQF_TRIGGER_FALLING | IRQF_ONESHOT,
client->dev.driver->name, kpad);
if (error) {
dev_err(&client->dev, "failed to request irq %d: %d\n",
client->irq, error);
return error;
}
dev_info(&client->dev, "Rev.%d keypad, irq %d\n", revid, client->irq);
return 0;
}
static void adp5588_remove(struct i2c_client *client)
{
adp5588_write(client, CFG, 0);
/* all resources will be freed by devm */
}
static int adp5588_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
disable_irq(client->irq);
return 0;
}
static int adp5588_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
enable_irq(client->irq);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(adp5588_dev_pm_ops, adp5588_suspend, adp5588_resume);
static const struct i2c_device_id adp5588_id[] = {
{ "adp5588-keys", 0 },
{ "adp5587-keys", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, adp5588_id);
static const struct of_device_id adp5588_of_match[] = {
{ .compatible = "adi,adp5588" },
{ .compatible = "adi,adp5587" },
{}
};
MODULE_DEVICE_TABLE(of, adp5588_of_match);
static struct i2c_driver adp5588_driver = {
.driver = {
.name = KBUILD_MODNAME,
.of_match_table = adp5588_of_match,
.pm = pm_sleep_ptr(&adp5588_dev_pm_ops),
},
.probe = adp5588_probe,
.remove = adp5588_remove,
.id_table = adp5588_id,
};
module_i2c_driver(adp5588_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Michael Hennerich <[email protected]>");
MODULE_DESCRIPTION("ADP5588/87 Keypad driver");
|
linux-master
|
drivers/input/keyboard/adp5588-keys.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Driver for keys on TCA6416 I2C IO expander
*
* Copyright (C) 2010 Texas Instruments
*
* Author : Sriramakrishnan.A.G. <[email protected]>
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/workqueue.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/tca6416_keypad.h>
#define TCA6416_INPUT 0
#define TCA6416_OUTPUT 1
#define TCA6416_INVERT 2
#define TCA6416_DIRECTION 3
#define TCA6416_POLL_INTERVAL 100 /* msec */
static const struct i2c_device_id tca6416_id[] = {
{ "tca6416-keys", 16, },
{ "tca6408-keys", 8, },
{ }
};
MODULE_DEVICE_TABLE(i2c, tca6416_id);
struct tca6416_drv_data {
struct input_dev *input;
struct tca6416_button data[];
};
struct tca6416_keypad_chip {
uint16_t reg_output;
uint16_t reg_direction;
uint16_t reg_input;
struct i2c_client *client;
struct input_dev *input;
int io_size;
int irqnum;
u16 pinmask;
bool use_polling;
struct tca6416_button buttons[];
};
static int tca6416_write_reg(struct tca6416_keypad_chip *chip, int reg, u16 val)
{
int error;
error = chip->io_size > 8 ?
i2c_smbus_write_word_data(chip->client, reg << 1, val) :
i2c_smbus_write_byte_data(chip->client, reg, val);
if (error < 0) {
dev_err(&chip->client->dev,
"%s failed, reg: %d, val: %d, error: %d\n",
__func__, reg, val, error);
return error;
}
return 0;
}
static int tca6416_read_reg(struct tca6416_keypad_chip *chip, int reg, u16 *val)
{
int retval;
retval = chip->io_size > 8 ?
i2c_smbus_read_word_data(chip->client, reg << 1) :
i2c_smbus_read_byte_data(chip->client, reg);
if (retval < 0) {
dev_err(&chip->client->dev, "%s failed, reg: %d, error: %d\n",
__func__, reg, retval);
return retval;
}
*val = (u16)retval;
return 0;
}
static void tca6416_keys_scan(struct input_dev *input)
{
struct tca6416_keypad_chip *chip = input_get_drvdata(input);
u16 reg_val, val;
int error, i, pin_index;
error = tca6416_read_reg(chip, TCA6416_INPUT, ®_val);
if (error)
return;
reg_val &= chip->pinmask;
/* Figure out which lines have changed */
val = reg_val ^ chip->reg_input;
chip->reg_input = reg_val;
for (i = 0, pin_index = 0; i < 16; i++) {
if (val & (1 << i)) {
struct tca6416_button *button = &chip->buttons[pin_index];
unsigned int type = button->type ?: EV_KEY;
int state = ((reg_val & (1 << i)) ? 1 : 0)
^ button->active_low;
input_event(input, type, button->code, !!state);
input_sync(input);
}
if (chip->pinmask & (1 << i))
pin_index++;
}
}
/*
* This is threaded IRQ handler and this can (and will) sleep.
*/
static irqreturn_t tca6416_keys_isr(int irq, void *dev_id)
{
tca6416_keys_scan(dev_id);
return IRQ_HANDLED;
}
static int tca6416_keys_open(struct input_dev *dev)
{
struct tca6416_keypad_chip *chip = input_get_drvdata(dev);
if (!chip->use_polling) {
/* Get initial device state in case it has switches */
tca6416_keys_scan(dev);
enable_irq(chip->client->irq);
}
return 0;
}
static void tca6416_keys_close(struct input_dev *dev)
{
struct tca6416_keypad_chip *chip = input_get_drvdata(dev);
if (!chip->use_polling)
disable_irq(chip->client->irq);
}
static int tca6416_setup_registers(struct tca6416_keypad_chip *chip)
{
int error;
error = tca6416_read_reg(chip, TCA6416_OUTPUT, &chip->reg_output);
if (error)
return error;
error = tca6416_read_reg(chip, TCA6416_DIRECTION, &chip->reg_direction);
if (error)
return error;
/* ensure that keypad pins are set to input */
error = tca6416_write_reg(chip, TCA6416_DIRECTION,
chip->reg_direction | chip->pinmask);
if (error)
return error;
error = tca6416_read_reg(chip, TCA6416_DIRECTION, &chip->reg_direction);
if (error)
return error;
error = tca6416_read_reg(chip, TCA6416_INPUT, &chip->reg_input);
if (error)
return error;
chip->reg_input &= chip->pinmask;
return 0;
}
static int tca6416_keypad_probe(struct i2c_client *client)
{
const struct i2c_device_id *id = i2c_client_get_device_id(client);
struct tca6416_keys_platform_data *pdata;
struct tca6416_keypad_chip *chip;
struct input_dev *input;
int error;
int i;
/* Check functionality */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE)) {
dev_err(&client->dev, "%s adapter not supported\n",
dev_driver_string(&client->adapter->dev));
return -ENODEV;
}
pdata = dev_get_platdata(&client->dev);
if (!pdata) {
dev_dbg(&client->dev, "no platform data\n");
return -EINVAL;
}
chip = devm_kzalloc(&client->dev,
struct_size(chip, buttons, pdata->nbuttons),
GFP_KERNEL);
if (!chip)
return -ENOMEM;
input = devm_input_allocate_device(&client->dev);
if (!input)
return -ENOMEM;
chip->client = client;
chip->input = input;
chip->io_size = id->driver_data;
chip->pinmask = pdata->pinmask;
chip->use_polling = pdata->use_polling;
input->phys = "tca6416-keys/input0";
input->name = client->name;
input->open = tca6416_keys_open;
input->close = tca6416_keys_close;
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
/* Enable auto repeat feature of Linux input subsystem */
if (pdata->rep)
__set_bit(EV_REP, input->evbit);
for (i = 0; i < pdata->nbuttons; i++) {
unsigned int type;
chip->buttons[i] = pdata->buttons[i];
type = (pdata->buttons[i].type) ?: EV_KEY;
input_set_capability(input, type, pdata->buttons[i].code);
}
input_set_drvdata(input, chip);
/*
* Initialize cached registers from their original values.
* we can't share this chip with another i2c master.
*/
error = tca6416_setup_registers(chip);
if (error)
return error;
if (chip->use_polling) {
error = input_setup_polling(input, tca6416_keys_scan);
if (error) {
dev_err(&client->dev, "Failed to setup polling\n");
return error;
}
input_set_poll_interval(input, TCA6416_POLL_INTERVAL);
} else {
error = devm_request_threaded_irq(&client->dev, client->irq,
NULL, tca6416_keys_isr,
IRQF_TRIGGER_FALLING |
IRQF_ONESHOT |
IRQF_NO_AUTOEN,
"tca6416-keypad", input);
if (error) {
dev_dbg(&client->dev,
"Unable to claim irq %d; error %d\n",
client->irq, error);
return error;
}
}
error = input_register_device(input);
if (error) {
dev_dbg(&client->dev,
"Unable to register input device, error: %d\n", error);
return error;
}
i2c_set_clientdata(client, chip);
return 0;
}
static struct i2c_driver tca6416_keypad_driver = {
.driver = {
.name = "tca6416-keypad",
},
.probe = tca6416_keypad_probe,
.id_table = tca6416_id,
};
static int __init tca6416_keypad_init(void)
{
return i2c_add_driver(&tca6416_keypad_driver);
}
subsys_initcall(tca6416_keypad_init);
static void __exit tca6416_keypad_exit(void)
{
i2c_del_driver(&tca6416_keypad_driver);
}
module_exit(tca6416_keypad_exit);
MODULE_AUTHOR("Sriramakrishnan <[email protected]>");
MODULE_DESCRIPTION("Keypad driver over tca6416 IO expander");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/tca6416-keypad.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* linux/drivers/hil/hilkbd.c
*
* Copyright (C) 1998 Philip Blundell <[email protected]>
* Copyright (C) 1999 Matthew Wilcox <[email protected]>
* Copyright (C) 1999-2007 Helge Deller <[email protected]>
*
* Very basic HP Human Interface Loop (HIL) driver.
* This driver handles the keyboard on HP300 (m68k) and on some
* HP700 (parisc) series machines.
*/
#include <linux/pci_ids.h>
#include <linux/ioport.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/input.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/hil.h>
#include <linux/io.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <asm/irq.h>
#ifdef CONFIG_HP300
#include <asm/hwtest.h>
#endif
MODULE_AUTHOR("Philip Blundell, Matthew Wilcox, Helge Deller");
MODULE_DESCRIPTION("HIL keyboard driver (basic functionality)");
MODULE_LICENSE("GPL v2");
#if defined(CONFIG_PARISC)
#include <asm/io.h>
#include <asm/hardware.h>
#include <asm/parisc-device.h>
static unsigned long hil_base; /* HPA for the HIL device */
static unsigned int hil_irq;
#define HILBASE hil_base /* HPPA (parisc) port address */
#define HIL_DATA 0x800
#define HIL_CMD 0x801
#define HIL_IRQ hil_irq
#define hil_readb(p) gsc_readb(p)
#define hil_writeb(v,p) gsc_writeb((v),(p))
#elif defined(CONFIG_HP300)
#define HILBASE 0xf0428000UL /* HP300 (m68k) port address */
#define HIL_DATA 0x1
#define HIL_CMD 0x3
#define HIL_IRQ 2
#define hil_readb(p) readb((const volatile void __iomem *)(p))
#define hil_writeb(v, p) writeb((v), (volatile void __iomem *)(p))
#else
#error "HIL is not supported on this platform"
#endif
/* HIL helper functions */
#define hil_busy() (hil_readb(HILBASE + HIL_CMD) & HIL_BUSY)
#define hil_data_available() (hil_readb(HILBASE + HIL_CMD) & HIL_DATA_RDY)
#define hil_status() (hil_readb(HILBASE + HIL_CMD))
#define hil_command(x) do { hil_writeb((x), HILBASE + HIL_CMD); } while (0)
#define hil_read_data() (hil_readb(HILBASE + HIL_DATA))
#define hil_write_data(x) do { hil_writeb((x), HILBASE + HIL_DATA); } while (0)
/* HIL constants */
#define HIL_BUSY 0x02
#define HIL_DATA_RDY 0x01
#define HIL_SETARD 0xA0 /* set auto-repeat delay */
#define HIL_SETARR 0xA2 /* set auto-repeat rate */
#define HIL_SETTONE 0xA3 /* set tone generator */
#define HIL_CNMT 0xB2 /* clear nmi */
#define HIL_INTON 0x5C /* Turn on interrupts. */
#define HIL_INTOFF 0x5D /* Turn off interrupts. */
#define HIL_READKBDSADR 0xF9
#define HIL_WRITEKBDSADR 0xE9
static unsigned int hphilkeyb_keycode[HIL_KEYCODES_SET1_TBLSIZE] __read_mostly =
{ HIL_KEYCODES_SET1 };
/* HIL structure */
static struct {
struct input_dev *dev;
unsigned int curdev;
unsigned char s;
unsigned char c;
int valid;
unsigned char data[16];
unsigned int ptr;
spinlock_t lock;
void *dev_id; /* native bus device */
} hil_dev;
static void poll_finished(void)
{
int down;
int key;
unsigned char scode;
switch (hil_dev.data[0]) {
case 0x40:
down = (hil_dev.data[1] & 1) == 0;
scode = hil_dev.data[1] >> 1;
key = hphilkeyb_keycode[scode];
input_report_key(hil_dev.dev, key, down);
break;
}
hil_dev.curdev = 0;
}
static inline void handle_status(unsigned char s, unsigned char c)
{
if (c & 0x8) {
/* End of block */
if (c & 0x10)
poll_finished();
} else {
if (c & 0x10) {
if (hil_dev.curdev)
poll_finished(); /* just in case */
hil_dev.curdev = c & 7;
hil_dev.ptr = 0;
}
}
}
static inline void handle_data(unsigned char s, unsigned char c)
{
if (hil_dev.curdev) {
hil_dev.data[hil_dev.ptr++] = c;
hil_dev.ptr &= 15;
}
}
/* handle HIL interrupts */
static irqreturn_t hil_interrupt(int irq, void *handle)
{
unsigned char s, c;
s = hil_status();
c = hil_read_data();
switch (s >> 4) {
case 0x5:
handle_status(s, c);
break;
case 0x6:
handle_data(s, c);
break;
case 0x4:
hil_dev.s = s;
hil_dev.c = c;
mb();
hil_dev.valid = 1;
break;
}
return IRQ_HANDLED;
}
/* send a command to the HIL */
static void hil_do(unsigned char cmd, unsigned char *data, unsigned int len)
{
unsigned long flags;
spin_lock_irqsave(&hil_dev.lock, flags);
while (hil_busy())
/* wait */;
hil_command(cmd);
while (len--) {
while (hil_busy())
/* wait */;
hil_write_data(*(data++));
}
spin_unlock_irqrestore(&hil_dev.lock, flags);
}
/* initialize HIL */
static int hil_keyb_init(void)
{
unsigned char c;
unsigned int i, kbid;
wait_queue_head_t hil_wait;
int err;
if (hil_dev.dev)
return -ENODEV; /* already initialized */
init_waitqueue_head(&hil_wait);
spin_lock_init(&hil_dev.lock);
hil_dev.dev = input_allocate_device();
if (!hil_dev.dev)
return -ENOMEM;
err = request_irq(HIL_IRQ, hil_interrupt, 0, "hil", hil_dev.dev_id);
if (err) {
printk(KERN_ERR "HIL: Can't get IRQ\n");
goto err1;
}
/* Turn on interrupts */
hil_do(HIL_INTON, NULL, 0);
/* Look for keyboards */
hil_dev.valid = 0; /* clear any pending data */
hil_do(HIL_READKBDSADR, NULL, 0);
wait_event_interruptible_timeout(hil_wait, hil_dev.valid, 3 * HZ);
if (!hil_dev.valid)
printk(KERN_WARNING "HIL: timed out, assuming no keyboard present\n");
c = hil_dev.c;
hil_dev.valid = 0;
if (c == 0) {
kbid = -1;
printk(KERN_WARNING "HIL: no keyboard present\n");
} else {
kbid = ffz(~c);
printk(KERN_INFO "HIL: keyboard found at id %d\n", kbid);
}
/* set it to raw mode */
c = 0;
hil_do(HIL_WRITEKBDSADR, &c, 1);
for (i = 0; i < HIL_KEYCODES_SET1_TBLSIZE; i++)
if (hphilkeyb_keycode[i] != KEY_RESERVED)
__set_bit(hphilkeyb_keycode[i], hil_dev.dev->keybit);
hil_dev.dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
hil_dev.dev->ledbit[0] = BIT_MASK(LED_NUML) | BIT_MASK(LED_CAPSL) |
BIT_MASK(LED_SCROLLL);
hil_dev.dev->keycodemax = HIL_KEYCODES_SET1_TBLSIZE;
hil_dev.dev->keycodesize= sizeof(hphilkeyb_keycode[0]);
hil_dev.dev->keycode = hphilkeyb_keycode;
hil_dev.dev->name = "HIL keyboard";
hil_dev.dev->phys = "hpkbd/input0";
hil_dev.dev->id.bustype = BUS_HIL;
hil_dev.dev->id.vendor = PCI_VENDOR_ID_HP;
hil_dev.dev->id.product = 0x0001;
hil_dev.dev->id.version = 0x0010;
err = input_register_device(hil_dev.dev);
if (err) {
printk(KERN_ERR "HIL: Can't register device\n");
goto err2;
}
printk(KERN_INFO "input: %s, ID %d at 0x%08lx (irq %d) found and attached\n",
hil_dev.dev->name, kbid, HILBASE, HIL_IRQ);
return 0;
err2:
hil_do(HIL_INTOFF, NULL, 0);
free_irq(HIL_IRQ, hil_dev.dev_id);
err1:
input_free_device(hil_dev.dev);
hil_dev.dev = NULL;
return err;
}
static void hil_keyb_exit(void)
{
if (HIL_IRQ)
free_irq(HIL_IRQ, hil_dev.dev_id);
/* Turn off interrupts */
hil_do(HIL_INTOFF, NULL, 0);
input_unregister_device(hil_dev.dev);
hil_dev.dev = NULL;
}
#if defined(CONFIG_PARISC)
static int __init hil_probe_chip(struct parisc_device *dev)
{
/* Only allow one HIL keyboard */
if (hil_dev.dev)
return -ENODEV;
if (!dev->irq) {
printk(KERN_WARNING "HIL: IRQ not found for HIL bus at 0x%p\n",
(void *)dev->hpa.start);
return -ENODEV;
}
hil_base = dev->hpa.start;
hil_irq = dev->irq;
hil_dev.dev_id = dev;
printk(KERN_INFO "Found HIL bus at 0x%08lx, IRQ %d\n", hil_base, hil_irq);
return hil_keyb_init();
}
static void __exit hil_remove_chip(struct parisc_device *dev)
{
hil_keyb_exit();
}
static const struct parisc_device_id hil_tbl[] __initconst = {
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x00073 },
{ 0, }
};
#if 0
/* Disabled to avoid conflicts with the HP SDC HIL drivers */
MODULE_DEVICE_TABLE(parisc, hil_tbl);
#endif
static struct parisc_driver hil_driver __refdata = {
.name = "hil",
.id_table = hil_tbl,
.probe = hil_probe_chip,
.remove = __exit_p(hil_remove_chip),
};
static int __init hil_init(void)
{
return register_parisc_driver(&hil_driver);
}
static void __exit hil_exit(void)
{
unregister_parisc_driver(&hil_driver);
}
#else /* !CONFIG_PARISC */
static int __init hil_init(void)
{
int error;
/* Only allow one HIL keyboard */
if (hil_dev.dev)
return -EBUSY;
if (!MACH_IS_HP300)
return -ENODEV;
if (!hwreg_present((void *)(HILBASE + HIL_DATA))) {
printk(KERN_ERR "HIL: hardware register was not found\n");
return -ENODEV;
}
if (!request_region(HILBASE + HIL_DATA, 2, "hil")) {
printk(KERN_ERR "HIL: IOPORT region already used\n");
return -EIO;
}
error = hil_keyb_init();
if (error) {
release_region(HILBASE + HIL_DATA, 2);
return error;
}
return 0;
}
static void __exit hil_exit(void)
{
hil_keyb_exit();
release_region(HILBASE + HIL_DATA, 2);
}
#endif /* CONFIG_PARISC */
module_init(hil_init);
module_exit(hil_exit);
|
linux-master
|
drivers/input/keyboard/hilkbd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Touchkey driver for Freescale MPR121 Controllor
*
* Copyright (C) 2011 Freescale Semiconductor, Inc.
* Author: Zhang Jiejing <[email protected]>
*
* Based on mcs_touchkey.c
*/
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/property.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
/* Register definitions */
#define ELE_TOUCH_STATUS_0_ADDR 0x0
#define ELE_TOUCH_STATUS_1_ADDR 0X1
#define MHD_RISING_ADDR 0x2b
#define NHD_RISING_ADDR 0x2c
#define NCL_RISING_ADDR 0x2d
#define FDL_RISING_ADDR 0x2e
#define MHD_FALLING_ADDR 0x2f
#define NHD_FALLING_ADDR 0x30
#define NCL_FALLING_ADDR 0x31
#define FDL_FALLING_ADDR 0x32
#define ELE0_TOUCH_THRESHOLD_ADDR 0x41
#define ELE0_RELEASE_THRESHOLD_ADDR 0x42
#define AFE_CONF_ADDR 0x5c
#define FILTER_CONF_ADDR 0x5d
/*
* ELECTRODE_CONF_ADDR: This register configures the number of
* enabled capacitance sensing inputs and its run/suspend mode.
*/
#define ELECTRODE_CONF_ADDR 0x5e
#define ELECTRODE_CONF_QUICK_CHARGE 0x80
#define AUTO_CONFIG_CTRL_ADDR 0x7b
#define AUTO_CONFIG_USL_ADDR 0x7d
#define AUTO_CONFIG_LSL_ADDR 0x7e
#define AUTO_CONFIG_TL_ADDR 0x7f
/* Threshold of touch/release trigger */
#define TOUCH_THRESHOLD 0x08
#define RELEASE_THRESHOLD 0x05
/* Masks for touch and release triggers */
#define TOUCH_STATUS_MASK 0xfff
/* MPR121 has 12 keys */
#define MPR121_MAX_KEY_COUNT 12
#define MPR121_MIN_POLL_INTERVAL 10
#define MPR121_MAX_POLL_INTERVAL 200
struct mpr121_touchkey {
struct i2c_client *client;
struct input_dev *input_dev;
unsigned int statusbits;
unsigned int keycount;
u32 keycodes[MPR121_MAX_KEY_COUNT];
};
struct mpr121_init_register {
int addr;
u8 val;
};
static const struct mpr121_init_register init_reg_table[] = {
{ MHD_RISING_ADDR, 0x1 },
{ NHD_RISING_ADDR, 0x1 },
{ MHD_FALLING_ADDR, 0x1 },
{ NHD_FALLING_ADDR, 0x1 },
{ NCL_FALLING_ADDR, 0xff },
{ FDL_FALLING_ADDR, 0x02 },
{ FILTER_CONF_ADDR, 0x04 },
{ AFE_CONF_ADDR, 0x0b },
{ AUTO_CONFIG_CTRL_ADDR, 0x0b },
};
static void mpr121_vdd_supply_disable(void *data)
{
struct regulator *vdd_supply = data;
regulator_disable(vdd_supply);
}
static struct regulator *mpr121_vdd_supply_init(struct device *dev)
{
struct regulator *vdd_supply;
int err;
vdd_supply = devm_regulator_get(dev, "vdd");
if (IS_ERR(vdd_supply)) {
dev_err(dev, "failed to get vdd regulator: %ld\n",
PTR_ERR(vdd_supply));
return vdd_supply;
}
err = regulator_enable(vdd_supply);
if (err) {
dev_err(dev, "failed to enable vdd regulator: %d\n", err);
return ERR_PTR(err);
}
err = devm_add_action_or_reset(dev, mpr121_vdd_supply_disable,
vdd_supply);
if (err) {
dev_err(dev, "failed to add disable regulator action: %d\n",
err);
return ERR_PTR(err);
}
return vdd_supply;
}
static void mpr_touchkey_report(struct input_dev *dev)
{
struct mpr121_touchkey *mpr121 = input_get_drvdata(dev);
struct input_dev *input = mpr121->input_dev;
struct i2c_client *client = mpr121->client;
unsigned long bit_changed;
unsigned int key_num;
int reg;
reg = i2c_smbus_read_byte_data(client, ELE_TOUCH_STATUS_1_ADDR);
if (reg < 0) {
dev_err(&client->dev, "i2c read error [%d]\n", reg);
return;
}
reg <<= 8;
reg |= i2c_smbus_read_byte_data(client, ELE_TOUCH_STATUS_0_ADDR);
if (reg < 0) {
dev_err(&client->dev, "i2c read error [%d]\n", reg);
return;
}
reg &= TOUCH_STATUS_MASK;
/* use old press bit to figure out which bit changed */
bit_changed = reg ^ mpr121->statusbits;
mpr121->statusbits = reg;
for_each_set_bit(key_num, &bit_changed, mpr121->keycount) {
unsigned int key_val, pressed;
pressed = reg & BIT(key_num);
key_val = mpr121->keycodes[key_num];
input_event(input, EV_MSC, MSC_SCAN, key_num);
input_report_key(input, key_val, pressed);
dev_dbg(&client->dev, "key %d %d %s\n", key_num, key_val,
pressed ? "pressed" : "released");
}
input_sync(input);
}
static irqreturn_t mpr_touchkey_interrupt(int irq, void *dev_id)
{
struct mpr121_touchkey *mpr121 = dev_id;
mpr_touchkey_report(mpr121->input_dev);
return IRQ_HANDLED;
}
static int mpr121_phys_init(struct mpr121_touchkey *mpr121,
struct i2c_client *client, int vdd_uv)
{
const struct mpr121_init_register *reg;
unsigned char usl, lsl, tl, eleconf;
int i, t, vdd, ret;
/* Set up touch/release threshold for ele0-ele11 */
for (i = 0; i <= MPR121_MAX_KEY_COUNT; i++) {
t = ELE0_TOUCH_THRESHOLD_ADDR + (i * 2);
ret = i2c_smbus_write_byte_data(client, t, TOUCH_THRESHOLD);
if (ret < 0)
goto err_i2c_write;
ret = i2c_smbus_write_byte_data(client, t + 1,
RELEASE_THRESHOLD);
if (ret < 0)
goto err_i2c_write;
}
/* Set up init register */
for (i = 0; i < ARRAY_SIZE(init_reg_table); i++) {
reg = &init_reg_table[i];
ret = i2c_smbus_write_byte_data(client, reg->addr, reg->val);
if (ret < 0)
goto err_i2c_write;
}
/*
* Capacitance on sensing input varies and needs to be compensated.
* The internal MPR121-auto-configuration can do this if it's
* registers are set properly (based on vdd_uv).
*/
vdd = vdd_uv / 1000;
usl = ((vdd - 700) * 256) / vdd;
lsl = (usl * 65) / 100;
tl = (usl * 90) / 100;
ret = i2c_smbus_write_byte_data(client, AUTO_CONFIG_USL_ADDR, usl);
ret |= i2c_smbus_write_byte_data(client, AUTO_CONFIG_LSL_ADDR, lsl);
ret |= i2c_smbus_write_byte_data(client, AUTO_CONFIG_TL_ADDR, tl);
/*
* Quick charge bit will let the capacitive charge to ready
* state quickly, or the buttons may not function after system
* boot.
*/
eleconf = mpr121->keycount | ELECTRODE_CONF_QUICK_CHARGE;
ret |= i2c_smbus_write_byte_data(client, ELECTRODE_CONF_ADDR,
eleconf);
if (ret != 0)
goto err_i2c_write;
dev_dbg(&client->dev, "set up with %x keys.\n", mpr121->keycount);
return 0;
err_i2c_write:
dev_err(&client->dev, "i2c write error: %d\n", ret);
return ret;
}
static int mpr_touchkey_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
struct regulator *vdd_supply;
int vdd_uv;
struct mpr121_touchkey *mpr121;
struct input_dev *input_dev;
u32 poll_interval = 0;
int error;
int i;
vdd_supply = mpr121_vdd_supply_init(dev);
if (IS_ERR(vdd_supply))
return PTR_ERR(vdd_supply);
vdd_uv = regulator_get_voltage(vdd_supply);
mpr121 = devm_kzalloc(dev, sizeof(*mpr121), GFP_KERNEL);
if (!mpr121)
return -ENOMEM;
input_dev = devm_input_allocate_device(dev);
if (!input_dev)
return -ENOMEM;
mpr121->client = client;
mpr121->input_dev = input_dev;
mpr121->keycount = device_property_count_u32(dev, "linux,keycodes");
if (mpr121->keycount > MPR121_MAX_KEY_COUNT) {
dev_err(dev, "too many keys defined (%d)\n", mpr121->keycount);
return -EINVAL;
}
error = device_property_read_u32_array(dev, "linux,keycodes",
mpr121->keycodes,
mpr121->keycount);
if (error) {
dev_err(dev,
"failed to read linux,keycode property: %d\n", error);
return error;
}
input_dev->name = "Freescale MPR121 Touchkey";
input_dev->id.bustype = BUS_I2C;
input_dev->dev.parent = dev;
if (device_property_read_bool(dev, "autorepeat"))
__set_bit(EV_REP, input_dev->evbit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
input_set_drvdata(input_dev, mpr121);
input_dev->keycode = mpr121->keycodes;
input_dev->keycodesize = sizeof(mpr121->keycodes[0]);
input_dev->keycodemax = mpr121->keycount;
for (i = 0; i < mpr121->keycount; i++)
input_set_capability(input_dev, EV_KEY, mpr121->keycodes[i]);
error = mpr121_phys_init(mpr121, client, vdd_uv);
if (error) {
dev_err(dev, "Failed to init register\n");
return error;
}
device_property_read_u32(dev, "poll-interval", &poll_interval);
if (client->irq) {
error = devm_request_threaded_irq(dev, client->irq, NULL,
mpr_touchkey_interrupt,
IRQF_TRIGGER_FALLING |
IRQF_ONESHOT,
dev->driver->name, mpr121);
if (error) {
dev_err(dev, "Failed to register interrupt\n");
return error;
}
} else if (poll_interval) {
if (poll_interval < MPR121_MIN_POLL_INTERVAL)
return -EINVAL;
if (poll_interval > MPR121_MAX_POLL_INTERVAL)
return -EINVAL;
error = input_setup_polling(input_dev, mpr_touchkey_report);
if (error) {
dev_err(dev, "Failed to setup polling\n");
return error;
}
input_set_poll_interval(input_dev, poll_interval);
input_set_min_poll_interval(input_dev,
MPR121_MIN_POLL_INTERVAL);
input_set_max_poll_interval(input_dev,
MPR121_MAX_POLL_INTERVAL);
} else {
dev_err(dev,
"invalid IRQ number and polling not configured\n");
return -EINVAL;
}
error = input_register_device(input_dev);
if (error)
return error;
i2c_set_clientdata(client, mpr121);
device_init_wakeup(dev,
device_property_read_bool(dev, "wakeup-source"));
return 0;
}
static int mpr_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
if (device_may_wakeup(&client->dev))
enable_irq_wake(client->irq);
i2c_smbus_write_byte_data(client, ELECTRODE_CONF_ADDR, 0x00);
return 0;
}
static int mpr_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct mpr121_touchkey *mpr121 = i2c_get_clientdata(client);
if (device_may_wakeup(&client->dev))
disable_irq_wake(client->irq);
i2c_smbus_write_byte_data(client, ELECTRODE_CONF_ADDR,
mpr121->keycount);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(mpr121_touchkey_pm_ops, mpr_suspend, mpr_resume);
static const struct i2c_device_id mpr121_id[] = {
{ "mpr121_touchkey", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, mpr121_id);
#ifdef CONFIG_OF
static const struct of_device_id mpr121_touchkey_dt_match_table[] = {
{ .compatible = "fsl,mpr121-touchkey" },
{ },
};
MODULE_DEVICE_TABLE(of, mpr121_touchkey_dt_match_table);
#endif
static struct i2c_driver mpr_touchkey_driver = {
.driver = {
.name = "mpr121",
.pm = pm_sleep_ptr(&mpr121_touchkey_pm_ops),
.of_match_table = of_match_ptr(mpr121_touchkey_dt_match_table),
},
.id_table = mpr121_id,
.probe = mpr_touchkey_probe,
};
module_i2c_driver(mpr_touchkey_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Zhang Jiejing <[email protected]>");
MODULE_DESCRIPTION("Touch Key driver for Freescale MPR121 Chip");
|
linux-master
|
drivers/input/keyboard/mpr121_touchkey.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 2000 Justin Cormack
*/
/*
* Newton keyboard driver for Linux
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "Newton keyboard driver"
MODULE_AUTHOR("Justin Cormack <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define NKBD_KEY 0x7f
#define NKBD_PRESS 0x80
static unsigned char nkbd_keycode[128] = {
KEY_A, KEY_S, KEY_D, KEY_F, KEY_H, KEY_G, KEY_Z, KEY_X,
KEY_C, KEY_V, 0, KEY_B, KEY_Q, KEY_W, KEY_E, KEY_R,
KEY_Y, KEY_T, KEY_1, KEY_2, KEY_3, KEY_4, KEY_6, KEY_5,
KEY_EQUAL, KEY_9, KEY_7, KEY_MINUS, KEY_8, KEY_0, KEY_RIGHTBRACE, KEY_O,
KEY_U, KEY_LEFTBRACE, KEY_I, KEY_P, KEY_ENTER, KEY_L, KEY_J, KEY_APOSTROPHE,
KEY_K, KEY_SEMICOLON, KEY_BACKSLASH, KEY_COMMA, KEY_SLASH, KEY_N, KEY_M, KEY_DOT,
KEY_TAB, KEY_SPACE, KEY_GRAVE, KEY_DELETE, 0, 0, 0, KEY_LEFTMETA,
KEY_LEFTSHIFT, KEY_CAPSLOCK, KEY_LEFTALT, KEY_LEFTCTRL, KEY_RIGHTSHIFT, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
KEY_LEFT, KEY_RIGHT, KEY_DOWN, KEY_UP, 0
};
struct nkbd {
unsigned char keycode[128];
struct input_dev *dev;
struct serio *serio;
char phys[32];
};
static irqreturn_t nkbd_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct nkbd *nkbd = serio_get_drvdata(serio);
/* invalid scan codes are probably the init sequence, so we ignore them */
if (nkbd->keycode[data & NKBD_KEY]) {
input_report_key(nkbd->dev, nkbd->keycode[data & NKBD_KEY], data & NKBD_PRESS);
input_sync(nkbd->dev);
}
else if (data == 0xe7) /* end of init sequence */
printk(KERN_INFO "input: %s on %s\n", nkbd->dev->name, serio->phys);
return IRQ_HANDLED;
}
static int nkbd_connect(struct serio *serio, struct serio_driver *drv)
{
struct nkbd *nkbd;
struct input_dev *input_dev;
int err = -ENOMEM;
int i;
nkbd = kzalloc(sizeof(struct nkbd), GFP_KERNEL);
input_dev = input_allocate_device();
if (!nkbd || !input_dev)
goto fail1;
nkbd->serio = serio;
nkbd->dev = input_dev;
snprintf(nkbd->phys, sizeof(nkbd->phys), "%s/input0", serio->phys);
memcpy(nkbd->keycode, nkbd_keycode, sizeof(nkbd->keycode));
input_dev->name = "Newton Keyboard";
input_dev->phys = nkbd->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_NEWTON;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
input_dev->keycode = nkbd->keycode;
input_dev->keycodesize = sizeof(unsigned char);
input_dev->keycodemax = ARRAY_SIZE(nkbd_keycode);
for (i = 0; i < 128; i++)
set_bit(nkbd->keycode[i], input_dev->keybit);
clear_bit(0, input_dev->keybit);
serio_set_drvdata(serio, nkbd);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(nkbd->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(nkbd);
return err;
}
static void nkbd_disconnect(struct serio *serio)
{
struct nkbd *nkbd = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(nkbd->dev);
kfree(nkbd);
}
static const struct serio_device_id nkbd_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_NEWTON,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, nkbd_serio_ids);
static struct serio_driver nkbd_drv = {
.driver = {
.name = "newtonkbd",
},
.description = DRIVER_DESC,
.id_table = nkbd_serio_ids,
.interrupt = nkbd_interrupt,
.connect = nkbd_connect,
.disconnect = nkbd_disconnect,
};
module_serio_driver(nkbd_drv);
|
linux-master
|
drivers/input/keyboard/newtonkbd.c
|
// SPDX-License-Identifier: GPL-2.0
//
// Driver for the IMX keypad port.
// Copyright (C) 2009 Alberto Panizzo <[email protected]>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/timer.h>
/*
* Keypad Controller registers (halfword)
*/
#define KPCR 0x00 /* Keypad Control Register */
#define KPSR 0x02 /* Keypad Status Register */
#define KBD_STAT_KPKD (0x1 << 0) /* Key Press Interrupt Status bit (w1c) */
#define KBD_STAT_KPKR (0x1 << 1) /* Key Release Interrupt Status bit (w1c) */
#define KBD_STAT_KDSC (0x1 << 2) /* Key Depress Synch Chain Status bit (w1c)*/
#define KBD_STAT_KRSS (0x1 << 3) /* Key Release Synch Status bit (w1c)*/
#define KBD_STAT_KDIE (0x1 << 8) /* Key Depress Interrupt Enable Status bit */
#define KBD_STAT_KRIE (0x1 << 9) /* Key Release Interrupt Enable */
#define KBD_STAT_KPPEN (0x1 << 10) /* Keypad Clock Enable */
#define KDDR 0x04 /* Keypad Data Direction Register */
#define KPDR 0x06 /* Keypad Data Register */
#define MAX_MATRIX_KEY_ROWS 8
#define MAX_MATRIX_KEY_COLS 8
#define MATRIX_ROW_SHIFT 3
#define MAX_MATRIX_KEY_NUM (MAX_MATRIX_KEY_ROWS * MAX_MATRIX_KEY_COLS)
struct imx_keypad {
struct clk *clk;
struct input_dev *input_dev;
void __iomem *mmio_base;
int irq;
struct timer_list check_matrix_timer;
/*
* The matrix is stable only if no changes are detected after
* IMX_KEYPAD_SCANS_FOR_STABILITY scans
*/
#define IMX_KEYPAD_SCANS_FOR_STABILITY 3
int stable_count;
bool enabled;
/* Masks for enabled rows/cols */
unsigned short rows_en_mask;
unsigned short cols_en_mask;
unsigned short keycodes[MAX_MATRIX_KEY_NUM];
/*
* Matrix states:
* -stable: achieved after a complete debounce process.
* -unstable: used in the debouncing process.
*/
unsigned short matrix_stable_state[MAX_MATRIX_KEY_COLS];
unsigned short matrix_unstable_state[MAX_MATRIX_KEY_COLS];
};
/* Scan the matrix and return the new state in *matrix_volatile_state. */
static void imx_keypad_scan_matrix(struct imx_keypad *keypad,
unsigned short *matrix_volatile_state)
{
int col;
unsigned short reg_val;
for (col = 0; col < MAX_MATRIX_KEY_COLS; col++) {
if ((keypad->cols_en_mask & (1 << col)) == 0)
continue;
/*
* Discharge keypad capacitance:
* 2. write 1s on column data.
* 3. configure columns as totem-pole to discharge capacitance.
* 4. configure columns as open-drain.
*/
reg_val = readw(keypad->mmio_base + KPDR);
reg_val |= 0xff00;
writew(reg_val, keypad->mmio_base + KPDR);
reg_val = readw(keypad->mmio_base + KPCR);
reg_val &= ~((keypad->cols_en_mask & 0xff) << 8);
writew(reg_val, keypad->mmio_base + KPCR);
udelay(2);
reg_val = readw(keypad->mmio_base + KPCR);
reg_val |= (keypad->cols_en_mask & 0xff) << 8;
writew(reg_val, keypad->mmio_base + KPCR);
/*
* 5. Write a single column to 0, others to 1.
* 6. Sample row inputs and save data.
* 7. Repeat steps 2 - 6 for remaining columns.
*/
reg_val = readw(keypad->mmio_base + KPDR);
reg_val &= ~(1 << (8 + col));
writew(reg_val, keypad->mmio_base + KPDR);
/*
* Delay added to avoid propagating the 0 from column to row
* when scanning.
*/
udelay(5);
/*
* 1s in matrix_volatile_state[col] means key pressures
* throw data from non enabled rows.
*/
reg_val = readw(keypad->mmio_base + KPDR);
matrix_volatile_state[col] = (~reg_val) & keypad->rows_en_mask;
}
/*
* Return in standby mode:
* 9. write 0s to columns
*/
reg_val = readw(keypad->mmio_base + KPDR);
reg_val &= 0x00ff;
writew(reg_val, keypad->mmio_base + KPDR);
}
/*
* Compare the new matrix state (volatile) with the stable one stored in
* keypad->matrix_stable_state and fire events if changes are detected.
*/
static void imx_keypad_fire_events(struct imx_keypad *keypad,
unsigned short *matrix_volatile_state)
{
struct input_dev *input_dev = keypad->input_dev;
int row, col;
for (col = 0; col < MAX_MATRIX_KEY_COLS; col++) {
unsigned short bits_changed;
int code;
if ((keypad->cols_en_mask & (1 << col)) == 0)
continue; /* Column is not enabled */
bits_changed = keypad->matrix_stable_state[col] ^
matrix_volatile_state[col];
if (bits_changed == 0)
continue; /* Column does not contain changes */
for (row = 0; row < MAX_MATRIX_KEY_ROWS; row++) {
if ((keypad->rows_en_mask & (1 << row)) == 0)
continue; /* Row is not enabled */
if ((bits_changed & (1 << row)) == 0)
continue; /* Row does not contain changes */
code = MATRIX_SCAN_CODE(row, col, MATRIX_ROW_SHIFT);
input_event(input_dev, EV_MSC, MSC_SCAN, code);
input_report_key(input_dev, keypad->keycodes[code],
matrix_volatile_state[col] & (1 << row));
dev_dbg(&input_dev->dev, "Event code: %d, val: %d",
keypad->keycodes[code],
matrix_volatile_state[col] & (1 << row));
}
}
input_sync(input_dev);
}
/*
* imx_keypad_check_for_events is the timer handler.
*/
static void imx_keypad_check_for_events(struct timer_list *t)
{
struct imx_keypad *keypad = from_timer(keypad, t, check_matrix_timer);
unsigned short matrix_volatile_state[MAX_MATRIX_KEY_COLS];
unsigned short reg_val;
bool state_changed, is_zero_matrix;
int i;
memset(matrix_volatile_state, 0, sizeof(matrix_volatile_state));
imx_keypad_scan_matrix(keypad, matrix_volatile_state);
state_changed = false;
for (i = 0; i < MAX_MATRIX_KEY_COLS; i++) {
if ((keypad->cols_en_mask & (1 << i)) == 0)
continue;
if (keypad->matrix_unstable_state[i] ^ matrix_volatile_state[i]) {
state_changed = true;
break;
}
}
/*
* If the matrix state is changed from the previous scan
* (Re)Begin the debouncing process, saving the new state in
* keypad->matrix_unstable_state.
* else
* Increase the count of number of scans with a stable state.
*/
if (state_changed) {
memcpy(keypad->matrix_unstable_state, matrix_volatile_state,
sizeof(matrix_volatile_state));
keypad->stable_count = 0;
} else
keypad->stable_count++;
/*
* If the matrix is not as stable as we want reschedule scan
* in the near future.
*/
if (keypad->stable_count < IMX_KEYPAD_SCANS_FOR_STABILITY) {
mod_timer(&keypad->check_matrix_timer,
jiffies + msecs_to_jiffies(10));
return;
}
/*
* If the matrix state is stable, fire the events and save the new
* stable state. Note, if the matrix is kept stable for longer
* (keypad->stable_count > IMX_KEYPAD_SCANS_FOR_STABILITY) all
* events have already been generated.
*/
if (keypad->stable_count == IMX_KEYPAD_SCANS_FOR_STABILITY) {
imx_keypad_fire_events(keypad, matrix_volatile_state);
memcpy(keypad->matrix_stable_state, matrix_volatile_state,
sizeof(matrix_volatile_state));
}
is_zero_matrix = true;
for (i = 0; i < MAX_MATRIX_KEY_COLS; i++) {
if (matrix_volatile_state[i] != 0) {
is_zero_matrix = false;
break;
}
}
if (is_zero_matrix) {
/*
* All keys have been released. Enable only the KDI
* interrupt for future key presses (clear the KDI
* status bit and its sync chain before that).
*/
reg_val = readw(keypad->mmio_base + KPSR);
reg_val |= KBD_STAT_KPKD | KBD_STAT_KDSC;
writew(reg_val, keypad->mmio_base + KPSR);
reg_val = readw(keypad->mmio_base + KPSR);
reg_val |= KBD_STAT_KDIE;
reg_val &= ~KBD_STAT_KRIE;
writew(reg_val, keypad->mmio_base + KPSR);
} else {
/*
* Some keys are still pressed. Schedule a rescan in
* attempt to detect multiple key presses and enable
* the KRI interrupt to react quickly to key release
* event.
*/
mod_timer(&keypad->check_matrix_timer,
jiffies + msecs_to_jiffies(60));
reg_val = readw(keypad->mmio_base + KPSR);
reg_val |= KBD_STAT_KPKR | KBD_STAT_KRSS;
writew(reg_val, keypad->mmio_base + KPSR);
reg_val = readw(keypad->mmio_base + KPSR);
reg_val |= KBD_STAT_KRIE;
reg_val &= ~KBD_STAT_KDIE;
writew(reg_val, keypad->mmio_base + KPSR);
}
}
static irqreturn_t imx_keypad_irq_handler(int irq, void *dev_id)
{
struct imx_keypad *keypad = dev_id;
unsigned short reg_val;
reg_val = readw(keypad->mmio_base + KPSR);
/* Disable both interrupt types */
reg_val &= ~(KBD_STAT_KRIE | KBD_STAT_KDIE);
/* Clear interrupts status bits */
reg_val |= KBD_STAT_KPKR | KBD_STAT_KPKD;
writew(reg_val, keypad->mmio_base + KPSR);
if (keypad->enabled) {
/* The matrix is supposed to be changed */
keypad->stable_count = 0;
/* Schedule the scanning procedure near in the future */
mod_timer(&keypad->check_matrix_timer,
jiffies + msecs_to_jiffies(2));
}
return IRQ_HANDLED;
}
static void imx_keypad_config(struct imx_keypad *keypad)
{
unsigned short reg_val;
/*
* Include enabled rows in interrupt generation (KPCR[7:0])
* Configure keypad columns as open-drain (KPCR[15:8])
*/
reg_val = readw(keypad->mmio_base + KPCR);
reg_val |= keypad->rows_en_mask & 0xff; /* rows */
reg_val |= (keypad->cols_en_mask & 0xff) << 8; /* cols */
writew(reg_val, keypad->mmio_base + KPCR);
/* Write 0's to KPDR[15:8] (Colums) */
reg_val = readw(keypad->mmio_base + KPDR);
reg_val &= 0x00ff;
writew(reg_val, keypad->mmio_base + KPDR);
/* Configure columns as output, rows as input (KDDR[15:0]) */
writew(0xff00, keypad->mmio_base + KDDR);
/*
* Clear Key Depress and Key Release status bit.
* Clear both synchronizer chain.
*/
reg_val = readw(keypad->mmio_base + KPSR);
reg_val |= KBD_STAT_KPKR | KBD_STAT_KPKD |
KBD_STAT_KDSC | KBD_STAT_KRSS;
writew(reg_val, keypad->mmio_base + KPSR);
/* Enable KDI and disable KRI (avoid false release events). */
reg_val |= KBD_STAT_KDIE;
reg_val &= ~KBD_STAT_KRIE;
writew(reg_val, keypad->mmio_base + KPSR);
}
static void imx_keypad_inhibit(struct imx_keypad *keypad)
{
unsigned short reg_val;
/* Inhibit KDI and KRI interrupts. */
reg_val = readw(keypad->mmio_base + KPSR);
reg_val &= ~(KBD_STAT_KRIE | KBD_STAT_KDIE);
reg_val |= KBD_STAT_KPKR | KBD_STAT_KPKD;
writew(reg_val, keypad->mmio_base + KPSR);
/* Colums as open drain and disable all rows */
reg_val = (keypad->cols_en_mask & 0xff) << 8;
writew(reg_val, keypad->mmio_base + KPCR);
}
static void imx_keypad_close(struct input_dev *dev)
{
struct imx_keypad *keypad = input_get_drvdata(dev);
dev_dbg(&dev->dev, ">%s\n", __func__);
/* Mark keypad as being inactive */
keypad->enabled = false;
synchronize_irq(keypad->irq);
del_timer_sync(&keypad->check_matrix_timer);
imx_keypad_inhibit(keypad);
/* Disable clock unit */
clk_disable_unprepare(keypad->clk);
}
static int imx_keypad_open(struct input_dev *dev)
{
struct imx_keypad *keypad = input_get_drvdata(dev);
int error;
dev_dbg(&dev->dev, ">%s\n", __func__);
/* Enable the kpp clock */
error = clk_prepare_enable(keypad->clk);
if (error)
return error;
/* We became active from now */
keypad->enabled = true;
imx_keypad_config(keypad);
/* Sanity control, not all the rows must be actived now. */
if ((readw(keypad->mmio_base + KPDR) & keypad->rows_en_mask) == 0) {
dev_err(&dev->dev,
"too many keys pressed, control pins initialisation\n");
goto open_err;
}
return 0;
open_err:
imx_keypad_close(dev);
return -EIO;
}
static const struct of_device_id imx_keypad_of_match[] = {
{ .compatible = "fsl,imx21-kpp", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, imx_keypad_of_match);
static int imx_keypad_probe(struct platform_device *pdev)
{
struct imx_keypad *keypad;
struct input_dev *input_dev;
int irq, error, i, row, col;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
input_dev = devm_input_allocate_device(&pdev->dev);
if (!input_dev) {
dev_err(&pdev->dev, "failed to allocate the input device\n");
return -ENOMEM;
}
keypad = devm_kzalloc(&pdev->dev, sizeof(*keypad), GFP_KERNEL);
if (!keypad) {
dev_err(&pdev->dev, "not enough memory for driver data\n");
return -ENOMEM;
}
keypad->input_dev = input_dev;
keypad->irq = irq;
keypad->stable_count = 0;
timer_setup(&keypad->check_matrix_timer,
imx_keypad_check_for_events, 0);
keypad->mmio_base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(keypad->mmio_base))
return PTR_ERR(keypad->mmio_base);
keypad->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(keypad->clk)) {
dev_err(&pdev->dev, "failed to get keypad clock\n");
return PTR_ERR(keypad->clk);
}
/* Init the Input device */
input_dev->name = pdev->name;
input_dev->id.bustype = BUS_HOST;
input_dev->dev.parent = &pdev->dev;
input_dev->open = imx_keypad_open;
input_dev->close = imx_keypad_close;
error = matrix_keypad_build_keymap(NULL, NULL,
MAX_MATRIX_KEY_ROWS,
MAX_MATRIX_KEY_COLS,
keypad->keycodes, input_dev);
if (error) {
dev_err(&pdev->dev, "failed to build keymap\n");
return error;
}
/* Search for rows and cols enabled */
for (row = 0; row < MAX_MATRIX_KEY_ROWS; row++) {
for (col = 0; col < MAX_MATRIX_KEY_COLS; col++) {
i = MATRIX_SCAN_CODE(row, col, MATRIX_ROW_SHIFT);
if (keypad->keycodes[i] != KEY_RESERVED) {
keypad->rows_en_mask |= 1 << row;
keypad->cols_en_mask |= 1 << col;
}
}
}
dev_dbg(&pdev->dev, "enabled rows mask: %x\n", keypad->rows_en_mask);
dev_dbg(&pdev->dev, "enabled cols mask: %x\n", keypad->cols_en_mask);
__set_bit(EV_REP, input_dev->evbit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
input_set_drvdata(input_dev, keypad);
/* Ensure that the keypad will stay dormant until opened */
error = clk_prepare_enable(keypad->clk);
if (error)
return error;
imx_keypad_inhibit(keypad);
clk_disable_unprepare(keypad->clk);
error = devm_request_irq(&pdev->dev, irq, imx_keypad_irq_handler, 0,
pdev->name, keypad);
if (error) {
dev_err(&pdev->dev, "failed to request IRQ\n");
return error;
}
/* Register the input device */
error = input_register_device(input_dev);
if (error) {
dev_err(&pdev->dev, "failed to register input device\n");
return error;
}
platform_set_drvdata(pdev, keypad);
device_init_wakeup(&pdev->dev, 1);
return 0;
}
static int __maybe_unused imx_kbd_noirq_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct imx_keypad *kbd = platform_get_drvdata(pdev);
struct input_dev *input_dev = kbd->input_dev;
unsigned short reg_val = readw(kbd->mmio_base + KPSR);
/* imx kbd can wake up system even clock is disabled */
mutex_lock(&input_dev->mutex);
if (input_device_enabled(input_dev))
clk_disable_unprepare(kbd->clk);
mutex_unlock(&input_dev->mutex);
if (device_may_wakeup(&pdev->dev)) {
if (reg_val & KBD_STAT_KPKD)
reg_val |= KBD_STAT_KRIE;
if (reg_val & KBD_STAT_KPKR)
reg_val |= KBD_STAT_KDIE;
writew(reg_val, kbd->mmio_base + KPSR);
enable_irq_wake(kbd->irq);
}
return 0;
}
static int __maybe_unused imx_kbd_noirq_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct imx_keypad *kbd = platform_get_drvdata(pdev);
struct input_dev *input_dev = kbd->input_dev;
int ret = 0;
if (device_may_wakeup(&pdev->dev))
disable_irq_wake(kbd->irq);
mutex_lock(&input_dev->mutex);
if (input_device_enabled(input_dev)) {
ret = clk_prepare_enable(kbd->clk);
if (ret)
goto err_clk;
}
err_clk:
mutex_unlock(&input_dev->mutex);
return ret;
}
static const struct dev_pm_ops imx_kbd_pm_ops = {
SET_NOIRQ_SYSTEM_SLEEP_PM_OPS(imx_kbd_noirq_suspend, imx_kbd_noirq_resume)
};
static struct platform_driver imx_keypad_driver = {
.driver = {
.name = "imx-keypad",
.pm = &imx_kbd_pm_ops,
.of_match_table = imx_keypad_of_match,
},
.probe = imx_keypad_probe,
};
module_platform_driver(imx_keypad_driver);
MODULE_AUTHOR("Alberto Panizzo <[email protected]>");
MODULE_DESCRIPTION("IMX Keypad Port Driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:imx-keypad");
|
linux-master
|
drivers/input/keyboard/imx_keypad.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* Sun keyboard driver for Linux
*/
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/workqueue.h>
#define DRIVER_DESC "Sun keyboard driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static unsigned char sunkbd_keycode[128] = {
0,128,114,129,115, 59, 60, 68, 61, 87, 62, 88, 63,100, 64,112,
65, 66, 67, 56,103,119, 99, 70,105,130,131,108,106, 1, 2, 3,
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 41, 14,110,113, 98, 55,
116,132, 83,133,102, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27,111,127, 71, 72, 73, 74,134,135,107, 0, 29, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 40, 43, 28, 96, 75, 76, 77, 82,136,
104,137, 69, 42, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,101,
79, 80, 81, 0, 0, 0,138, 58,125, 57,126,109, 86, 78
};
#define SUNKBD_CMD_RESET 0x1
#define SUNKBD_CMD_BELLON 0x2
#define SUNKBD_CMD_BELLOFF 0x3
#define SUNKBD_CMD_CLICK 0xa
#define SUNKBD_CMD_NOCLICK 0xb
#define SUNKBD_CMD_SETLED 0xe
#define SUNKBD_CMD_LAYOUT 0xf
#define SUNKBD_RET_RESET 0xff
#define SUNKBD_RET_ALLUP 0x7f
#define SUNKBD_RET_LAYOUT 0xfe
#define SUNKBD_LAYOUT_5_MASK 0x20
#define SUNKBD_RELEASE 0x80
#define SUNKBD_KEY 0x7f
/*
* Per-keyboard data.
*/
struct sunkbd {
unsigned char keycode[ARRAY_SIZE(sunkbd_keycode)];
struct input_dev *dev;
struct serio *serio;
struct work_struct tq;
wait_queue_head_t wait;
char name[64];
char phys[32];
char type;
bool enabled;
volatile s8 reset;
volatile s8 layout;
};
/*
* sunkbd_interrupt() is called by the low level driver when a character
* is received.
*/
static irqreturn_t sunkbd_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct sunkbd *sunkbd = serio_get_drvdata(serio);
if (sunkbd->reset <= -1) {
/*
* If cp[i] is 0xff, sunkbd->reset will stay -1.
* The keyboard sends 0xff 0xff 0xID on powerup.
*/
sunkbd->reset = data;
wake_up_interruptible(&sunkbd->wait);
goto out;
}
if (sunkbd->layout == -1) {
sunkbd->layout = data;
wake_up_interruptible(&sunkbd->wait);
goto out;
}
switch (data) {
case SUNKBD_RET_RESET:
if (sunkbd->enabled)
schedule_work(&sunkbd->tq);
sunkbd->reset = -1;
break;
case SUNKBD_RET_LAYOUT:
sunkbd->layout = -1;
break;
case SUNKBD_RET_ALLUP: /* All keys released */
break;
default:
if (!sunkbd->enabled)
break;
if (sunkbd->keycode[data & SUNKBD_KEY]) {
input_report_key(sunkbd->dev,
sunkbd->keycode[data & SUNKBD_KEY],
!(data & SUNKBD_RELEASE));
input_sync(sunkbd->dev);
} else {
printk(KERN_WARNING
"sunkbd.c: Unknown key (scancode %#x) %s.\n",
data & SUNKBD_KEY,
data & SUNKBD_RELEASE ? "released" : "pressed");
}
}
out:
return IRQ_HANDLED;
}
/*
* sunkbd_event() handles events from the input module.
*/
static int sunkbd_event(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
struct sunkbd *sunkbd = input_get_drvdata(dev);
switch (type) {
case EV_LED:
serio_write(sunkbd->serio, SUNKBD_CMD_SETLED);
serio_write(sunkbd->serio,
(!!test_bit(LED_CAPSL, dev->led) << 3) |
(!!test_bit(LED_SCROLLL, dev->led) << 2) |
(!!test_bit(LED_COMPOSE, dev->led) << 1) |
!!test_bit(LED_NUML, dev->led));
return 0;
case EV_SND:
switch (code) {
case SND_CLICK:
serio_write(sunkbd->serio, SUNKBD_CMD_NOCLICK - value);
return 0;
case SND_BELL:
serio_write(sunkbd->serio, SUNKBD_CMD_BELLOFF - value);
return 0;
}
break;
}
return -1;
}
/*
* sunkbd_initialize() checks for a Sun keyboard attached, and determines
* its type.
*/
static int sunkbd_initialize(struct sunkbd *sunkbd)
{
sunkbd->reset = -2;
serio_write(sunkbd->serio, SUNKBD_CMD_RESET);
wait_event_interruptible_timeout(sunkbd->wait, sunkbd->reset >= 0, HZ);
if (sunkbd->reset < 0)
return -1;
sunkbd->type = sunkbd->reset;
if (sunkbd->type == 4) { /* Type 4 keyboard */
sunkbd->layout = -2;
serio_write(sunkbd->serio, SUNKBD_CMD_LAYOUT);
wait_event_interruptible_timeout(sunkbd->wait,
sunkbd->layout >= 0, HZ / 4);
if (sunkbd->layout < 0)
return -1;
if (sunkbd->layout & SUNKBD_LAYOUT_5_MASK)
sunkbd->type = 5;
}
return 0;
}
/*
* sunkbd_set_leds_beeps() sets leds and beeps to a state the computer remembers
* they were in.
*/
static void sunkbd_set_leds_beeps(struct sunkbd *sunkbd)
{
serio_write(sunkbd->serio, SUNKBD_CMD_SETLED);
serio_write(sunkbd->serio,
(!!test_bit(LED_CAPSL, sunkbd->dev->led) << 3) |
(!!test_bit(LED_SCROLLL, sunkbd->dev->led) << 2) |
(!!test_bit(LED_COMPOSE, sunkbd->dev->led) << 1) |
!!test_bit(LED_NUML, sunkbd->dev->led));
serio_write(sunkbd->serio,
SUNKBD_CMD_NOCLICK - !!test_bit(SND_CLICK, sunkbd->dev->snd));
serio_write(sunkbd->serio,
SUNKBD_CMD_BELLOFF - !!test_bit(SND_BELL, sunkbd->dev->snd));
}
/*
* sunkbd_reinit() wait for the keyboard reset to complete and restores state
* of leds and beeps.
*/
static void sunkbd_reinit(struct work_struct *work)
{
struct sunkbd *sunkbd = container_of(work, struct sunkbd, tq);
/*
* It is OK that we check sunkbd->enabled without pausing serio,
* as we only want to catch true->false transition that will
* happen once and we will be woken up for it.
*/
wait_event_interruptible_timeout(sunkbd->wait,
sunkbd->reset >= 0 || !sunkbd->enabled,
HZ);
if (sunkbd->reset >= 0 && sunkbd->enabled)
sunkbd_set_leds_beeps(sunkbd);
}
static void sunkbd_enable(struct sunkbd *sunkbd, bool enable)
{
serio_pause_rx(sunkbd->serio);
sunkbd->enabled = enable;
serio_continue_rx(sunkbd->serio);
if (!enable) {
wake_up_interruptible(&sunkbd->wait);
cancel_work_sync(&sunkbd->tq);
}
}
/*
* sunkbd_connect() probes for a Sun keyboard and fills the necessary
* structures.
*/
static int sunkbd_connect(struct serio *serio, struct serio_driver *drv)
{
struct sunkbd *sunkbd;
struct input_dev *input_dev;
int err = -ENOMEM;
int i;
sunkbd = kzalloc(sizeof(struct sunkbd), GFP_KERNEL);
input_dev = input_allocate_device();
if (!sunkbd || !input_dev)
goto fail1;
sunkbd->serio = serio;
sunkbd->dev = input_dev;
init_waitqueue_head(&sunkbd->wait);
INIT_WORK(&sunkbd->tq, sunkbd_reinit);
snprintf(sunkbd->phys, sizeof(sunkbd->phys), "%s/input0", serio->phys);
serio_set_drvdata(serio, sunkbd);
err = serio_open(serio, drv);
if (err)
goto fail2;
if (sunkbd_initialize(sunkbd) < 0) {
err = -ENODEV;
goto fail3;
}
snprintf(sunkbd->name, sizeof(sunkbd->name),
"Sun Type %d keyboard", sunkbd->type);
memcpy(sunkbd->keycode, sunkbd_keycode, sizeof(sunkbd->keycode));
input_dev->name = sunkbd->name;
input_dev->phys = sunkbd->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_SUNKBD;
input_dev->id.product = sunkbd->type;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_set_drvdata(input_dev, sunkbd);
input_dev->event = sunkbd_event;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_LED) |
BIT_MASK(EV_SND) | BIT_MASK(EV_REP);
input_dev->ledbit[0] = BIT_MASK(LED_CAPSL) | BIT_MASK(LED_COMPOSE) |
BIT_MASK(LED_SCROLLL) | BIT_MASK(LED_NUML);
input_dev->sndbit[0] = BIT_MASK(SND_CLICK) | BIT_MASK(SND_BELL);
input_dev->keycode = sunkbd->keycode;
input_dev->keycodesize = sizeof(unsigned char);
input_dev->keycodemax = ARRAY_SIZE(sunkbd_keycode);
for (i = 0; i < ARRAY_SIZE(sunkbd_keycode); i++)
__set_bit(sunkbd->keycode[i], input_dev->keybit);
__clear_bit(KEY_RESERVED, input_dev->keybit);
sunkbd_enable(sunkbd, true);
err = input_register_device(sunkbd->dev);
if (err)
goto fail4;
return 0;
fail4: sunkbd_enable(sunkbd, false);
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(sunkbd);
return err;
}
/*
* sunkbd_disconnect() unregisters and closes behind us.
*/
static void sunkbd_disconnect(struct serio *serio)
{
struct sunkbd *sunkbd = serio_get_drvdata(serio);
sunkbd_enable(sunkbd, false);
input_unregister_device(sunkbd->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
kfree(sunkbd);
}
static const struct serio_device_id sunkbd_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_SUNKBD,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{
.type = SERIO_RS232,
.proto = SERIO_UNKNOWN, /* sunkbd does probe */
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, sunkbd_serio_ids);
static struct serio_driver sunkbd_drv = {
.driver = {
.name = "sunkbd",
},
.description = DRIVER_DESC,
.id_table = sunkbd_serio_ids,
.interrupt = sunkbd_interrupt,
.connect = sunkbd_connect,
.disconnect = sunkbd_disconnect,
};
module_serio_driver(sunkbd_drv);
|
linux-master
|
drivers/input/keyboard/sunkbd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Input driver for Microchip CAP11xx based capacitive touch sensors
*
* (c) 2014 Daniel Mack <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/leds.h>
#include <linux/of_irq.h>
#include <linux/regmap.h>
#include <linux/i2c.h>
#include <linux/gpio/consumer.h>
#define CAP11XX_REG_MAIN_CONTROL 0x00
#define CAP11XX_REG_MAIN_CONTROL_GAIN_SHIFT (6)
#define CAP11XX_REG_MAIN_CONTROL_GAIN_MASK (0xc0)
#define CAP11XX_REG_MAIN_CONTROL_DLSEEP BIT(4)
#define CAP11XX_REG_GENERAL_STATUS 0x02
#define CAP11XX_REG_SENSOR_INPUT 0x03
#define CAP11XX_REG_NOISE_FLAG_STATUS 0x0a
#define CAP11XX_REG_SENOR_DELTA(X) (0x10 + (X))
#define CAP11XX_REG_SENSITIVITY_CONTROL 0x1f
#define CAP11XX_REG_CONFIG 0x20
#define CAP11XX_REG_SENSOR_ENABLE 0x21
#define CAP11XX_REG_SENSOR_CONFIG 0x22
#define CAP11XX_REG_SENSOR_CONFIG2 0x23
#define CAP11XX_REG_SAMPLING_CONFIG 0x24
#define CAP11XX_REG_CALIBRATION 0x26
#define CAP11XX_REG_INT_ENABLE 0x27
#define CAP11XX_REG_REPEAT_RATE 0x28
#define CAP11XX_REG_MT_CONFIG 0x2a
#define CAP11XX_REG_MT_PATTERN_CONFIG 0x2b
#define CAP11XX_REG_MT_PATTERN 0x2d
#define CAP11XX_REG_RECALIB_CONFIG 0x2f
#define CAP11XX_REG_SENSOR_THRESH(X) (0x30 + (X))
#define CAP11XX_REG_SENSOR_NOISE_THRESH 0x38
#define CAP11XX_REG_STANDBY_CHANNEL 0x40
#define CAP11XX_REG_STANDBY_CONFIG 0x41
#define CAP11XX_REG_STANDBY_SENSITIVITY 0x42
#define CAP11XX_REG_STANDBY_THRESH 0x43
#define CAP11XX_REG_CONFIG2 0x44
#define CAP11XX_REG_CONFIG2_ALT_POL BIT(6)
#define CAP11XX_REG_SENSOR_BASE_CNT(X) (0x50 + (X))
#define CAP11XX_REG_LED_POLARITY 0x73
#define CAP11XX_REG_LED_OUTPUT_CONTROL 0x74
#define CAP11XX_REG_LED_DUTY_CYCLE_1 0x90
#define CAP11XX_REG_LED_DUTY_CYCLE_2 0x91
#define CAP11XX_REG_LED_DUTY_CYCLE_3 0x92
#define CAP11XX_REG_LED_DUTY_CYCLE_4 0x93
#define CAP11XX_REG_LED_DUTY_MIN_MASK (0x0f)
#define CAP11XX_REG_LED_DUTY_MIN_MASK_SHIFT (0)
#define CAP11XX_REG_LED_DUTY_MAX_MASK (0xf0)
#define CAP11XX_REG_LED_DUTY_MAX_MASK_SHIFT (4)
#define CAP11XX_REG_LED_DUTY_MAX_VALUE (15)
#define CAP11XX_REG_SENSOR_CALIB (0xb1 + (X))
#define CAP11XX_REG_SENSOR_CALIB_LSB1 0xb9
#define CAP11XX_REG_SENSOR_CALIB_LSB2 0xba
#define CAP11XX_REG_PRODUCT_ID 0xfd
#define CAP11XX_REG_MANUFACTURER_ID 0xfe
#define CAP11XX_REG_REVISION 0xff
#define CAP11XX_MANUFACTURER_ID 0x5d
#ifdef CONFIG_LEDS_CLASS
struct cap11xx_led {
struct cap11xx_priv *priv;
struct led_classdev cdev;
u32 reg;
};
#endif
struct cap11xx_priv {
struct regmap *regmap;
struct input_dev *idev;
struct cap11xx_led *leds;
int num_leds;
/* config */
u32 keycodes[];
};
struct cap11xx_hw_model {
u8 product_id;
unsigned int num_channels;
unsigned int num_leds;
bool no_gain;
};
enum {
CAP1106,
CAP1126,
CAP1188,
CAP1203,
CAP1206,
CAP1293,
CAP1298
};
static const struct cap11xx_hw_model cap11xx_devices[] = {
[CAP1106] = { .product_id = 0x55, .num_channels = 6, .num_leds = 0, .no_gain = false },
[CAP1126] = { .product_id = 0x53, .num_channels = 6, .num_leds = 2, .no_gain = false },
[CAP1188] = { .product_id = 0x50, .num_channels = 8, .num_leds = 8, .no_gain = false },
[CAP1203] = { .product_id = 0x6d, .num_channels = 3, .num_leds = 0, .no_gain = true },
[CAP1206] = { .product_id = 0x67, .num_channels = 6, .num_leds = 0, .no_gain = true },
[CAP1293] = { .product_id = 0x6f, .num_channels = 3, .num_leds = 0, .no_gain = false },
[CAP1298] = { .product_id = 0x71, .num_channels = 8, .num_leds = 0, .no_gain = false },
};
static const struct reg_default cap11xx_reg_defaults[] = {
{ CAP11XX_REG_MAIN_CONTROL, 0x00 },
{ CAP11XX_REG_GENERAL_STATUS, 0x00 },
{ CAP11XX_REG_SENSOR_INPUT, 0x00 },
{ CAP11XX_REG_NOISE_FLAG_STATUS, 0x00 },
{ CAP11XX_REG_SENSITIVITY_CONTROL, 0x2f },
{ CAP11XX_REG_CONFIG, 0x20 },
{ CAP11XX_REG_SENSOR_ENABLE, 0x3f },
{ CAP11XX_REG_SENSOR_CONFIG, 0xa4 },
{ CAP11XX_REG_SENSOR_CONFIG2, 0x07 },
{ CAP11XX_REG_SAMPLING_CONFIG, 0x39 },
{ CAP11XX_REG_CALIBRATION, 0x00 },
{ CAP11XX_REG_INT_ENABLE, 0x3f },
{ CAP11XX_REG_REPEAT_RATE, 0x3f },
{ CAP11XX_REG_MT_CONFIG, 0x80 },
{ CAP11XX_REG_MT_PATTERN_CONFIG, 0x00 },
{ CAP11XX_REG_MT_PATTERN, 0x3f },
{ CAP11XX_REG_RECALIB_CONFIG, 0x8a },
{ CAP11XX_REG_SENSOR_THRESH(0), 0x40 },
{ CAP11XX_REG_SENSOR_THRESH(1), 0x40 },
{ CAP11XX_REG_SENSOR_THRESH(2), 0x40 },
{ CAP11XX_REG_SENSOR_THRESH(3), 0x40 },
{ CAP11XX_REG_SENSOR_THRESH(4), 0x40 },
{ CAP11XX_REG_SENSOR_THRESH(5), 0x40 },
{ CAP11XX_REG_SENSOR_NOISE_THRESH, 0x01 },
{ CAP11XX_REG_STANDBY_CHANNEL, 0x00 },
{ CAP11XX_REG_STANDBY_CONFIG, 0x39 },
{ CAP11XX_REG_STANDBY_SENSITIVITY, 0x02 },
{ CAP11XX_REG_STANDBY_THRESH, 0x40 },
{ CAP11XX_REG_CONFIG2, 0x40 },
{ CAP11XX_REG_LED_POLARITY, 0x00 },
{ CAP11XX_REG_SENSOR_CALIB_LSB1, 0x00 },
{ CAP11XX_REG_SENSOR_CALIB_LSB2, 0x00 },
};
static bool cap11xx_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case CAP11XX_REG_MAIN_CONTROL:
case CAP11XX_REG_SENSOR_INPUT:
case CAP11XX_REG_SENOR_DELTA(0):
case CAP11XX_REG_SENOR_DELTA(1):
case CAP11XX_REG_SENOR_DELTA(2):
case CAP11XX_REG_SENOR_DELTA(3):
case CAP11XX_REG_SENOR_DELTA(4):
case CAP11XX_REG_SENOR_DELTA(5):
case CAP11XX_REG_PRODUCT_ID:
case CAP11XX_REG_MANUFACTURER_ID:
case CAP11XX_REG_REVISION:
return true;
}
return false;
}
static const struct regmap_config cap11xx_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = CAP11XX_REG_REVISION,
.reg_defaults = cap11xx_reg_defaults,
.num_reg_defaults = ARRAY_SIZE(cap11xx_reg_defaults),
.cache_type = REGCACHE_RBTREE,
.volatile_reg = cap11xx_volatile_reg,
};
static irqreturn_t cap11xx_thread_func(int irq_num, void *data)
{
struct cap11xx_priv *priv = data;
unsigned int status;
int ret, i;
/*
* Deassert interrupt. This needs to be done before reading the status
* registers, which will not carry valid values otherwise.
*/
ret = regmap_update_bits(priv->regmap, CAP11XX_REG_MAIN_CONTROL, 1, 0);
if (ret < 0)
goto out;
ret = regmap_read(priv->regmap, CAP11XX_REG_SENSOR_INPUT, &status);
if (ret < 0)
goto out;
for (i = 0; i < priv->idev->keycodemax; i++)
input_report_key(priv->idev, priv->keycodes[i],
status & (1 << i));
input_sync(priv->idev);
out:
return IRQ_HANDLED;
}
static int cap11xx_set_sleep(struct cap11xx_priv *priv, bool sleep)
{
/*
* DLSEEP mode will turn off all LEDS, prevent this
*/
if (IS_ENABLED(CONFIG_LEDS_CLASS) && priv->num_leds)
return 0;
return regmap_update_bits(priv->regmap, CAP11XX_REG_MAIN_CONTROL,
CAP11XX_REG_MAIN_CONTROL_DLSEEP,
sleep ? CAP11XX_REG_MAIN_CONTROL_DLSEEP : 0);
}
static int cap11xx_input_open(struct input_dev *idev)
{
struct cap11xx_priv *priv = input_get_drvdata(idev);
return cap11xx_set_sleep(priv, false);
}
static void cap11xx_input_close(struct input_dev *idev)
{
struct cap11xx_priv *priv = input_get_drvdata(idev);
cap11xx_set_sleep(priv, true);
}
#ifdef CONFIG_LEDS_CLASS
static int cap11xx_led_set(struct led_classdev *cdev,
enum led_brightness value)
{
struct cap11xx_led *led = container_of(cdev, struct cap11xx_led, cdev);
struct cap11xx_priv *priv = led->priv;
/*
* All LEDs share the same duty cycle as this is a HW
* limitation. Brightness levels per LED are either
* 0 (OFF) and 1 (ON).
*/
return regmap_update_bits(priv->regmap,
CAP11XX_REG_LED_OUTPUT_CONTROL,
BIT(led->reg),
value ? BIT(led->reg) : 0);
}
static int cap11xx_init_leds(struct device *dev,
struct cap11xx_priv *priv, int num_leds)
{
struct device_node *node = dev->of_node, *child;
struct cap11xx_led *led;
int cnt = of_get_child_count(node);
int error;
if (!num_leds || !cnt)
return 0;
if (cnt > num_leds)
return -EINVAL;
led = devm_kcalloc(dev, cnt, sizeof(struct cap11xx_led), GFP_KERNEL);
if (!led)
return -ENOMEM;
priv->leds = led;
error = regmap_update_bits(priv->regmap,
CAP11XX_REG_LED_OUTPUT_CONTROL, 0xff, 0);
if (error)
return error;
error = regmap_update_bits(priv->regmap, CAP11XX_REG_LED_DUTY_CYCLE_4,
CAP11XX_REG_LED_DUTY_MAX_MASK,
CAP11XX_REG_LED_DUTY_MAX_VALUE <<
CAP11XX_REG_LED_DUTY_MAX_MASK_SHIFT);
if (error)
return error;
for_each_child_of_node(node, child) {
u32 reg;
led->cdev.name =
of_get_property(child, "label", NULL) ? : child->name;
led->cdev.default_trigger =
of_get_property(child, "linux,default-trigger", NULL);
led->cdev.flags = 0;
led->cdev.brightness_set_blocking = cap11xx_led_set;
led->cdev.max_brightness = 1;
led->cdev.brightness = LED_OFF;
error = of_property_read_u32(child, "reg", ®);
if (error != 0 || reg >= num_leds) {
of_node_put(child);
return -EINVAL;
}
led->reg = reg;
led->priv = priv;
error = devm_led_classdev_register(dev, &led->cdev);
if (error) {
of_node_put(child);
return error;
}
priv->num_leds++;
led++;
}
return 0;
}
#else
static int cap11xx_init_leds(struct device *dev,
struct cap11xx_priv *priv, int num_leds)
{
return 0;
}
#endif
static int cap11xx_i2c_probe(struct i2c_client *i2c_client)
{
const struct i2c_device_id *id = i2c_client_get_device_id(i2c_client);
struct device *dev = &i2c_client->dev;
struct cap11xx_priv *priv;
struct device_node *node;
const struct cap11xx_hw_model *cap;
int i, error, irq, gain = 0;
unsigned int val, rev;
u32 gain32;
if (id->driver_data >= ARRAY_SIZE(cap11xx_devices)) {
dev_err(dev, "Invalid device ID %lu\n", id->driver_data);
return -EINVAL;
}
cap = &cap11xx_devices[id->driver_data];
if (!cap || !cap->num_channels) {
dev_err(dev, "Invalid device configuration\n");
return -EINVAL;
}
priv = devm_kzalloc(dev,
struct_size(priv, keycodes, cap->num_channels),
GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->regmap = devm_regmap_init_i2c(i2c_client, &cap11xx_regmap_config);
if (IS_ERR(priv->regmap))
return PTR_ERR(priv->regmap);
error = regmap_read(priv->regmap, CAP11XX_REG_PRODUCT_ID, &val);
if (error)
return error;
if (val != cap->product_id) {
dev_err(dev, "Product ID: Got 0x%02x, expected 0x%02x\n",
val, cap->product_id);
return -ENXIO;
}
error = regmap_read(priv->regmap, CAP11XX_REG_MANUFACTURER_ID, &val);
if (error)
return error;
if (val != CAP11XX_MANUFACTURER_ID) {
dev_err(dev, "Manufacturer ID: Got 0x%02x, expected 0x%02x\n",
val, CAP11XX_MANUFACTURER_ID);
return -ENXIO;
}
error = regmap_read(priv->regmap, CAP11XX_REG_REVISION, &rev);
if (error < 0)
return error;
dev_info(dev, "CAP11XX detected, model %s, revision 0x%02x\n",
id->name, rev);
node = dev->of_node;
if (!of_property_read_u32(node, "microchip,sensor-gain", &gain32)) {
if (cap->no_gain)
dev_warn(dev,
"This version doesn't support sensor gain\n");
else if (is_power_of_2(gain32) && gain32 <= 8)
gain = ilog2(gain32);
else
dev_err(dev, "Invalid sensor-gain value %d\n", gain32);
}
if (id->driver_data == CAP1106 ||
id->driver_data == CAP1126 ||
id->driver_data == CAP1188) {
if (of_property_read_bool(node, "microchip,irq-active-high")) {
error = regmap_update_bits(priv->regmap,
CAP11XX_REG_CONFIG2,
CAP11XX_REG_CONFIG2_ALT_POL,
0);
if (error)
return error;
}
}
/* Provide some useful defaults */
for (i = 0; i < cap->num_channels; i++)
priv->keycodes[i] = KEY_A + i;
of_property_read_u32_array(node, "linux,keycodes",
priv->keycodes, cap->num_channels);
if (!cap->no_gain) {
error = regmap_update_bits(priv->regmap,
CAP11XX_REG_MAIN_CONTROL,
CAP11XX_REG_MAIN_CONTROL_GAIN_MASK,
gain << CAP11XX_REG_MAIN_CONTROL_GAIN_SHIFT);
if (error)
return error;
}
/* Disable autorepeat. The Linux input system has its own handling. */
error = regmap_write(priv->regmap, CAP11XX_REG_REPEAT_RATE, 0);
if (error)
return error;
priv->idev = devm_input_allocate_device(dev);
if (!priv->idev)
return -ENOMEM;
priv->idev->name = "CAP11XX capacitive touch sensor";
priv->idev->id.bustype = BUS_I2C;
priv->idev->evbit[0] = BIT_MASK(EV_KEY);
if (of_property_read_bool(node, "autorepeat"))
__set_bit(EV_REP, priv->idev->evbit);
for (i = 0; i < cap->num_channels; i++)
__set_bit(priv->keycodes[i], priv->idev->keybit);
__clear_bit(KEY_RESERVED, priv->idev->keybit);
priv->idev->keycode = priv->keycodes;
priv->idev->keycodesize = sizeof(priv->keycodes[0]);
priv->idev->keycodemax = cap->num_channels;
priv->idev->id.vendor = CAP11XX_MANUFACTURER_ID;
priv->idev->id.product = cap->product_id;
priv->idev->id.version = rev;
priv->idev->open = cap11xx_input_open;
priv->idev->close = cap11xx_input_close;
error = cap11xx_init_leds(dev, priv, cap->num_leds);
if (error)
return error;
input_set_drvdata(priv->idev, priv);
/*
* Put the device in deep sleep mode for now.
* ->open() will bring it back once the it is actually needed.
*/
cap11xx_set_sleep(priv, true);
error = input_register_device(priv->idev);
if (error)
return error;
irq = irq_of_parse_and_map(node, 0);
if (!irq) {
dev_err(dev, "Unable to parse or map IRQ\n");
return -ENXIO;
}
error = devm_request_threaded_irq(dev, irq, NULL, cap11xx_thread_func,
IRQF_ONESHOT, dev_name(dev), priv);
if (error)
return error;
return 0;
}
static const struct of_device_id cap11xx_dt_ids[] = {
{ .compatible = "microchip,cap1106", },
{ .compatible = "microchip,cap1126", },
{ .compatible = "microchip,cap1188", },
{ .compatible = "microchip,cap1203", },
{ .compatible = "microchip,cap1206", },
{ .compatible = "microchip,cap1293", },
{ .compatible = "microchip,cap1298", },
{}
};
MODULE_DEVICE_TABLE(of, cap11xx_dt_ids);
static const struct i2c_device_id cap11xx_i2c_ids[] = {
{ "cap1106", CAP1106 },
{ "cap1126", CAP1126 },
{ "cap1188", CAP1188 },
{ "cap1203", CAP1203 },
{ "cap1206", CAP1206 },
{ "cap1293", CAP1293 },
{ "cap1298", CAP1298 },
{}
};
MODULE_DEVICE_TABLE(i2c, cap11xx_i2c_ids);
static struct i2c_driver cap11xx_i2c_driver = {
.driver = {
.name = "cap11xx",
.of_match_table = cap11xx_dt_ids,
},
.id_table = cap11xx_i2c_ids,
.probe = cap11xx_i2c_probe,
};
module_i2c_driver(cap11xx_i2c_driver);
MODULE_DESCRIPTION("Microchip CAP11XX driver");
MODULE_AUTHOR("Daniel Mack <[email protected]>");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/keyboard/cap11xx.c
|
// SPDX-License-Identifier: GPL-2.0+
//
// Driver for the IMX SNVS ON/OFF Power Key
// Copyright (C) 2015 Freescale Semiconductor, Inc. All Rights Reserved.
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/platform_device.h>
#include <linux/pm_wakeirq.h>
#include <linux/mfd/syscon.h>
#include <linux/regmap.h>
#define SNVS_HPVIDR1_REG 0xBF8
#define SNVS_LPSR_REG 0x4C /* LP Status Register */
#define SNVS_LPCR_REG 0x38 /* LP Control Register */
#define SNVS_HPSR_REG 0x14
#define SNVS_HPSR_BTN BIT(6)
#define SNVS_LPSR_SPO BIT(18)
#define SNVS_LPCR_DEP_EN BIT(5)
#define DEBOUNCE_TIME 30
#define REPEAT_INTERVAL 60
struct pwrkey_drv_data {
struct regmap *snvs;
int irq;
int keycode;
int keystate; /* 1:pressed */
int wakeup;
struct timer_list check_timer;
struct input_dev *input;
u8 minor_rev;
};
static void imx_imx_snvs_check_for_events(struct timer_list *t)
{
struct pwrkey_drv_data *pdata = from_timer(pdata, t, check_timer);
struct input_dev *input = pdata->input;
u32 state;
regmap_read(pdata->snvs, SNVS_HPSR_REG, &state);
state = state & SNVS_HPSR_BTN ? 1 : 0;
/* only report new event if status changed */
if (state ^ pdata->keystate) {
pdata->keystate = state;
input_event(input, EV_KEY, pdata->keycode, state);
input_sync(input);
pm_relax(pdata->input->dev.parent);
}
/* repeat check if pressed long */
if (state) {
mod_timer(&pdata->check_timer,
jiffies + msecs_to_jiffies(REPEAT_INTERVAL));
}
}
static irqreturn_t imx_snvs_pwrkey_interrupt(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct pwrkey_drv_data *pdata = platform_get_drvdata(pdev);
struct input_dev *input = pdata->input;
u32 lp_status;
pm_wakeup_event(input->dev.parent, 0);
regmap_read(pdata->snvs, SNVS_LPSR_REG, &lp_status);
if (lp_status & SNVS_LPSR_SPO) {
if (pdata->minor_rev == 0) {
/*
* The first generation i.MX6 SoCs only sends an
* interrupt on button release. To mimic power-key
* usage, we'll prepend a press event.
*/
input_report_key(input, pdata->keycode, 1);
input_sync(input);
input_report_key(input, pdata->keycode, 0);
input_sync(input);
pm_relax(input->dev.parent);
} else {
mod_timer(&pdata->check_timer,
jiffies + msecs_to_jiffies(DEBOUNCE_TIME));
}
}
/* clear SPO status */
regmap_write(pdata->snvs, SNVS_LPSR_REG, SNVS_LPSR_SPO);
return IRQ_HANDLED;
}
static void imx_snvs_pwrkey_disable_clk(void *data)
{
clk_disable_unprepare(data);
}
static void imx_snvs_pwrkey_act(void *pdata)
{
struct pwrkey_drv_data *pd = pdata;
del_timer_sync(&pd->check_timer);
}
static int imx_snvs_pwrkey_probe(struct platform_device *pdev)
{
struct pwrkey_drv_data *pdata;
struct input_dev *input;
struct device_node *np;
struct clk *clk;
int error;
u32 vid;
/* Get SNVS register Page */
np = pdev->dev.of_node;
if (!np)
return -ENODEV;
pdata = devm_kzalloc(&pdev->dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return -ENOMEM;
pdata->snvs = syscon_regmap_lookup_by_phandle(np, "regmap");
if (IS_ERR(pdata->snvs)) {
dev_err(&pdev->dev, "Can't get snvs syscon\n");
return PTR_ERR(pdata->snvs);
}
if (of_property_read_u32(np, "linux,keycode", &pdata->keycode)) {
pdata->keycode = KEY_POWER;
dev_warn(&pdev->dev, "KEY_POWER without setting in dts\n");
}
clk = devm_clk_get_optional(&pdev->dev, NULL);
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "Failed to get snvs clock (%pe)\n", clk);
return PTR_ERR(clk);
}
error = clk_prepare_enable(clk);
if (error) {
dev_err(&pdev->dev, "Failed to enable snvs clock (%pe)\n",
ERR_PTR(error));
return error;
}
error = devm_add_action_or_reset(&pdev->dev,
imx_snvs_pwrkey_disable_clk, clk);
if (error) {
dev_err(&pdev->dev,
"Failed to register clock cleanup handler (%pe)\n",
ERR_PTR(error));
return error;
}
pdata->wakeup = of_property_read_bool(np, "wakeup-source");
pdata->irq = platform_get_irq(pdev, 0);
if (pdata->irq < 0)
return -EINVAL;
regmap_read(pdata->snvs, SNVS_HPVIDR1_REG, &vid);
pdata->minor_rev = vid & 0xff;
regmap_update_bits(pdata->snvs, SNVS_LPCR_REG, SNVS_LPCR_DEP_EN, SNVS_LPCR_DEP_EN);
/* clear the unexpected interrupt before driver ready */
regmap_write(pdata->snvs, SNVS_LPSR_REG, SNVS_LPSR_SPO);
timer_setup(&pdata->check_timer, imx_imx_snvs_check_for_events, 0);
input = devm_input_allocate_device(&pdev->dev);
if (!input) {
dev_err(&pdev->dev, "failed to allocate the input device\n");
return -ENOMEM;
}
input->name = pdev->name;
input->phys = "snvs-pwrkey/input0";
input->id.bustype = BUS_HOST;
input_set_capability(input, EV_KEY, pdata->keycode);
/* input customer action to cancel release timer */
error = devm_add_action(&pdev->dev, imx_snvs_pwrkey_act, pdata);
if (error) {
dev_err(&pdev->dev, "failed to register remove action\n");
return error;
}
pdata->input = input;
platform_set_drvdata(pdev, pdata);
error = devm_request_irq(&pdev->dev, pdata->irq,
imx_snvs_pwrkey_interrupt,
0, pdev->name, pdev);
if (error) {
dev_err(&pdev->dev, "interrupt not available.\n");
return error;
}
error = input_register_device(input);
if (error < 0) {
dev_err(&pdev->dev, "failed to register input device\n");
return error;
}
device_init_wakeup(&pdev->dev, pdata->wakeup);
error = dev_pm_set_wake_irq(&pdev->dev, pdata->irq);
if (error)
dev_err(&pdev->dev, "irq wake enable failed.\n");
return 0;
}
static const struct of_device_id imx_snvs_pwrkey_ids[] = {
{ .compatible = "fsl,sec-v4.0-pwrkey" },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, imx_snvs_pwrkey_ids);
static struct platform_driver imx_snvs_pwrkey_driver = {
.driver = {
.name = "snvs_pwrkey",
.of_match_table = imx_snvs_pwrkey_ids,
},
.probe = imx_snvs_pwrkey_probe,
};
module_platform_driver(imx_snvs_pwrkey_driver);
MODULE_AUTHOR("Freescale Semiconductor");
MODULE_DESCRIPTION("i.MX snvs power key Driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/snvs_pwrkey.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* OMAP4 Keypad Driver
*
* Copyright (C) 2010 Texas Instruments
*
* Author: Abraham Arce <[email protected]>
* Initial Code: Syed Rafiuddin <[email protected]>
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/errno.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/slab.h>
#include <linux/pm_runtime.h>
#include <linux/pm_wakeirq.h>
/* OMAP4 registers */
#define OMAP4_KBD_REVISION 0x00
#define OMAP4_KBD_SYSCONFIG 0x10
#define OMAP4_KBD_SYSSTATUS 0x14
#define OMAP4_KBD_IRQSTATUS 0x18
#define OMAP4_KBD_IRQENABLE 0x1C
#define OMAP4_KBD_WAKEUPENABLE 0x20
#define OMAP4_KBD_PENDING 0x24
#define OMAP4_KBD_CTRL 0x28
#define OMAP4_KBD_DEBOUNCINGTIME 0x2C
#define OMAP4_KBD_LONGKEYTIME 0x30
#define OMAP4_KBD_TIMEOUT 0x34
#define OMAP4_KBD_STATEMACHINE 0x38
#define OMAP4_KBD_ROWINPUTS 0x3C
#define OMAP4_KBD_COLUMNOUTPUTS 0x40
#define OMAP4_KBD_FULLCODE31_0 0x44
#define OMAP4_KBD_FULLCODE63_32 0x48
/* OMAP4 bit definitions */
#define OMAP4_DEF_IRQENABLE_EVENTEN BIT(0)
#define OMAP4_DEF_IRQENABLE_LONGKEY BIT(1)
#define OMAP4_DEF_WUP_EVENT_ENA BIT(0)
#define OMAP4_DEF_WUP_LONG_KEY_ENA BIT(1)
#define OMAP4_DEF_CTRL_NOSOFTMODE BIT(1)
#define OMAP4_DEF_CTRL_PTV_SHIFT 2
/* OMAP4 values */
#define OMAP4_VAL_IRQDISABLE 0x0
/*
* Errata i689: If a key is released for a time shorter than debounce time,
* the keyboard will idle and never detect the key release. The workaround
* is to use at least a 12ms debounce time. See omap5432 TRM chapter
* "26.4.6.2 Keyboard Controller Timer" for more information.
*/
#define OMAP4_KEYPAD_PTV_DIV_128 0x6
#define OMAP4_KEYPAD_DEBOUNCINGTIME_MS(dbms, ptv) \
((((dbms) * 1000) / ((1 << ((ptv) + 1)) * (1000000 / 32768))) - 1)
#define OMAP4_VAL_DEBOUNCINGTIME_16MS \
OMAP4_KEYPAD_DEBOUNCINGTIME_MS(16, OMAP4_KEYPAD_PTV_DIV_128)
#define OMAP4_KEYPAD_AUTOIDLE_MS 50 /* Approximate measured time */
#define OMAP4_KEYPAD_IDLE_CHECK_MS (OMAP4_KEYPAD_AUTOIDLE_MS / 2)
enum {
KBD_REVISION_OMAP4 = 0,
KBD_REVISION_OMAP5,
};
struct omap4_keypad {
struct input_dev *input;
void __iomem *base;
unsigned int irq;
struct mutex lock; /* for key scan */
unsigned int rows;
unsigned int cols;
u32 reg_offset;
u32 irqreg_offset;
unsigned int row_shift;
bool no_autorepeat;
u64 keys;
unsigned short *keymap;
};
static int kbd_readl(struct omap4_keypad *keypad_data, u32 offset)
{
return __raw_readl(keypad_data->base +
keypad_data->reg_offset + offset);
}
static void kbd_writel(struct omap4_keypad *keypad_data, u32 offset, u32 value)
{
__raw_writel(value,
keypad_data->base + keypad_data->reg_offset + offset);
}
static int kbd_read_irqreg(struct omap4_keypad *keypad_data, u32 offset)
{
return __raw_readl(keypad_data->base +
keypad_data->irqreg_offset + offset);
}
static void kbd_write_irqreg(struct omap4_keypad *keypad_data,
u32 offset, u32 value)
{
__raw_writel(value,
keypad_data->base + keypad_data->irqreg_offset + offset);
}
static int omap4_keypad_report_keys(struct omap4_keypad *keypad_data,
u64 keys, bool down)
{
struct input_dev *input_dev = keypad_data->input;
unsigned int col, row, code;
DECLARE_BITMAP(mask, 64);
unsigned long bit;
int events = 0;
bitmap_from_u64(mask, keys);
for_each_set_bit(bit, mask, keypad_data->rows * BITS_PER_BYTE) {
row = bit / BITS_PER_BYTE;
col = bit % BITS_PER_BYTE;
code = MATRIX_SCAN_CODE(row, col, keypad_data->row_shift);
input_event(input_dev, EV_MSC, MSC_SCAN, code);
input_report_key(input_dev, keypad_data->keymap[code], down);
events++;
}
if (events)
input_sync(input_dev);
return events;
}
static void omap4_keypad_scan_keys(struct omap4_keypad *keypad_data, u64 keys)
{
u64 changed;
mutex_lock(&keypad_data->lock);
changed = keys ^ keypad_data->keys;
/*
* Report key up events separately and first. This matters in case we
* lost key-up interrupt and just now catching up.
*/
omap4_keypad_report_keys(keypad_data, changed & ~keys, false);
/* Report key down events */
omap4_keypad_report_keys(keypad_data, changed & keys, true);
keypad_data->keys = keys;
mutex_unlock(&keypad_data->lock);
}
/* Interrupt handlers */
static irqreturn_t omap4_keypad_irq_handler(int irq, void *dev_id)
{
struct omap4_keypad *keypad_data = dev_id;
if (kbd_read_irqreg(keypad_data, OMAP4_KBD_IRQSTATUS))
return IRQ_WAKE_THREAD;
return IRQ_NONE;
}
static irqreturn_t omap4_keypad_irq_thread_fn(int irq, void *dev_id)
{
struct omap4_keypad *keypad_data = dev_id;
struct device *dev = keypad_data->input->dev.parent;
u32 low, high;
int error;
u64 keys;
error = pm_runtime_resume_and_get(dev);
if (error)
return IRQ_NONE;
low = kbd_readl(keypad_data, OMAP4_KBD_FULLCODE31_0);
high = kbd_readl(keypad_data, OMAP4_KBD_FULLCODE63_32);
keys = low | (u64)high << 32;
omap4_keypad_scan_keys(keypad_data, keys);
/* clear pending interrupts */
kbd_write_irqreg(keypad_data, OMAP4_KBD_IRQSTATUS,
kbd_read_irqreg(keypad_data, OMAP4_KBD_IRQSTATUS));
pm_runtime_mark_last_busy(dev);
pm_runtime_put_autosuspend(dev);
return IRQ_HANDLED;
}
static int omap4_keypad_open(struct input_dev *input)
{
struct omap4_keypad *keypad_data = input_get_drvdata(input);
struct device *dev = input->dev.parent;
int error;
error = pm_runtime_resume_and_get(dev);
if (error)
return error;
disable_irq(keypad_data->irq);
kbd_writel(keypad_data, OMAP4_KBD_CTRL,
OMAP4_DEF_CTRL_NOSOFTMODE |
(OMAP4_KEYPAD_PTV_DIV_128 << OMAP4_DEF_CTRL_PTV_SHIFT));
kbd_writel(keypad_data, OMAP4_KBD_DEBOUNCINGTIME,
OMAP4_VAL_DEBOUNCINGTIME_16MS);
/* clear pending interrupts */
kbd_write_irqreg(keypad_data, OMAP4_KBD_IRQSTATUS,
kbd_read_irqreg(keypad_data, OMAP4_KBD_IRQSTATUS));
kbd_write_irqreg(keypad_data, OMAP4_KBD_IRQENABLE,
OMAP4_DEF_IRQENABLE_EVENTEN);
kbd_writel(keypad_data, OMAP4_KBD_WAKEUPENABLE,
OMAP4_DEF_WUP_EVENT_ENA);
enable_irq(keypad_data->irq);
pm_runtime_mark_last_busy(dev);
pm_runtime_put_autosuspend(dev);
return 0;
}
static void omap4_keypad_stop(struct omap4_keypad *keypad_data)
{
/* Disable interrupts and wake-up events */
kbd_write_irqreg(keypad_data, OMAP4_KBD_IRQENABLE,
OMAP4_VAL_IRQDISABLE);
kbd_writel(keypad_data, OMAP4_KBD_WAKEUPENABLE, 0);
/* clear pending interrupts */
kbd_write_irqreg(keypad_data, OMAP4_KBD_IRQSTATUS,
kbd_read_irqreg(keypad_data, OMAP4_KBD_IRQSTATUS));
}
static void omap4_keypad_close(struct input_dev *input)
{
struct omap4_keypad *keypad_data = input_get_drvdata(input);
struct device *dev = input->dev.parent;
int error;
error = pm_runtime_resume_and_get(dev);
if (error)
dev_err(dev, "%s: pm_runtime_resume_and_get() failed: %d\n",
__func__, error);
disable_irq(keypad_data->irq);
omap4_keypad_stop(keypad_data);
enable_irq(keypad_data->irq);
pm_runtime_mark_last_busy(dev);
pm_runtime_put_autosuspend(dev);
}
static int omap4_keypad_parse_dt(struct device *dev,
struct omap4_keypad *keypad_data)
{
struct device_node *np = dev->of_node;
int err;
err = matrix_keypad_parse_properties(dev, &keypad_data->rows,
&keypad_data->cols);
if (err)
return err;
keypad_data->no_autorepeat = of_property_read_bool(np, "linux,input-no-autorepeat");
return 0;
}
static int omap4_keypad_check_revision(struct device *dev,
struct omap4_keypad *keypad_data)
{
unsigned int rev;
rev = __raw_readl(keypad_data->base + OMAP4_KBD_REVISION);
rev &= 0x03 << 30;
rev >>= 30;
switch (rev) {
case KBD_REVISION_OMAP4:
keypad_data->reg_offset = 0x00;
keypad_data->irqreg_offset = 0x00;
break;
case KBD_REVISION_OMAP5:
keypad_data->reg_offset = 0x10;
keypad_data->irqreg_offset = 0x0c;
break;
default:
dev_err(dev, "Keypad reports unsupported revision %d", rev);
return -EINVAL;
}
return 0;
}
/*
* Errata ID i689 "1.32 Keyboard Key Up Event Can Be Missed".
* Interrupt may not happen for key-up events. We must clear stuck
* key-up events after the keyboard hardware has auto-idled.
*/
static int omap4_keypad_runtime_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct omap4_keypad *keypad_data = platform_get_drvdata(pdev);
u32 active;
active = kbd_readl(keypad_data, OMAP4_KBD_STATEMACHINE);
if (active) {
pm_runtime_mark_last_busy(dev);
return -EBUSY;
}
omap4_keypad_scan_keys(keypad_data, 0);
return 0;
}
static const struct dev_pm_ops omap4_keypad_pm_ops = {
RUNTIME_PM_OPS(omap4_keypad_runtime_suspend, NULL, NULL)
};
static void omap4_disable_pm(void *d)
{
pm_runtime_dont_use_autosuspend(d);
pm_runtime_disable(d);
}
static int omap4_keypad_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct omap4_keypad *keypad_data;
struct input_dev *input_dev;
unsigned int max_keys;
int irq;
int error;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
keypad_data = devm_kzalloc(dev, sizeof(*keypad_data), GFP_KERNEL);
if (!keypad_data) {
dev_err(dev, "keypad_data memory allocation failed\n");
return -ENOMEM;
}
keypad_data->irq = irq;
mutex_init(&keypad_data->lock);
platform_set_drvdata(pdev, keypad_data);
error = omap4_keypad_parse_dt(dev, keypad_data);
if (error)
return error;
keypad_data->base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(keypad_data->base))
return PTR_ERR(keypad_data->base);
pm_runtime_use_autosuspend(dev);
pm_runtime_set_autosuspend_delay(dev, OMAP4_KEYPAD_IDLE_CHECK_MS);
pm_runtime_enable(dev);
error = devm_add_action_or_reset(dev, omap4_disable_pm, dev);
if (error) {
dev_err(dev, "unable to register cleanup action\n");
return error;
}
/*
* Enable clocks for the keypad module so that we can read
* revision register.
*/
error = pm_runtime_resume_and_get(dev);
if (error) {
dev_err(dev, "pm_runtime_resume_and_get() failed\n");
return error;
}
error = omap4_keypad_check_revision(dev, keypad_data);
if (!error) {
/* Ensure device does not raise interrupts */
omap4_keypad_stop(keypad_data);
}
pm_runtime_mark_last_busy(dev);
pm_runtime_put_autosuspend(dev);
if (error)
return error;
/* input device allocation */
keypad_data->input = input_dev = devm_input_allocate_device(dev);
if (!input_dev)
return -ENOMEM;
input_dev->name = pdev->name;
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0001;
input_dev->open = omap4_keypad_open;
input_dev->close = omap4_keypad_close;
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
if (!keypad_data->no_autorepeat)
__set_bit(EV_REP, input_dev->evbit);
input_set_drvdata(input_dev, keypad_data);
keypad_data->row_shift = get_count_order(keypad_data->cols);
max_keys = keypad_data->rows << keypad_data->row_shift;
keypad_data->keymap = devm_kcalloc(dev,
max_keys,
sizeof(keypad_data->keymap[0]),
GFP_KERNEL);
if (!keypad_data->keymap) {
dev_err(dev, "Not enough memory for keymap\n");
return -ENOMEM;
}
error = matrix_keypad_build_keymap(NULL, NULL,
keypad_data->rows, keypad_data->cols,
keypad_data->keymap, input_dev);
if (error) {
dev_err(dev, "failed to build keymap\n");
return error;
}
error = devm_request_threaded_irq(dev, keypad_data->irq,
omap4_keypad_irq_handler,
omap4_keypad_irq_thread_fn,
IRQF_ONESHOT,
"omap4-keypad", keypad_data);
if (error) {
dev_err(dev, "failed to register interrupt\n");
return error;
}
error = input_register_device(keypad_data->input);
if (error) {
dev_err(dev, "failed to register input device\n");
return error;
}
device_init_wakeup(dev, true);
error = dev_pm_set_wake_irq(dev, keypad_data->irq);
if (error)
dev_warn(dev, "failed to set up wakeup irq: %d\n", error);
return 0;
}
static int omap4_keypad_remove(struct platform_device *pdev)
{
dev_pm_clear_wake_irq(&pdev->dev);
return 0;
}
static const struct of_device_id omap_keypad_dt_match[] = {
{ .compatible = "ti,omap4-keypad" },
{},
};
MODULE_DEVICE_TABLE(of, omap_keypad_dt_match);
static struct platform_driver omap4_keypad_driver = {
.probe = omap4_keypad_probe,
.remove = omap4_keypad_remove,
.driver = {
.name = "omap4-keypad",
.of_match_table = omap_keypad_dt_match,
.pm = pm_ptr(&omap4_keypad_pm_ops),
},
};
module_platform_driver(omap4_keypad_driver);
MODULE_AUTHOR("Texas Instruments");
MODULE_DESCRIPTION("OMAP4 Keypad Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:omap4-keypad");
|
linux-master
|
drivers/input/keyboard/omap4-keypad.c
|
// SPDX-License-Identifier: GPL-2.0
// ChromeOS EC keyboard driver
//
// Copyright (C) 2012 Google, Inc.
//
// This driver uses the ChromeOS EC byte-level message-based protocol for
// communicating the keyboard state (which keys are pressed) from a keyboard EC
// to the AP over some bus (such as i2c, lpc, spi). The EC does debouncing,
// but everything else (including deghosting) is done here. The main
// motivation for this is to keep the EC firmware as simple as possible, since
// it cannot be easily upgraded and EC flash/IRAM space is relatively
// expensive.
#include <linux/module.h>
#include <linux/acpi.h>
#include <linux/bitops.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/vivaldi-fmap.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/notifier.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/sysrq.h>
#include <linux/input/matrix_keypad.h>
#include <linux/platform_data/cros_ec_commands.h>
#include <linux/platform_data/cros_ec_proto.h>
#include <asm/unaligned.h>
/**
* struct cros_ec_keyb - Structure representing EC keyboard device
*
* @rows: Number of rows in the keypad
* @cols: Number of columns in the keypad
* @row_shift: log2 or number of rows, rounded up
* @keymap_data: Matrix keymap data used to convert to keyscan values
* @ghost_filter: true to enable the matrix key-ghosting filter
* @valid_keys: bitmap of existing keys for each matrix column
* @old_kb_state: bitmap of keys pressed last scan
* @dev: Device pointer
* @ec: Top level ChromeOS device to use to talk to EC
* @idev: The input device for the matrix keys.
* @bs_idev: The input device for non-matrix buttons and switches (or NULL).
* @notifier: interrupt event notifier for transport devices
* @vdata: vivaldi function row data
*/
struct cros_ec_keyb {
unsigned int rows;
unsigned int cols;
int row_shift;
const struct matrix_keymap_data *keymap_data;
bool ghost_filter;
uint8_t *valid_keys;
uint8_t *old_kb_state;
struct device *dev;
struct cros_ec_device *ec;
struct input_dev *idev;
struct input_dev *bs_idev;
struct notifier_block notifier;
struct vivaldi_data vdata;
};
/**
* struct cros_ec_bs_map - Mapping between Linux keycodes and EC button/switch
* bitmap #defines
*
* @ev_type: The type of the input event to generate (e.g., EV_KEY).
* @code: A linux keycode
* @bit: A #define like EC_MKBP_POWER_BUTTON or EC_MKBP_LID_OPEN
* @inverted: If the #define and EV_SW have opposite meanings, this is true.
* Only applicable to switches.
*/
struct cros_ec_bs_map {
unsigned int ev_type;
unsigned int code;
u8 bit;
bool inverted;
};
/* cros_ec_keyb_bs - Map EC button/switch #defines into kernel ones */
static const struct cros_ec_bs_map cros_ec_keyb_bs[] = {
/* Buttons */
{
.ev_type = EV_KEY,
.code = KEY_POWER,
.bit = EC_MKBP_POWER_BUTTON,
},
{
.ev_type = EV_KEY,
.code = KEY_VOLUMEUP,
.bit = EC_MKBP_VOL_UP,
},
{
.ev_type = EV_KEY,
.code = KEY_VOLUMEDOWN,
.bit = EC_MKBP_VOL_DOWN,
},
{
.ev_type = EV_KEY,
.code = KEY_BRIGHTNESSUP,
.bit = EC_MKBP_BRI_UP,
},
{
.ev_type = EV_KEY,
.code = KEY_BRIGHTNESSDOWN,
.bit = EC_MKBP_BRI_DOWN,
},
{
.ev_type = EV_KEY,
.code = KEY_SCREENLOCK,
.bit = EC_MKBP_SCREEN_LOCK,
},
/* Switches */
{
.ev_type = EV_SW,
.code = SW_LID,
.bit = EC_MKBP_LID_OPEN,
.inverted = true,
},
{
.ev_type = EV_SW,
.code = SW_TABLET_MODE,
.bit = EC_MKBP_TABLET_MODE,
},
};
/*
* Returns true when there is at least one combination of pressed keys that
* results in ghosting.
*/
static bool cros_ec_keyb_has_ghosting(struct cros_ec_keyb *ckdev, uint8_t *buf)
{
int col1, col2, buf1, buf2;
struct device *dev = ckdev->dev;
uint8_t *valid_keys = ckdev->valid_keys;
/*
* Ghosting happens if for any pressed key X there are other keys
* pressed both in the same row and column of X as, for instance,
* in the following diagram:
*
* . . Y . g .
* . . . . . .
* . . . . . .
* . . X . Z .
*
* In this case only X, Y, and Z are pressed, but g appears to be
* pressed too (see Wikipedia).
*/
for (col1 = 0; col1 < ckdev->cols; col1++) {
buf1 = buf[col1] & valid_keys[col1];
for (col2 = col1 + 1; col2 < ckdev->cols; col2++) {
buf2 = buf[col2] & valid_keys[col2];
if (hweight8(buf1 & buf2) > 1) {
dev_dbg(dev, "ghost found at: B[%02d]:0x%02x & B[%02d]:0x%02x",
col1, buf1, col2, buf2);
return true;
}
}
}
return false;
}
/*
* Compares the new keyboard state to the old one and produces key
* press/release events accordingly. The keyboard state is 13 bytes (one byte
* per column)
*/
static void cros_ec_keyb_process(struct cros_ec_keyb *ckdev,
uint8_t *kb_state, int len)
{
struct input_dev *idev = ckdev->idev;
int col, row;
int new_state;
int old_state;
if (ckdev->ghost_filter && cros_ec_keyb_has_ghosting(ckdev, kb_state)) {
/*
* Simple-minded solution: ignore this state. The obvious
* improvement is to only ignore changes to keys involved in
* the ghosting, but process the other changes.
*/
dev_dbg(ckdev->dev, "ghosting found\n");
return;
}
for (col = 0; col < ckdev->cols; col++) {
for (row = 0; row < ckdev->rows; row++) {
int pos = MATRIX_SCAN_CODE(row, col, ckdev->row_shift);
const unsigned short *keycodes = idev->keycode;
new_state = kb_state[col] & (1 << row);
old_state = ckdev->old_kb_state[col] & (1 << row);
if (new_state != old_state) {
dev_dbg(ckdev->dev,
"changed: [r%d c%d]: byte %02x\n",
row, col, new_state);
input_event(idev, EV_MSC, MSC_SCAN, pos);
input_report_key(idev, keycodes[pos],
new_state);
}
}
ckdev->old_kb_state[col] = kb_state[col];
}
input_sync(ckdev->idev);
}
/**
* cros_ec_keyb_report_bs - Report non-matrixed buttons or switches
*
* This takes a bitmap of buttons or switches from the EC and reports events,
* syncing at the end.
*
* @ckdev: The keyboard device.
* @ev_type: The input event type (e.g., EV_KEY).
* @mask: A bitmap of buttons from the EC.
*/
static void cros_ec_keyb_report_bs(struct cros_ec_keyb *ckdev,
unsigned int ev_type, u32 mask)
{
struct input_dev *idev = ckdev->bs_idev;
int i;
for (i = 0; i < ARRAY_SIZE(cros_ec_keyb_bs); i++) {
const struct cros_ec_bs_map *map = &cros_ec_keyb_bs[i];
if (map->ev_type != ev_type)
continue;
input_event(idev, ev_type, map->code,
!!(mask & BIT(map->bit)) ^ map->inverted);
}
input_sync(idev);
}
static int cros_ec_keyb_work(struct notifier_block *nb,
unsigned long queued_during_suspend, void *_notify)
{
struct cros_ec_keyb *ckdev = container_of(nb, struct cros_ec_keyb,
notifier);
u32 val;
unsigned int ev_type;
/*
* If not wake enabled, discard key state changes during
* suspend. Switches will be re-checked in
* cros_ec_keyb_resume() to be sure nothing is lost.
*/
if (queued_during_suspend && !device_may_wakeup(ckdev->dev))
return NOTIFY_OK;
switch (ckdev->ec->event_data.event_type) {
case EC_MKBP_EVENT_KEY_MATRIX:
pm_wakeup_event(ckdev->dev, 0);
if (ckdev->ec->event_size != ckdev->cols) {
dev_err(ckdev->dev,
"Discarded incomplete key matrix event.\n");
return NOTIFY_OK;
}
cros_ec_keyb_process(ckdev,
ckdev->ec->event_data.data.key_matrix,
ckdev->ec->event_size);
break;
case EC_MKBP_EVENT_SYSRQ:
pm_wakeup_event(ckdev->dev, 0);
val = get_unaligned_le32(&ckdev->ec->event_data.data.sysrq);
dev_dbg(ckdev->dev, "sysrq code from EC: %#x\n", val);
handle_sysrq(val);
break;
case EC_MKBP_EVENT_BUTTON:
case EC_MKBP_EVENT_SWITCH:
pm_wakeup_event(ckdev->dev, 0);
if (ckdev->ec->event_data.event_type == EC_MKBP_EVENT_BUTTON) {
val = get_unaligned_le32(
&ckdev->ec->event_data.data.buttons);
ev_type = EV_KEY;
} else {
val = get_unaligned_le32(
&ckdev->ec->event_data.data.switches);
ev_type = EV_SW;
}
cros_ec_keyb_report_bs(ckdev, ev_type, val);
break;
default:
return NOTIFY_DONE;
}
return NOTIFY_OK;
}
/*
* Walks keycodes flipping bit in buffer COLUMNS deep where bit is ROW. Used by
* ghosting logic to ignore NULL or virtual keys.
*/
static void cros_ec_keyb_compute_valid_keys(struct cros_ec_keyb *ckdev)
{
int row, col;
int row_shift = ckdev->row_shift;
unsigned short *keymap = ckdev->idev->keycode;
unsigned short code;
BUG_ON(ckdev->idev->keycodesize != sizeof(*keymap));
for (col = 0; col < ckdev->cols; col++) {
for (row = 0; row < ckdev->rows; row++) {
code = keymap[MATRIX_SCAN_CODE(row, col, row_shift)];
if (code && (code != KEY_BATTERY))
ckdev->valid_keys[col] |= 1 << row;
}
dev_dbg(ckdev->dev, "valid_keys[%02d] = 0x%02x\n",
col, ckdev->valid_keys[col]);
}
}
/**
* cros_ec_keyb_info - Wrap the EC command EC_CMD_MKBP_INFO
*
* This wraps the EC_CMD_MKBP_INFO, abstracting out all of the marshalling and
* unmarshalling and different version nonsense into something simple.
*
* @ec_dev: The EC device
* @info_type: Either EC_MKBP_INFO_SUPPORTED or EC_MKBP_INFO_CURRENT.
* @event_type: Either EC_MKBP_EVENT_BUTTON or EC_MKBP_EVENT_SWITCH. Actually
* in some cases this could be EC_MKBP_EVENT_KEY_MATRIX or
* EC_MKBP_EVENT_HOST_EVENT too but we don't use in this driver.
* @result: Where we'll store the result; a union
* @result_size: The size of the result. Expected to be the size of one of
* the elements in the union.
*
* Returns 0 if no error or -error upon error.
*/
static int cros_ec_keyb_info(struct cros_ec_device *ec_dev,
enum ec_mkbp_info_type info_type,
enum ec_mkbp_event event_type,
union ec_response_get_next_data *result,
size_t result_size)
{
struct ec_params_mkbp_info *params;
struct cros_ec_command *msg;
int ret;
msg = kzalloc(sizeof(*msg) + max_t(size_t, result_size,
sizeof(*params)), GFP_KERNEL);
if (!msg)
return -ENOMEM;
msg->command = EC_CMD_MKBP_INFO;
msg->version = 1;
msg->outsize = sizeof(*params);
msg->insize = result_size;
params = (struct ec_params_mkbp_info *)msg->data;
params->info_type = info_type;
params->event_type = event_type;
ret = cros_ec_cmd_xfer_status(ec_dev, msg);
if (ret == -ENOPROTOOPT) {
/* With older ECs we just return 0 for everything */
memset(result, 0, result_size);
ret = 0;
} else if (ret < 0) {
dev_warn(ec_dev->dev, "Transfer error %d/%d: %d\n",
(int)info_type, (int)event_type, ret);
} else if (ret != result_size) {
dev_warn(ec_dev->dev, "Wrong size %d/%d: %d != %zu\n",
(int)info_type, (int)event_type,
ret, result_size);
ret = -EPROTO;
} else {
memcpy(result, msg->data, result_size);
ret = 0;
}
kfree(msg);
return ret;
}
/**
* cros_ec_keyb_query_switches - Query the state of switches and report
*
* This will ask the EC about the current state of switches and report to the
* kernel. Note that we don't query for buttons because they are more
* transitory and we'll get an update on the next release / press.
*
* @ckdev: The keyboard device
*
* Returns 0 if no error or -error upon error.
*/
static int cros_ec_keyb_query_switches(struct cros_ec_keyb *ckdev)
{
struct cros_ec_device *ec_dev = ckdev->ec;
union ec_response_get_next_data event_data = {};
int ret;
ret = cros_ec_keyb_info(ec_dev, EC_MKBP_INFO_CURRENT,
EC_MKBP_EVENT_SWITCH, &event_data,
sizeof(event_data.switches));
if (ret)
return ret;
cros_ec_keyb_report_bs(ckdev, EV_SW,
get_unaligned_le32(&event_data.switches));
return 0;
}
/**
* cros_ec_keyb_resume - Resume the keyboard
*
* We use the resume notification as a chance to query the EC for switches.
*
* @dev: The keyboard device
*
* Returns 0 if no error or -error upon error.
*/
static int cros_ec_keyb_resume(struct device *dev)
{
struct cros_ec_keyb *ckdev = dev_get_drvdata(dev);
if (ckdev->bs_idev)
return cros_ec_keyb_query_switches(ckdev);
return 0;
}
/**
* cros_ec_keyb_register_bs - Register non-matrix buttons/switches
*
* Handles all the bits of the keyboard driver related to non-matrix buttons
* and switches, including asking the EC about which are present and telling
* the kernel to expect them.
*
* If this device has no support for buttons and switches we'll return no error
* but the ckdev->bs_idev will remain NULL when this function exits.
*
* @ckdev: The keyboard device
* @expect_buttons_switches: Indicates that EC must report button and/or
* switch events
*
* Returns 0 if no error or -error upon error.
*/
static int cros_ec_keyb_register_bs(struct cros_ec_keyb *ckdev,
bool expect_buttons_switches)
{
struct cros_ec_device *ec_dev = ckdev->ec;
struct device *dev = ckdev->dev;
struct input_dev *idev;
union ec_response_get_next_data event_data = {};
const char *phys;
u32 buttons;
u32 switches;
int ret;
int i;
ret = cros_ec_keyb_info(ec_dev, EC_MKBP_INFO_SUPPORTED,
EC_MKBP_EVENT_BUTTON, &event_data,
sizeof(event_data.buttons));
if (ret)
return ret;
buttons = get_unaligned_le32(&event_data.buttons);
ret = cros_ec_keyb_info(ec_dev, EC_MKBP_INFO_SUPPORTED,
EC_MKBP_EVENT_SWITCH, &event_data,
sizeof(event_data.switches));
if (ret)
return ret;
switches = get_unaligned_le32(&event_data.switches);
if (!buttons && !switches)
return expect_buttons_switches ? -EINVAL : 0;
/*
* We call the non-matrix buttons/switches 'input1', if present.
* Allocate phys before input dev, to ensure correct tear-down
* ordering.
*/
phys = devm_kasprintf(dev, GFP_KERNEL, "%s/input1", ec_dev->phys_name);
if (!phys)
return -ENOMEM;
idev = devm_input_allocate_device(dev);
if (!idev)
return -ENOMEM;
idev->name = "cros_ec_buttons";
idev->phys = phys;
__set_bit(EV_REP, idev->evbit);
idev->id.bustype = BUS_VIRTUAL;
idev->id.version = 1;
idev->id.product = 0;
idev->dev.parent = dev;
input_set_drvdata(idev, ckdev);
ckdev->bs_idev = idev;
for (i = 0; i < ARRAY_SIZE(cros_ec_keyb_bs); i++) {
const struct cros_ec_bs_map *map = &cros_ec_keyb_bs[i];
if ((map->ev_type == EV_KEY && (buttons & BIT(map->bit))) ||
(map->ev_type == EV_SW && (switches & BIT(map->bit))))
input_set_capability(idev, map->ev_type, map->code);
}
ret = cros_ec_keyb_query_switches(ckdev);
if (ret) {
dev_err(dev, "cannot query switches\n");
return ret;
}
ret = input_register_device(ckdev->bs_idev);
if (ret) {
dev_err(dev, "cannot register input device\n");
return ret;
}
return 0;
}
static void cros_ec_keyb_parse_vivaldi_physmap(struct cros_ec_keyb *ckdev)
{
u32 *physmap = ckdev->vdata.function_row_physmap;
unsigned int row, col, scancode;
int n_physmap;
int error;
int i;
n_physmap = device_property_count_u32(ckdev->dev,
"function-row-physmap");
if (n_physmap <= 0)
return;
if (n_physmap >= VIVALDI_MAX_FUNCTION_ROW_KEYS) {
dev_warn(ckdev->dev,
"only up to %d top row keys is supported (%d specified)\n",
VIVALDI_MAX_FUNCTION_ROW_KEYS, n_physmap);
n_physmap = VIVALDI_MAX_FUNCTION_ROW_KEYS;
}
error = device_property_read_u32_array(ckdev->dev,
"function-row-physmap",
physmap, n_physmap);
if (error) {
dev_warn(ckdev->dev,
"failed to parse function-row-physmap property: %d\n",
error);
return;
}
/*
* Convert (in place) from row/column encoding to matrix "scancode"
* used by the driver.
*/
for (i = 0; i < n_physmap; i++) {
row = KEY_ROW(physmap[i]);
col = KEY_COL(physmap[i]);
scancode = MATRIX_SCAN_CODE(row, col, ckdev->row_shift);
physmap[i] = scancode;
}
ckdev->vdata.num_function_row_keys = n_physmap;
}
/**
* cros_ec_keyb_register_matrix - Register matrix keys
*
* Handles all the bits of the keyboard driver related to matrix keys.
*
* @ckdev: The keyboard device
*
* Returns 0 if no error or -error upon error.
*/
static int cros_ec_keyb_register_matrix(struct cros_ec_keyb *ckdev)
{
struct cros_ec_device *ec_dev = ckdev->ec;
struct device *dev = ckdev->dev;
struct input_dev *idev;
const char *phys;
int err;
err = matrix_keypad_parse_properties(dev, &ckdev->rows, &ckdev->cols);
if (err)
return err;
ckdev->valid_keys = devm_kzalloc(dev, ckdev->cols, GFP_KERNEL);
if (!ckdev->valid_keys)
return -ENOMEM;
ckdev->old_kb_state = devm_kzalloc(dev, ckdev->cols, GFP_KERNEL);
if (!ckdev->old_kb_state)
return -ENOMEM;
/*
* We call the keyboard matrix 'input0'. Allocate phys before input
* dev, to ensure correct tear-down ordering.
*/
phys = devm_kasprintf(dev, GFP_KERNEL, "%s/input0", ec_dev->phys_name);
if (!phys)
return -ENOMEM;
idev = devm_input_allocate_device(dev);
if (!idev)
return -ENOMEM;
idev->name = CROS_EC_DEV_NAME;
idev->phys = phys;
__set_bit(EV_REP, idev->evbit);
idev->id.bustype = BUS_VIRTUAL;
idev->id.version = 1;
idev->id.product = 0;
idev->dev.parent = dev;
ckdev->ghost_filter = device_property_read_bool(dev,
"google,needs-ghost-filter");
err = matrix_keypad_build_keymap(NULL, NULL, ckdev->rows, ckdev->cols,
NULL, idev);
if (err) {
dev_err(dev, "cannot build key matrix\n");
return err;
}
ckdev->row_shift = get_count_order(ckdev->cols);
input_set_capability(idev, EV_MSC, MSC_SCAN);
input_set_drvdata(idev, ckdev);
ckdev->idev = idev;
cros_ec_keyb_compute_valid_keys(ckdev);
cros_ec_keyb_parse_vivaldi_physmap(ckdev);
err = input_register_device(ckdev->idev);
if (err) {
dev_err(dev, "cannot register input device\n");
return err;
}
return 0;
}
static ssize_t function_row_physmap_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
const struct cros_ec_keyb *ckdev = dev_get_drvdata(dev);
const struct vivaldi_data *data = &ckdev->vdata;
return vivaldi_function_row_physmap_show(data, buf);
}
static DEVICE_ATTR_RO(function_row_physmap);
static struct attribute *cros_ec_keyb_attrs[] = {
&dev_attr_function_row_physmap.attr,
NULL,
};
static umode_t cros_ec_keyb_attr_is_visible(struct kobject *kobj,
struct attribute *attr,
int n)
{
struct device *dev = kobj_to_dev(kobj);
struct cros_ec_keyb *ckdev = dev_get_drvdata(dev);
if (attr == &dev_attr_function_row_physmap.attr &&
!ckdev->vdata.num_function_row_keys)
return 0;
return attr->mode;
}
static const struct attribute_group cros_ec_keyb_attr_group = {
.is_visible = cros_ec_keyb_attr_is_visible,
.attrs = cros_ec_keyb_attrs,
};
static int cros_ec_keyb_probe(struct platform_device *pdev)
{
struct cros_ec_device *ec;
struct device *dev = &pdev->dev;
struct cros_ec_keyb *ckdev;
bool buttons_switches_only = device_get_match_data(dev);
int err;
/*
* If the parent ec device has not been probed yet, defer the probe of
* this keyboard/button driver until later.
*/
ec = dev_get_drvdata(pdev->dev.parent);
if (!ec)
return -EPROBE_DEFER;
ckdev = devm_kzalloc(dev, sizeof(*ckdev), GFP_KERNEL);
if (!ckdev)
return -ENOMEM;
ckdev->ec = ec;
ckdev->dev = dev;
dev_set_drvdata(dev, ckdev);
if (!buttons_switches_only) {
err = cros_ec_keyb_register_matrix(ckdev);
if (err) {
dev_err(dev, "cannot register matrix inputs: %d\n",
err);
return err;
}
}
err = cros_ec_keyb_register_bs(ckdev, buttons_switches_only);
if (err) {
dev_err(dev, "cannot register non-matrix inputs: %d\n", err);
return err;
}
err = devm_device_add_group(dev, &cros_ec_keyb_attr_group);
if (err) {
dev_err(dev, "failed to create attributes: %d\n", err);
return err;
}
ckdev->notifier.notifier_call = cros_ec_keyb_work;
err = blocking_notifier_chain_register(&ckdev->ec->event_notifier,
&ckdev->notifier);
if (err) {
dev_err(dev, "cannot register notifier: %d\n", err);
return err;
}
device_init_wakeup(ckdev->dev, true);
return 0;
}
static int cros_ec_keyb_remove(struct platform_device *pdev)
{
struct cros_ec_keyb *ckdev = dev_get_drvdata(&pdev->dev);
blocking_notifier_chain_unregister(&ckdev->ec->event_notifier,
&ckdev->notifier);
return 0;
}
#ifdef CONFIG_ACPI
static const struct acpi_device_id cros_ec_keyb_acpi_match[] = {
{ "GOOG0007", true },
{ }
};
MODULE_DEVICE_TABLE(acpi, cros_ec_keyb_acpi_match);
#endif
#ifdef CONFIG_OF
static const struct of_device_id cros_ec_keyb_of_match[] = {
{ .compatible = "google,cros-ec-keyb" },
{ .compatible = "google,cros-ec-keyb-switches", .data = (void *)true },
{}
};
MODULE_DEVICE_TABLE(of, cros_ec_keyb_of_match);
#endif
static DEFINE_SIMPLE_DEV_PM_OPS(cros_ec_keyb_pm_ops, NULL, cros_ec_keyb_resume);
static struct platform_driver cros_ec_keyb_driver = {
.probe = cros_ec_keyb_probe,
.remove = cros_ec_keyb_remove,
.driver = {
.name = "cros-ec-keyb",
.of_match_table = of_match_ptr(cros_ec_keyb_of_match),
.acpi_match_table = ACPI_PTR(cros_ec_keyb_acpi_match),
.pm = pm_sleep_ptr(&cros_ec_keyb_pm_ops),
},
};
module_platform_driver(cros_ec_keyb_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("ChromeOS EC keyboard driver");
MODULE_ALIAS("platform:cros-ec-keyb");
|
linux-master
|
drivers/input/keyboard/cros_ec_keyb.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* STMicroelectronics Key Scanning driver
*
* Copyright (c) 2014 STMicroelectonics Ltd.
* Author: Stuart Menefy <[email protected]>
*
* Based on sh_keysc.c, copyright 2008 Magnus Damm
*/
#include <linux/clk.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/io.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#define ST_KEYSCAN_MAXKEYS 16
#define KEYSCAN_CONFIG_OFF 0x0
#define KEYSCAN_CONFIG_ENABLE 0x1
#define KEYSCAN_DEBOUNCE_TIME_OFF 0x4
#define KEYSCAN_MATRIX_STATE_OFF 0x8
#define KEYSCAN_MATRIX_DIM_OFF 0xc
#define KEYSCAN_MATRIX_DIM_X_SHIFT 0x0
#define KEYSCAN_MATRIX_DIM_Y_SHIFT 0x2
struct st_keyscan {
void __iomem *base;
int irq;
struct clk *clk;
struct input_dev *input_dev;
unsigned long last_state;
unsigned int n_rows;
unsigned int n_cols;
unsigned int debounce_us;
};
static irqreturn_t keyscan_isr(int irq, void *dev_id)
{
struct st_keyscan *keypad = dev_id;
unsigned short *keycode = keypad->input_dev->keycode;
unsigned long state, change;
int bit_nr;
state = readl(keypad->base + KEYSCAN_MATRIX_STATE_OFF) & 0xffff;
change = keypad->last_state ^ state;
keypad->last_state = state;
for_each_set_bit(bit_nr, &change, BITS_PER_LONG)
input_report_key(keypad->input_dev,
keycode[bit_nr], state & BIT(bit_nr));
input_sync(keypad->input_dev);
return IRQ_HANDLED;
}
static int keyscan_start(struct st_keyscan *keypad)
{
int error;
error = clk_enable(keypad->clk);
if (error)
return error;
writel(keypad->debounce_us * (clk_get_rate(keypad->clk) / 1000000),
keypad->base + KEYSCAN_DEBOUNCE_TIME_OFF);
writel(((keypad->n_cols - 1) << KEYSCAN_MATRIX_DIM_X_SHIFT) |
((keypad->n_rows - 1) << KEYSCAN_MATRIX_DIM_Y_SHIFT),
keypad->base + KEYSCAN_MATRIX_DIM_OFF);
writel(KEYSCAN_CONFIG_ENABLE, keypad->base + KEYSCAN_CONFIG_OFF);
return 0;
}
static void keyscan_stop(struct st_keyscan *keypad)
{
writel(0, keypad->base + KEYSCAN_CONFIG_OFF);
clk_disable(keypad->clk);
}
static int keyscan_open(struct input_dev *dev)
{
struct st_keyscan *keypad = input_get_drvdata(dev);
return keyscan_start(keypad);
}
static void keyscan_close(struct input_dev *dev)
{
struct st_keyscan *keypad = input_get_drvdata(dev);
keyscan_stop(keypad);
}
static int keypad_matrix_key_parse_dt(struct st_keyscan *keypad_data)
{
struct device *dev = keypad_data->input_dev->dev.parent;
struct device_node *np = dev->of_node;
int error;
error = matrix_keypad_parse_properties(dev, &keypad_data->n_rows,
&keypad_data->n_cols);
if (error) {
dev_err(dev, "failed to parse keypad params\n");
return error;
}
of_property_read_u32(np, "st,debounce-us", &keypad_data->debounce_us);
dev_dbg(dev, "n_rows=%d n_col=%d debounce=%d\n",
keypad_data->n_rows, keypad_data->n_cols,
keypad_data->debounce_us);
return 0;
}
static int keyscan_probe(struct platform_device *pdev)
{
struct st_keyscan *keypad_data;
struct input_dev *input_dev;
int error;
if (!pdev->dev.of_node) {
dev_err(&pdev->dev, "no DT data present\n");
return -EINVAL;
}
keypad_data = devm_kzalloc(&pdev->dev, sizeof(*keypad_data),
GFP_KERNEL);
if (!keypad_data)
return -ENOMEM;
input_dev = devm_input_allocate_device(&pdev->dev);
if (!input_dev) {
dev_err(&pdev->dev, "failed to allocate the input device\n");
return -ENOMEM;
}
input_dev->name = pdev->name;
input_dev->phys = "keyscan-keys/input0";
input_dev->dev.parent = &pdev->dev;
input_dev->open = keyscan_open;
input_dev->close = keyscan_close;
input_dev->id.bustype = BUS_HOST;
keypad_data->input_dev = input_dev;
error = keypad_matrix_key_parse_dt(keypad_data);
if (error)
return error;
error = matrix_keypad_build_keymap(NULL, NULL,
keypad_data->n_rows,
keypad_data->n_cols,
NULL, input_dev);
if (error) {
dev_err(&pdev->dev, "failed to build keymap\n");
return error;
}
input_set_drvdata(input_dev, keypad_data);
keypad_data->base = devm_platform_get_and_ioremap_resource(pdev, 0, NULL);
if (IS_ERR(keypad_data->base))
return PTR_ERR(keypad_data->base);
keypad_data->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(keypad_data->clk)) {
dev_err(&pdev->dev, "cannot get clock\n");
return PTR_ERR(keypad_data->clk);
}
error = clk_enable(keypad_data->clk);
if (error) {
dev_err(&pdev->dev, "failed to enable clock\n");
return error;
}
keyscan_stop(keypad_data);
keypad_data->irq = platform_get_irq(pdev, 0);
if (keypad_data->irq < 0)
return -EINVAL;
error = devm_request_irq(&pdev->dev, keypad_data->irq, keyscan_isr, 0,
pdev->name, keypad_data);
if (error) {
dev_err(&pdev->dev, "failed to request IRQ\n");
return error;
}
error = input_register_device(input_dev);
if (error) {
dev_err(&pdev->dev, "failed to register input device\n");
return error;
}
platform_set_drvdata(pdev, keypad_data);
device_set_wakeup_capable(&pdev->dev, 1);
return 0;
}
static int keyscan_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct st_keyscan *keypad = platform_get_drvdata(pdev);
struct input_dev *input = keypad->input_dev;
mutex_lock(&input->mutex);
if (device_may_wakeup(dev))
enable_irq_wake(keypad->irq);
else if (input_device_enabled(input))
keyscan_stop(keypad);
mutex_unlock(&input->mutex);
return 0;
}
static int keyscan_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct st_keyscan *keypad = platform_get_drvdata(pdev);
struct input_dev *input = keypad->input_dev;
int retval = 0;
mutex_lock(&input->mutex);
if (device_may_wakeup(dev))
disable_irq_wake(keypad->irq);
else if (input_device_enabled(input))
retval = keyscan_start(keypad);
mutex_unlock(&input->mutex);
return retval;
}
static DEFINE_SIMPLE_DEV_PM_OPS(keyscan_dev_pm_ops,
keyscan_suspend, keyscan_resume);
static const struct of_device_id keyscan_of_match[] = {
{ .compatible = "st,sti-keyscan" },
{ },
};
MODULE_DEVICE_TABLE(of, keyscan_of_match);
static struct platform_driver keyscan_device_driver = {
.probe = keyscan_probe,
.driver = {
.name = "st-keyscan",
.pm = pm_sleep_ptr(&keyscan_dev_pm_ops),
.of_match_table = keyscan_of_match,
}
};
module_platform_driver(keyscan_device_driver);
MODULE_AUTHOR("Stuart Menefy <[email protected]>");
MODULE_DESCRIPTION("STMicroelectronics keyscan device driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/st-keyscan.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* qt2160.c - Atmel AT42QT2160 Touch Sense Controller
*
* Copyright (C) 2009 Raphael Derosso Pereira <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#define QT2160_VALID_CHIPID 0x11
#define QT2160_CMD_CHIPID 0
#define QT2160_CMD_CODEVER 1
#define QT2160_CMD_GSTAT 2
#define QT2160_CMD_KEYS3 3
#define QT2160_CMD_KEYS4 4
#define QT2160_CMD_SLIDE 5
#define QT2160_CMD_GPIOS 6
#define QT2160_CMD_SUBVER 7
#define QT2160_CMD_CALIBRATE 10
#define QT2160_CMD_DRIVE_X 70
#define QT2160_CMD_PWMEN_X 74
#define QT2160_CMD_PWM_DUTY 76
#define QT2160_NUM_LEDS_X 8
#define QT2160_CYCLE_INTERVAL 2000 /* msec - 2 sec */
static unsigned char qt2160_key2code[] = {
KEY_0, KEY_1, KEY_2, KEY_3,
KEY_4, KEY_5, KEY_6, KEY_7,
KEY_8, KEY_9, KEY_A, KEY_B,
KEY_C, KEY_D, KEY_E, KEY_F,
};
#ifdef CONFIG_LEDS_CLASS
struct qt2160_led {
struct qt2160_data *qt2160;
struct led_classdev cdev;
char name[32];
int id;
enum led_brightness brightness;
};
#endif
struct qt2160_data {
struct i2c_client *client;
struct input_dev *input;
unsigned short keycodes[ARRAY_SIZE(qt2160_key2code)];
u16 key_matrix;
#ifdef CONFIG_LEDS_CLASS
struct qt2160_led leds[QT2160_NUM_LEDS_X];
#endif
};
static int qt2160_read(struct i2c_client *client, u8 reg);
static int qt2160_write(struct i2c_client *client, u8 reg, u8 data);
#ifdef CONFIG_LEDS_CLASS
static int qt2160_led_set(struct led_classdev *cdev,
enum led_brightness value)
{
struct qt2160_led *led = container_of(cdev, struct qt2160_led, cdev);
struct qt2160_data *qt2160 = led->qt2160;
struct i2c_client *client = qt2160->client;
u32 drive, pwmen;
if (value != led->brightness) {
drive = qt2160_read(client, QT2160_CMD_DRIVE_X);
pwmen = qt2160_read(client, QT2160_CMD_PWMEN_X);
if (value != LED_OFF) {
drive |= BIT(led->id);
pwmen |= BIT(led->id);
} else {
drive &= ~BIT(led->id);
pwmen &= ~BIT(led->id);
}
qt2160_write(client, QT2160_CMD_DRIVE_X, drive);
qt2160_write(client, QT2160_CMD_PWMEN_X, pwmen);
/*
* Changing this register will change the brightness
* of every LED in the qt2160. It's a HW limitation.
*/
if (value != LED_OFF)
qt2160_write(client, QT2160_CMD_PWM_DUTY, value);
led->brightness = value;
}
return 0;
}
#endif /* CONFIG_LEDS_CLASS */
static int qt2160_read_block(struct i2c_client *client,
u8 inireg, u8 *buffer, unsigned int count)
{
int error, idx = 0;
/*
* Can't use SMBus block data read. Check for I2C functionality to speed
* things up whenever possible. Otherwise we will be forced to read
* sequentially.
*/
if (i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
error = i2c_smbus_write_byte(client, inireg + idx);
if (error) {
dev_err(&client->dev,
"couldn't send request. Returned %d\n", error);
return error;
}
error = i2c_master_recv(client, buffer, count);
if (error != count) {
dev_err(&client->dev,
"couldn't read registers. Returned %d bytes\n", error);
return error;
}
} else {
while (count--) {
int data;
error = i2c_smbus_write_byte(client, inireg + idx);
if (error) {
dev_err(&client->dev,
"couldn't send request. Returned %d\n", error);
return error;
}
data = i2c_smbus_read_byte(client);
if (data < 0) {
dev_err(&client->dev,
"couldn't read register. Returned %d\n", data);
return data;
}
buffer[idx++] = data;
}
}
return 0;
}
static void qt2160_get_key_matrix(struct input_dev *input)
{
struct qt2160_data *qt2160 = input_get_drvdata(input);
struct i2c_client *client = qt2160->client;
u8 regs[6];
u16 old_matrix, new_matrix;
int ret, i, mask;
dev_dbg(&client->dev, "requesting keys...\n");
/*
* Read all registers from General Status Register
* to GPIOs register
*/
ret = qt2160_read_block(client, QT2160_CMD_GSTAT, regs, 6);
if (ret) {
dev_err(&client->dev,
"could not perform chip read.\n");
return;
}
old_matrix = qt2160->key_matrix;
qt2160->key_matrix = new_matrix = (regs[2] << 8) | regs[1];
mask = 0x01;
for (i = 0; i < 16; ++i, mask <<= 1) {
int keyval = new_matrix & mask;
if ((old_matrix & mask) != keyval) {
input_report_key(input, qt2160->keycodes[i], keyval);
dev_dbg(&client->dev, "key %d %s\n",
i, keyval ? "pressed" : "released");
}
}
input_sync(input);
}
static irqreturn_t qt2160_irq(int irq, void *data)
{
struct input_dev *input = data;
qt2160_get_key_matrix(input);
return IRQ_HANDLED;
}
static int qt2160_read(struct i2c_client *client, u8 reg)
{
int ret;
ret = i2c_smbus_write_byte(client, reg);
if (ret) {
dev_err(&client->dev,
"couldn't send request. Returned %d\n", ret);
return ret;
}
ret = i2c_smbus_read_byte(client);
if (ret < 0) {
dev_err(&client->dev,
"couldn't read register. Returned %d\n", ret);
return ret;
}
return ret;
}
static int qt2160_write(struct i2c_client *client, u8 reg, u8 data)
{
int ret;
ret = i2c_smbus_write_byte_data(client, reg, data);
if (ret < 0)
dev_err(&client->dev,
"couldn't write data. Returned %d\n", ret);
return ret;
}
#ifdef CONFIG_LEDS_CLASS
static int qt2160_register_leds(struct qt2160_data *qt2160)
{
struct i2c_client *client = qt2160->client;
int error;
int i;
for (i = 0; i < QT2160_NUM_LEDS_X; i++) {
struct qt2160_led *led = &qt2160->leds[i];
snprintf(led->name, sizeof(led->name), "qt2160:x%d", i);
led->cdev.name = led->name;
led->cdev.brightness_set_blocking = qt2160_led_set;
led->cdev.brightness = LED_OFF;
led->id = i;
led->qt2160 = qt2160;
error = devm_led_classdev_register(&client->dev, &led->cdev);
if (error)
return error;
}
/* Tur off LEDs */
qt2160_write(client, QT2160_CMD_DRIVE_X, 0);
qt2160_write(client, QT2160_CMD_PWMEN_X, 0);
qt2160_write(client, QT2160_CMD_PWM_DUTY, 0);
return 0;
}
#else
static inline int qt2160_register_leds(struct qt2160_data *qt2160)
{
return 0;
}
#endif
static bool qt2160_identify(struct i2c_client *client)
{
int id, ver, rev;
/* Read Chid ID to check if chip is valid */
id = qt2160_read(client, QT2160_CMD_CHIPID);
if (id != QT2160_VALID_CHIPID) {
dev_err(&client->dev, "ID %d not supported\n", id);
return false;
}
/* Read chip firmware version */
ver = qt2160_read(client, QT2160_CMD_CODEVER);
if (ver < 0) {
dev_err(&client->dev, "could not get firmware version\n");
return false;
}
/* Read chip firmware revision */
rev = qt2160_read(client, QT2160_CMD_SUBVER);
if (rev < 0) {
dev_err(&client->dev, "could not get firmware revision\n");
return false;
}
dev_info(&client->dev, "AT42QT2160 firmware version %d.%d.%d\n",
ver >> 4, ver & 0xf, rev);
return true;
}
static int qt2160_probe(struct i2c_client *client)
{
struct qt2160_data *qt2160;
struct input_dev *input;
int i;
int error;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE)) {
dev_err(&client->dev, "%s adapter not supported\n",
dev_driver_string(&client->adapter->dev));
return -ENODEV;
}
if (!qt2160_identify(client))
return -ENODEV;
/* Chip is valid and active. Allocate structure */
qt2160 = devm_kzalloc(&client->dev, sizeof(*qt2160), GFP_KERNEL);
if (!qt2160)
return -ENOMEM;
input = devm_input_allocate_device(&client->dev);
if (!input)
return -ENOMEM;
qt2160->client = client;
qt2160->input = input;
input->name = "AT42QT2160 Touch Sense Keyboard";
input->id.bustype = BUS_I2C;
input->keycode = qt2160->keycodes;
input->keycodesize = sizeof(qt2160->keycodes[0]);
input->keycodemax = ARRAY_SIZE(qt2160_key2code);
__set_bit(EV_KEY, input->evbit);
__clear_bit(EV_REP, input->evbit);
for (i = 0; i < ARRAY_SIZE(qt2160_key2code); i++) {
qt2160->keycodes[i] = qt2160_key2code[i];
__set_bit(qt2160_key2code[i], input->keybit);
}
__clear_bit(KEY_RESERVED, input->keybit);
input_set_drvdata(input, qt2160);
/* Calibrate device */
error = qt2160_write(client, QT2160_CMD_CALIBRATE, 1);
if (error) {
dev_err(&client->dev, "failed to calibrate device\n");
return error;
}
if (client->irq) {
error = devm_request_threaded_irq(&client->dev, client->irq,
NULL, qt2160_irq,
IRQF_ONESHOT,
"qt2160", input);
if (error) {
dev_err(&client->dev,
"failed to allocate irq %d\n", client->irq);
return error;
}
} else {
error = input_setup_polling(input, qt2160_get_key_matrix);
if (error) {
dev_err(&client->dev, "Failed to setup polling\n");
return error;
}
input_set_poll_interval(input, QT2160_CYCLE_INTERVAL);
}
error = qt2160_register_leds(qt2160);
if (error) {
dev_err(&client->dev, "Failed to register leds\n");
return error;
}
error = input_register_device(qt2160->input);
if (error) {
dev_err(&client->dev,
"Failed to register input device\n");
return error;
}
return 0;
}
static const struct i2c_device_id qt2160_idtable[] = {
{ "qt2160", 0, },
{ }
};
MODULE_DEVICE_TABLE(i2c, qt2160_idtable);
static struct i2c_driver qt2160_driver = {
.driver = {
.name = "qt2160",
},
.id_table = qt2160_idtable,
.probe = qt2160_probe,
};
module_i2c_driver(qt2160_driver);
MODULE_AUTHOR("Raphael Derosso Pereira <[email protected]>");
MODULE_DESCRIPTION("Driver for AT42QT2160 Touch Sensor");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/qt2160.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* LoCoMo keyboard driver for Linux-based ARM PDAs:
* - SHARP Zaurus Collie (SL-5500)
* - SHARP Zaurus Poodle (SL-5600)
*
* Copyright (c) 2005 John Lenz
* Based on from xtkbd.c
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <asm/hardware/locomo.h>
#include <asm/irq.h>
MODULE_AUTHOR("John Lenz <[email protected]>");
MODULE_DESCRIPTION("LoCoMo keyboard driver");
MODULE_LICENSE("GPL");
#define LOCOMOKBD_NUMKEYS 128
#define KEY_ACTIVITY KEY_F16
#define KEY_CONTACT KEY_F18
#define KEY_CENTER KEY_F15
static const unsigned char
locomokbd_keycode[LOCOMOKBD_NUMKEYS] = {
0, KEY_ESC, KEY_ACTIVITY, 0, 0, 0, 0, 0, 0, 0, /* 0 - 9 */
0, 0, 0, 0, 0, 0, 0, KEY_MENU, KEY_HOME, KEY_CONTACT, /* 10 - 19 */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 20 - 29 */
0, 0, 0, KEY_CENTER, 0, KEY_MAIL, 0, 0, 0, 0, /* 30 - 39 */
0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_RIGHT, /* 40 - 49 */
KEY_UP, KEY_LEFT, 0, 0, KEY_P, 0, KEY_O, KEY_I, KEY_Y, KEY_T, /* 50 - 59 */
KEY_E, KEY_W, 0, 0, 0, 0, KEY_DOWN, KEY_ENTER, 0, 0, /* 60 - 69 */
KEY_BACKSPACE, 0, KEY_L, KEY_U, KEY_H, KEY_R, KEY_D, KEY_Q, 0, 0, /* 70 - 79 */
0, 0, 0, 0, 0, 0, KEY_ENTER, KEY_RIGHTSHIFT, KEY_K, KEY_J, /* 80 - 89 */
KEY_G, KEY_F, KEY_X, KEY_S, 0, 0, 0, 0, 0, 0, /* 90 - 99 */
0, 0, KEY_DOT, 0, KEY_COMMA, KEY_N, KEY_B, KEY_C, KEY_Z, KEY_A, /* 100 - 109 */
KEY_LEFTSHIFT, KEY_TAB, KEY_LEFTCTRL, 0, 0, 0, 0, 0, 0, 0, /* 110 - 119 */
KEY_M, KEY_SPACE, KEY_V, KEY_APOSTROPHE, KEY_SLASH, 0, 0, 0 /* 120 - 128 */
};
#define KB_ROWS 16
#define KB_COLS 8
#define KB_ROWMASK(r) (1 << (r))
#define SCANCODE(c,r) ( ((c)<<4) + (r) + 1 )
#define KB_DELAY 8
#define SCAN_INTERVAL (HZ/10)
struct locomokbd {
unsigned char keycode[LOCOMOKBD_NUMKEYS];
struct input_dev *input;
char phys[32];
unsigned long base;
spinlock_t lock;
struct timer_list timer;
unsigned long suspend_jiffies;
unsigned int count_cancel;
};
/* helper functions for reading the keyboard matrix */
static inline void locomokbd_charge_all(unsigned long membase)
{
locomo_writel(0x00FF, membase + LOCOMO_KSC);
}
static inline void locomokbd_activate_all(unsigned long membase)
{
unsigned long r;
locomo_writel(0, membase + LOCOMO_KSC);
r = locomo_readl(membase + LOCOMO_KIC);
r &= 0xFEFF;
locomo_writel(r, membase + LOCOMO_KIC);
}
static inline void locomokbd_activate_col(unsigned long membase, int col)
{
unsigned short nset;
unsigned short nbset;
nset = 0xFF & ~(1 << col);
nbset = (nset << 8) + nset;
locomo_writel(nbset, membase + LOCOMO_KSC);
}
static inline void locomokbd_reset_col(unsigned long membase, int col)
{
unsigned short nbset;
nbset = ((0xFF & ~(1 << col)) << 8) + 0xFF;
locomo_writel(nbset, membase + LOCOMO_KSC);
}
/*
* The LoCoMo keyboard only generates interrupts when a key is pressed.
* So when a key is pressed, we enable a timer. This timer scans the
* keyboard, and this is how we detect when the key is released.
*/
/* Scan the hardware keyboard and push any changes up through the input layer */
static void locomokbd_scankeyboard(struct locomokbd *locomokbd)
{
unsigned int row, col, rowd;
unsigned long flags;
unsigned int num_pressed;
unsigned long membase = locomokbd->base;
spin_lock_irqsave(&locomokbd->lock, flags);
locomokbd_charge_all(membase);
num_pressed = 0;
for (col = 0; col < KB_COLS; col++) {
locomokbd_activate_col(membase, col);
udelay(KB_DELAY);
rowd = ~locomo_readl(membase + LOCOMO_KIB);
for (row = 0; row < KB_ROWS; row++) {
unsigned int scancode, pressed, key;
scancode = SCANCODE(col, row);
pressed = rowd & KB_ROWMASK(row);
key = locomokbd->keycode[scancode];
input_report_key(locomokbd->input, key, pressed);
if (likely(!pressed))
continue;
num_pressed++;
/* The "Cancel/ESC" key is labeled "On/Off" on
* Collie and Poodle and should suspend the device
* if it was pressed for more than a second. */
if (unlikely(key == KEY_ESC)) {
if (!time_after(jiffies,
locomokbd->suspend_jiffies + HZ))
continue;
if (locomokbd->count_cancel++
!= (HZ/SCAN_INTERVAL + 1))
continue;
input_event(locomokbd->input, EV_PWR,
KEY_SUSPEND, 1);
locomokbd->suspend_jiffies = jiffies;
} else
locomokbd->count_cancel = 0;
}
locomokbd_reset_col(membase, col);
}
locomokbd_activate_all(membase);
input_sync(locomokbd->input);
/* if any keys are pressed, enable the timer */
if (num_pressed)
mod_timer(&locomokbd->timer, jiffies + SCAN_INTERVAL);
else
locomokbd->count_cancel = 0;
spin_unlock_irqrestore(&locomokbd->lock, flags);
}
/*
* LoCoMo keyboard interrupt handler.
*/
static irqreturn_t locomokbd_interrupt(int irq, void *dev_id)
{
struct locomokbd *locomokbd = dev_id;
u16 r;
r = locomo_readl(locomokbd->base + LOCOMO_KIC);
if ((r & 0x0001) == 0)
return IRQ_HANDLED;
locomo_writel(r & ~0x0100, locomokbd->base + LOCOMO_KIC); /* Ack */
/** wait chattering delay **/
udelay(100);
locomokbd_scankeyboard(locomokbd);
return IRQ_HANDLED;
}
/*
* LoCoMo timer checking for released keys
*/
static void locomokbd_timer_callback(struct timer_list *t)
{
struct locomokbd *locomokbd = from_timer(locomokbd, t, timer);
locomokbd_scankeyboard(locomokbd);
}
static int locomokbd_open(struct input_dev *dev)
{
struct locomokbd *locomokbd = input_get_drvdata(dev);
u16 r;
r = locomo_readl(locomokbd->base + LOCOMO_KIC) | 0x0010;
locomo_writel(r, locomokbd->base + LOCOMO_KIC);
return 0;
}
static void locomokbd_close(struct input_dev *dev)
{
struct locomokbd *locomokbd = input_get_drvdata(dev);
u16 r;
r = locomo_readl(locomokbd->base + LOCOMO_KIC) & ~0x0010;
locomo_writel(r, locomokbd->base + LOCOMO_KIC);
}
static int locomokbd_probe(struct locomo_dev *dev)
{
struct locomokbd *locomokbd;
struct input_dev *input_dev;
int i, err;
locomokbd = kzalloc(sizeof(struct locomokbd), GFP_KERNEL);
input_dev = input_allocate_device();
if (!locomokbd || !input_dev) {
err = -ENOMEM;
goto err_free_mem;
}
/* try and claim memory region */
if (!request_mem_region((unsigned long) dev->mapbase,
dev->length,
LOCOMO_DRIVER_NAME(dev))) {
err = -EBUSY;
printk(KERN_ERR "locomokbd: Can't acquire access to io memory for keyboard\n");
goto err_free_mem;
}
locomo_set_drvdata(dev, locomokbd);
locomokbd->base = (unsigned long) dev->mapbase;
spin_lock_init(&locomokbd->lock);
timer_setup(&locomokbd->timer, locomokbd_timer_callback, 0);
locomokbd->suspend_jiffies = jiffies;
locomokbd->input = input_dev;
strcpy(locomokbd->phys, "locomokbd/input0");
input_dev->name = "LoCoMo keyboard";
input_dev->phys = locomokbd->phys;
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->open = locomokbd_open;
input_dev->close = locomokbd_close;
input_dev->dev.parent = &dev->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP) |
BIT_MASK(EV_PWR);
input_dev->keycode = locomokbd->keycode;
input_dev->keycodesize = sizeof(locomokbd_keycode[0]);
input_dev->keycodemax = ARRAY_SIZE(locomokbd_keycode);
input_set_drvdata(input_dev, locomokbd);
memcpy(locomokbd->keycode, locomokbd_keycode, sizeof(locomokbd->keycode));
for (i = 0; i < LOCOMOKBD_NUMKEYS; i++)
set_bit(locomokbd->keycode[i], input_dev->keybit);
clear_bit(0, input_dev->keybit);
/* attempt to get the interrupt */
err = request_irq(dev->irq[0], locomokbd_interrupt, 0, "locomokbd", locomokbd);
if (err) {
printk(KERN_ERR "locomokbd: Can't get irq for keyboard\n");
goto err_release_region;
}
err = input_register_device(locomokbd->input);
if (err)
goto err_free_irq;
return 0;
err_free_irq:
free_irq(dev->irq[0], locomokbd);
err_release_region:
release_mem_region((unsigned long) dev->mapbase, dev->length);
locomo_set_drvdata(dev, NULL);
err_free_mem:
input_free_device(input_dev);
kfree(locomokbd);
return err;
}
static void locomokbd_remove(struct locomo_dev *dev)
{
struct locomokbd *locomokbd = locomo_get_drvdata(dev);
free_irq(dev->irq[0], locomokbd);
timer_shutdown_sync(&locomokbd->timer);
input_unregister_device(locomokbd->input);
locomo_set_drvdata(dev, NULL);
release_mem_region((unsigned long) dev->mapbase, dev->length);
kfree(locomokbd);
}
static struct locomo_driver keyboard_driver = {
.drv = {
.name = "locomokbd"
},
.devid = LOCOMO_DEVID_KEYBOARD,
.probe = locomokbd_probe,
.remove = locomokbd_remove,
};
static int __init locomokbd_init(void)
{
return locomo_driver_register(&keyboard_driver);
}
static void __exit locomokbd_exit(void)
{
locomo_driver_unregister(&keyboard_driver);
}
module_init(locomokbd_init);
module_exit(locomokbd_exit);
|
linux-master
|
drivers/input/keyboard/locomokbd.c
|
// SPDX-License-Identifier: GPL-2.0-only
//
// Copyright (C) 2021-2022 Samuel Holland <[email protected]>
#include <linux/crc8.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/of.h>
#include <linux/regulator/consumer.h>
#include <linux/types.h>
#define DRV_NAME "pinephone-keyboard"
#define PPKB_CRC8_POLYNOMIAL 0x07
#define PPKB_DEVICE_ID_HI 0x00
#define PPKB_DEVICE_ID_HI_VALUE 'K'
#define PPKB_DEVICE_ID_LO 0x01
#define PPKB_DEVICE_ID_LO_VALUE 'B'
#define PPKB_FW_REVISION 0x02
#define PPKB_FW_FEATURES 0x03
#define PPKB_MATRIX_SIZE 0x06
#define PPKB_SCAN_CRC 0x07
#define PPKB_SCAN_DATA 0x08
#define PPKB_SYS_CONFIG 0x20
#define PPKB_SYS_CONFIG_DISABLE_SCAN BIT(0)
#define PPKB_SYS_SMBUS_COMMAND 0x21
#define PPKB_SYS_SMBUS_DATA 0x22
#define PPKB_SYS_COMMAND 0x23
#define PPKB_SYS_COMMAND_SMBUS_READ 0x91
#define PPKB_SYS_COMMAND_SMBUS_WRITE 0xa1
#define PPKB_ROWS 6
#define PPKB_COLS 12
/* Size of the scan buffer, including the CRC byte at the beginning. */
#define PPKB_BUF_LEN (1 + PPKB_COLS)
static const uint32_t ppkb_keymap[] = {
KEY(0, 0, KEY_ESC),
KEY(0, 1, KEY_1),
KEY(0, 2, KEY_2),
KEY(0, 3, KEY_3),
KEY(0, 4, KEY_4),
KEY(0, 5, KEY_5),
KEY(0, 6, KEY_6),
KEY(0, 7, KEY_7),
KEY(0, 8, KEY_8),
KEY(0, 9, KEY_9),
KEY(0, 10, KEY_0),
KEY(0, 11, KEY_BACKSPACE),
KEY(1, 0, KEY_TAB),
KEY(1, 1, KEY_Q),
KEY(1, 2, KEY_W),
KEY(1, 3, KEY_E),
KEY(1, 4, KEY_R),
KEY(1, 5, KEY_T),
KEY(1, 6, KEY_Y),
KEY(1, 7, KEY_U),
KEY(1, 8, KEY_I),
KEY(1, 9, KEY_O),
KEY(1, 10, KEY_P),
KEY(1, 11, KEY_ENTER),
KEY(2, 0, KEY_LEFTMETA),
KEY(2, 1, KEY_A),
KEY(2, 2, KEY_S),
KEY(2, 3, KEY_D),
KEY(2, 4, KEY_F),
KEY(2, 5, KEY_G),
KEY(2, 6, KEY_H),
KEY(2, 7, KEY_J),
KEY(2, 8, KEY_K),
KEY(2, 9, KEY_L),
KEY(2, 10, KEY_SEMICOLON),
KEY(3, 0, KEY_LEFTSHIFT),
KEY(3, 1, KEY_Z),
KEY(3, 2, KEY_X),
KEY(3, 3, KEY_C),
KEY(3, 4, KEY_V),
KEY(3, 5, KEY_B),
KEY(3, 6, KEY_N),
KEY(3, 7, KEY_M),
KEY(3, 8, KEY_COMMA),
KEY(3, 9, KEY_DOT),
KEY(3, 10, KEY_SLASH),
KEY(4, 1, KEY_LEFTCTRL),
KEY(4, 4, KEY_SPACE),
KEY(4, 6, KEY_APOSTROPHE),
KEY(4, 8, KEY_RIGHTBRACE),
KEY(4, 9, KEY_LEFTBRACE),
KEY(5, 2, KEY_FN),
KEY(5, 3, KEY_LEFTALT),
KEY(5, 5, KEY_RIGHTALT),
/* FN layer */
KEY(PPKB_ROWS + 0, 0, KEY_FN_ESC),
KEY(PPKB_ROWS + 0, 1, KEY_F1),
KEY(PPKB_ROWS + 0, 2, KEY_F2),
KEY(PPKB_ROWS + 0, 3, KEY_F3),
KEY(PPKB_ROWS + 0, 4, KEY_F4),
KEY(PPKB_ROWS + 0, 5, KEY_F5),
KEY(PPKB_ROWS + 0, 6, KEY_F6),
KEY(PPKB_ROWS + 0, 7, KEY_F7),
KEY(PPKB_ROWS + 0, 8, KEY_F8),
KEY(PPKB_ROWS + 0, 9, KEY_F9),
KEY(PPKB_ROWS + 0, 10, KEY_F10),
KEY(PPKB_ROWS + 0, 11, KEY_DELETE),
KEY(PPKB_ROWS + 1, 10, KEY_PAGEUP),
KEY(PPKB_ROWS + 2, 0, KEY_SYSRQ),
KEY(PPKB_ROWS + 2, 9, KEY_PAGEDOWN),
KEY(PPKB_ROWS + 2, 10, KEY_INSERT),
KEY(PPKB_ROWS + 3, 0, KEY_LEFTSHIFT),
KEY(PPKB_ROWS + 3, 8, KEY_HOME),
KEY(PPKB_ROWS + 3, 9, KEY_UP),
KEY(PPKB_ROWS + 3, 10, KEY_END),
KEY(PPKB_ROWS + 4, 1, KEY_LEFTCTRL),
KEY(PPKB_ROWS + 4, 6, KEY_LEFT),
KEY(PPKB_ROWS + 4, 8, KEY_RIGHT),
KEY(PPKB_ROWS + 4, 9, KEY_DOWN),
KEY(PPKB_ROWS + 5, 3, KEY_LEFTALT),
KEY(PPKB_ROWS + 5, 5, KEY_RIGHTALT),
};
static const struct matrix_keymap_data ppkb_keymap_data = {
.keymap = ppkb_keymap,
.keymap_size = ARRAY_SIZE(ppkb_keymap),
};
struct pinephone_keyboard {
struct i2c_adapter adapter;
struct input_dev *input;
u8 buf[2][PPKB_BUF_LEN];
u8 crc_table[CRC8_TABLE_SIZE];
u8 fn_state[PPKB_COLS];
bool buf_swap;
bool fn_pressed;
};
static int ppkb_adap_smbus_xfer(struct i2c_adapter *adap, u16 addr,
unsigned short flags, char read_write,
u8 command, int size,
union i2c_smbus_data *data)
{
struct i2c_client *client = adap->algo_data;
u8 buf[3];
int ret;
buf[0] = command;
buf[1] = data->byte;
buf[2] = read_write == I2C_SMBUS_READ ? PPKB_SYS_COMMAND_SMBUS_READ
: PPKB_SYS_COMMAND_SMBUS_WRITE;
ret = i2c_smbus_write_i2c_block_data(client, PPKB_SYS_SMBUS_COMMAND,
sizeof(buf), buf);
if (ret)
return ret;
/* Read back the command status until it passes or fails. */
do {
usleep_range(300, 500);
ret = i2c_smbus_read_byte_data(client, PPKB_SYS_COMMAND);
} while (ret == buf[2]);
if (ret < 0)
return ret;
/* Commands return 0x00 on success and 0xff on failure. */
if (ret)
return -EIO;
if (read_write == I2C_SMBUS_READ) {
ret = i2c_smbus_read_byte_data(client, PPKB_SYS_SMBUS_DATA);
if (ret < 0)
return ret;
data->byte = ret;
}
return 0;
}
static u32 ppkg_adap_functionality(struct i2c_adapter *adap)
{
return I2C_FUNC_SMBUS_BYTE_DATA;
}
static const struct i2c_algorithm ppkb_adap_algo = {
.smbus_xfer = ppkb_adap_smbus_xfer,
.functionality = ppkg_adap_functionality,
};
static void ppkb_update(struct i2c_client *client)
{
struct pinephone_keyboard *ppkb = i2c_get_clientdata(client);
unsigned short *keymap = ppkb->input->keycode;
int row_shift = get_count_order(PPKB_COLS);
u8 *old_buf = ppkb->buf[!ppkb->buf_swap];
u8 *new_buf = ppkb->buf[ppkb->buf_swap];
int col, crc, ret, row;
struct device *dev = &client->dev;
ret = i2c_smbus_read_i2c_block_data(client, PPKB_SCAN_CRC,
PPKB_BUF_LEN, new_buf);
if (ret != PPKB_BUF_LEN) {
dev_err(dev, "Failed to read scan data: %d\n", ret);
return;
}
crc = crc8(ppkb->crc_table, &new_buf[1], PPKB_COLS, CRC8_INIT_VALUE);
if (crc != new_buf[0]) {
dev_err(dev, "Bad scan data (%02x != %02x)\n", crc, new_buf[0]);
return;
}
ppkb->buf_swap = !ppkb->buf_swap;
for (col = 0; col < PPKB_COLS; ++col) {
u8 old = old_buf[1 + col];
u8 new = new_buf[1 + col];
u8 changed = old ^ new;
if (!changed)
continue;
for (row = 0; row < PPKB_ROWS; ++row) {
u8 mask = BIT(row);
u8 value = new & mask;
unsigned short code;
bool fn_state;
if (!(changed & mask))
continue;
/*
* Save off the FN key state when the key was pressed,
* and use that to determine the code during a release.
*/
fn_state = value ? ppkb->fn_pressed : ppkb->fn_state[col] & mask;
if (fn_state)
ppkb->fn_state[col] ^= mask;
/* The FN layer is a second set of rows. */
code = MATRIX_SCAN_CODE(fn_state ? PPKB_ROWS + row : row,
col, row_shift);
input_event(ppkb->input, EV_MSC, MSC_SCAN, code);
input_report_key(ppkb->input, keymap[code], value);
if (keymap[code] == KEY_FN)
ppkb->fn_pressed = value;
}
}
input_sync(ppkb->input);
}
static irqreturn_t ppkb_irq_thread(int irq, void *data)
{
struct i2c_client *client = data;
ppkb_update(client);
return IRQ_HANDLED;
}
static int ppkb_set_scan(struct i2c_client *client, bool enable)
{
struct device *dev = &client->dev;
int ret, val;
ret = i2c_smbus_read_byte_data(client, PPKB_SYS_CONFIG);
if (ret < 0) {
dev_err(dev, "Failed to read config: %d\n", ret);
return ret;
}
if (enable)
val = ret & ~PPKB_SYS_CONFIG_DISABLE_SCAN;
else
val = ret | PPKB_SYS_CONFIG_DISABLE_SCAN;
ret = i2c_smbus_write_byte_data(client, PPKB_SYS_CONFIG, val);
if (ret) {
dev_err(dev, "Failed to write config: %d\n", ret);
return ret;
}
return 0;
}
static int ppkb_open(struct input_dev *input)
{
struct i2c_client *client = input_get_drvdata(input);
int error;
error = ppkb_set_scan(client, true);
if (error)
return error;
return 0;
}
static void ppkb_close(struct input_dev *input)
{
struct i2c_client *client = input_get_drvdata(input);
ppkb_set_scan(client, false);
}
static int ppkb_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
unsigned int phys_rows, phys_cols;
struct pinephone_keyboard *ppkb;
u8 info[PPKB_MATRIX_SIZE + 1];
struct device_node *i2c_bus;
int ret;
int error;
error = devm_regulator_get_enable(dev, "vbat");
if (error) {
dev_err(dev, "Failed to get VBAT supply: %d\n", error);
return error;
}
ret = i2c_smbus_read_i2c_block_data(client, 0, sizeof(info), info);
if (ret != sizeof(info)) {
error = ret < 0 ? ret : -EIO;
dev_err(dev, "Failed to read device ID: %d\n", error);
return error;
}
if (info[PPKB_DEVICE_ID_HI] != PPKB_DEVICE_ID_HI_VALUE ||
info[PPKB_DEVICE_ID_LO] != PPKB_DEVICE_ID_LO_VALUE) {
dev_warn(dev, "Unexpected device ID: %#02x %#02x\n",
info[PPKB_DEVICE_ID_HI], info[PPKB_DEVICE_ID_LO]);
return -ENODEV;
}
dev_info(dev, "Found firmware version %d.%d features %#x\n",
info[PPKB_FW_REVISION] >> 4,
info[PPKB_FW_REVISION] & 0xf,
info[PPKB_FW_FEATURES]);
phys_rows = info[PPKB_MATRIX_SIZE] & 0xf;
phys_cols = info[PPKB_MATRIX_SIZE] >> 4;
if (phys_rows != PPKB_ROWS || phys_cols != PPKB_COLS) {
dev_err(dev, "Unexpected keyboard size %ux%u\n",
phys_rows, phys_cols);
return -EINVAL;
}
/* Disable scan by default to save power. */
error = ppkb_set_scan(client, false);
if (error)
return error;
ppkb = devm_kzalloc(dev, sizeof(*ppkb), GFP_KERNEL);
if (!ppkb)
return -ENOMEM;
i2c_set_clientdata(client, ppkb);
i2c_bus = of_get_child_by_name(dev->of_node, "i2c");
if (i2c_bus) {
ppkb->adapter.owner = THIS_MODULE;
ppkb->adapter.algo = &ppkb_adap_algo;
ppkb->adapter.algo_data = client;
ppkb->adapter.dev.parent = dev;
ppkb->adapter.dev.of_node = i2c_bus;
strscpy(ppkb->adapter.name, DRV_NAME, sizeof(ppkb->adapter.name));
error = devm_i2c_add_adapter(dev, &ppkb->adapter);
if (error) {
dev_err(dev, "Failed to add I2C adapter: %d\n", error);
return error;
}
}
crc8_populate_msb(ppkb->crc_table, PPKB_CRC8_POLYNOMIAL);
ppkb->input = devm_input_allocate_device(dev);
if (!ppkb->input)
return -ENOMEM;
input_set_drvdata(ppkb->input, client);
ppkb->input->name = "PinePhone Keyboard";
ppkb->input->phys = DRV_NAME "/input0";
ppkb->input->id.bustype = BUS_I2C;
ppkb->input->open = ppkb_open;
ppkb->input->close = ppkb_close;
input_set_capability(ppkb->input, EV_MSC, MSC_SCAN);
__set_bit(EV_REP, ppkb->input->evbit);
error = matrix_keypad_build_keymap(&ppkb_keymap_data, NULL,
2 * PPKB_ROWS, PPKB_COLS, NULL,
ppkb->input);
if (error) {
dev_err(dev, "Failed to build keymap: %d\n", error);
return error;
}
error = input_register_device(ppkb->input);
if (error) {
dev_err(dev, "Failed to register input: %d\n", error);
return error;
}
error = devm_request_threaded_irq(dev, client->irq,
NULL, ppkb_irq_thread,
IRQF_ONESHOT, client->name, client);
if (error) {
dev_err(dev, "Failed to request IRQ: %d\n", error);
return error;
}
return 0;
}
static const struct of_device_id ppkb_of_match[] = {
{ .compatible = "pine64,pinephone-keyboard" },
{ }
};
MODULE_DEVICE_TABLE(of, ppkb_of_match);
static struct i2c_driver ppkb_driver = {
.probe = ppkb_probe,
.driver = {
.name = DRV_NAME,
.of_match_table = ppkb_of_match,
},
};
module_i2c_driver(ppkb_driver);
MODULE_AUTHOR("Samuel Holland <[email protected]>");
MODULE_DESCRIPTION("Pine64 PinePhone keyboard driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/pinephone-keyboard.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* NXP LPC32xx SoC Key Scan Interface
*
* Authors:
* Kevin Wells <[email protected]>
* Roland Stigge <[email protected]>
*
* Copyright (C) 2010 NXP Semiconductors
* Copyright (C) 2012 Roland Stigge
*
* This controller supports square key matrices from 1x1 up to 8x8
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/input.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/input/matrix_keypad.h>
#define DRV_NAME "lpc32xx_keys"
/*
* Key scanner register offsets
*/
#define LPC32XX_KS_DEB(x) ((x) + 0x00)
#define LPC32XX_KS_STATE_COND(x) ((x) + 0x04)
#define LPC32XX_KS_IRQ(x) ((x) + 0x08)
#define LPC32XX_KS_SCAN_CTL(x) ((x) + 0x0C)
#define LPC32XX_KS_FAST_TST(x) ((x) + 0x10)
#define LPC32XX_KS_MATRIX_DIM(x) ((x) + 0x14) /* 1..8 */
#define LPC32XX_KS_DATA(x, y) ((x) + 0x40 + ((y) << 2))
#define LPC32XX_KSCAN_DEB_NUM_DEB_PASS(n) ((n) & 0xFF)
#define LPC32XX_KSCAN_SCOND_IN_IDLE 0x0
#define LPC32XX_KSCAN_SCOND_IN_SCANONCE 0x1
#define LPC32XX_KSCAN_SCOND_IN_IRQGEN 0x2
#define LPC32XX_KSCAN_SCOND_IN_SCAN_MATRIX 0x3
#define LPC32XX_KSCAN_IRQ_PENDING_CLR 0x1
#define LPC32XX_KSCAN_SCTRL_SCAN_DELAY(n) ((n) & 0xFF)
#define LPC32XX_KSCAN_FTST_FORCESCANONCE 0x1
#define LPC32XX_KSCAN_FTST_USE32K_CLK 0x2
#define LPC32XX_KSCAN_MSEL_SELECT(n) ((n) & 0xF)
struct lpc32xx_kscan_drv {
struct input_dev *input;
struct clk *clk;
void __iomem *kscan_base;
unsigned int irq;
u32 matrix_sz; /* Size of matrix in XxY, ie. 3 = 3x3 */
u32 deb_clks; /* Debounce clocks (based on 32KHz clock) */
u32 scan_delay; /* Scan delay (based on 32KHz clock) */
unsigned short *keymap; /* Pointer to key map for the scan matrix */
unsigned int row_shift;
u8 lastkeystates[8];
};
static void lpc32xx_mod_states(struct lpc32xx_kscan_drv *kscandat, int col)
{
struct input_dev *input = kscandat->input;
unsigned row, changed, scancode, keycode;
u8 key;
key = readl(LPC32XX_KS_DATA(kscandat->kscan_base, col));
changed = key ^ kscandat->lastkeystates[col];
kscandat->lastkeystates[col] = key;
for (row = 0; changed; row++, changed >>= 1) {
if (changed & 1) {
/* Key state changed, signal an event */
scancode = MATRIX_SCAN_CODE(row, col,
kscandat->row_shift);
keycode = kscandat->keymap[scancode];
input_event(input, EV_MSC, MSC_SCAN, scancode);
input_report_key(input, keycode, key & (1 << row));
}
}
}
static irqreturn_t lpc32xx_kscan_irq(int irq, void *dev_id)
{
struct lpc32xx_kscan_drv *kscandat = dev_id;
int i;
for (i = 0; i < kscandat->matrix_sz; i++)
lpc32xx_mod_states(kscandat, i);
writel(1, LPC32XX_KS_IRQ(kscandat->kscan_base));
input_sync(kscandat->input);
return IRQ_HANDLED;
}
static int lpc32xx_kscan_open(struct input_dev *dev)
{
struct lpc32xx_kscan_drv *kscandat = input_get_drvdata(dev);
int error;
error = clk_prepare_enable(kscandat->clk);
if (error)
return error;
writel(1, LPC32XX_KS_IRQ(kscandat->kscan_base));
return 0;
}
static void lpc32xx_kscan_close(struct input_dev *dev)
{
struct lpc32xx_kscan_drv *kscandat = input_get_drvdata(dev);
writel(1, LPC32XX_KS_IRQ(kscandat->kscan_base));
clk_disable_unprepare(kscandat->clk);
}
static int lpc32xx_parse_dt(struct device *dev,
struct lpc32xx_kscan_drv *kscandat)
{
struct device_node *np = dev->of_node;
u32 rows = 0, columns = 0;
int err;
err = matrix_keypad_parse_properties(dev, &rows, &columns);
if (err)
return err;
if (rows != columns) {
dev_err(dev, "rows and columns must be equal!\n");
return -EINVAL;
}
kscandat->matrix_sz = rows;
kscandat->row_shift = get_count_order(columns);
of_property_read_u32(np, "nxp,debounce-delay-ms", &kscandat->deb_clks);
of_property_read_u32(np, "nxp,scan-delay-ms", &kscandat->scan_delay);
if (!kscandat->deb_clks || !kscandat->scan_delay) {
dev_err(dev, "debounce or scan delay not specified\n");
return -EINVAL;
}
return 0;
}
static int lpc32xx_kscan_probe(struct platform_device *pdev)
{
struct lpc32xx_kscan_drv *kscandat;
struct input_dev *input;
size_t keymap_size;
int error;
int irq;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return -EINVAL;
kscandat = devm_kzalloc(&pdev->dev, sizeof(*kscandat),
GFP_KERNEL);
if (!kscandat)
return -ENOMEM;
error = lpc32xx_parse_dt(&pdev->dev, kscandat);
if (error) {
dev_err(&pdev->dev, "failed to parse device tree\n");
return error;
}
keymap_size = sizeof(kscandat->keymap[0]) *
(kscandat->matrix_sz << kscandat->row_shift);
kscandat->keymap = devm_kzalloc(&pdev->dev, keymap_size, GFP_KERNEL);
if (!kscandat->keymap)
return -ENOMEM;
kscandat->input = input = devm_input_allocate_device(&pdev->dev);
if (!input) {
dev_err(&pdev->dev, "failed to allocate input device\n");
return -ENOMEM;
}
/* Setup key input */
input->name = pdev->name;
input->phys = "lpc32xx/input0";
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
input->open = lpc32xx_kscan_open;
input->close = lpc32xx_kscan_close;
input->dev.parent = &pdev->dev;
input_set_capability(input, EV_MSC, MSC_SCAN);
error = matrix_keypad_build_keymap(NULL, NULL,
kscandat->matrix_sz,
kscandat->matrix_sz,
kscandat->keymap, kscandat->input);
if (error) {
dev_err(&pdev->dev, "failed to build keymap\n");
return error;
}
input_set_drvdata(kscandat->input, kscandat);
kscandat->kscan_base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(kscandat->kscan_base))
return PTR_ERR(kscandat->kscan_base);
/* Get the key scanner clock */
kscandat->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(kscandat->clk)) {
dev_err(&pdev->dev, "failed to get clock\n");
return PTR_ERR(kscandat->clk);
}
/* Configure the key scanner */
error = clk_prepare_enable(kscandat->clk);
if (error)
return error;
writel(kscandat->deb_clks, LPC32XX_KS_DEB(kscandat->kscan_base));
writel(kscandat->scan_delay, LPC32XX_KS_SCAN_CTL(kscandat->kscan_base));
writel(LPC32XX_KSCAN_FTST_USE32K_CLK,
LPC32XX_KS_FAST_TST(kscandat->kscan_base));
writel(kscandat->matrix_sz,
LPC32XX_KS_MATRIX_DIM(kscandat->kscan_base));
writel(1, LPC32XX_KS_IRQ(kscandat->kscan_base));
clk_disable_unprepare(kscandat->clk);
error = devm_request_irq(&pdev->dev, irq, lpc32xx_kscan_irq, 0,
pdev->name, kscandat);
if (error) {
dev_err(&pdev->dev, "failed to request irq\n");
return error;
}
error = input_register_device(kscandat->input);
if (error) {
dev_err(&pdev->dev, "failed to register input device\n");
return error;
}
platform_set_drvdata(pdev, kscandat);
return 0;
}
static int lpc32xx_kscan_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct lpc32xx_kscan_drv *kscandat = platform_get_drvdata(pdev);
struct input_dev *input = kscandat->input;
mutex_lock(&input->mutex);
if (input_device_enabled(input)) {
/* Clear IRQ and disable clock */
writel(1, LPC32XX_KS_IRQ(kscandat->kscan_base));
clk_disable_unprepare(kscandat->clk);
}
mutex_unlock(&input->mutex);
return 0;
}
static int lpc32xx_kscan_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct lpc32xx_kscan_drv *kscandat = platform_get_drvdata(pdev);
struct input_dev *input = kscandat->input;
int retval = 0;
mutex_lock(&input->mutex);
if (input_device_enabled(input)) {
/* Enable clock and clear IRQ */
retval = clk_prepare_enable(kscandat->clk);
if (retval == 0)
writel(1, LPC32XX_KS_IRQ(kscandat->kscan_base));
}
mutex_unlock(&input->mutex);
return retval;
}
static DEFINE_SIMPLE_DEV_PM_OPS(lpc32xx_kscan_pm_ops, lpc32xx_kscan_suspend,
lpc32xx_kscan_resume);
static const struct of_device_id lpc32xx_kscan_match[] = {
{ .compatible = "nxp,lpc3220-key" },
{},
};
MODULE_DEVICE_TABLE(of, lpc32xx_kscan_match);
static struct platform_driver lpc32xx_kscan_driver = {
.probe = lpc32xx_kscan_probe,
.driver = {
.name = DRV_NAME,
.pm = pm_sleep_ptr(&lpc32xx_kscan_pm_ops),
.of_match_table = lpc32xx_kscan_match,
}
};
module_platform_driver(lpc32xx_kscan_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Kevin Wells <[email protected]>");
MODULE_AUTHOR("Roland Stigge <[email protected]>");
MODULE_DESCRIPTION("Key scanner driver for LPC32XX devices");
|
linux-master
|
drivers/input/keyboard/lpc32xx-keys.c
|
// SPDX-License-Identifier: GPL-2.0
/*
* Microchip AT42QT1050 QTouch Sensor Controller
*
* Copyright (C) 2019 Pengutronix, Marco Felsch <[email protected]>
*
* Base on AT42QT1070 driver by:
* Bo Shen <[email protected]>
* Copyright (C) 2011 Atmel
*/
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/regmap.h>
/* Chip ID */
#define QT1050_CHIP_ID 0x00
#define QT1050_CHIP_ID_VER 0x46
/* Firmware version */
#define QT1050_FW_VERSION 0x01
/* Detection status */
#define QT1050_DET_STATUS 0x02
/* Key status */
#define QT1050_KEY_STATUS 0x03
/* Key Signals */
#define QT1050_KEY_SIGNAL_0_MSB 0x06
#define QT1050_KEY_SIGNAL_0_LSB 0x07
#define QT1050_KEY_SIGNAL_1_MSB 0x08
#define QT1050_KEY_SIGNAL_1_LSB 0x09
#define QT1050_KEY_SIGNAL_2_MSB 0x0c
#define QT1050_KEY_SIGNAL_2_LSB 0x0d
#define QT1050_KEY_SIGNAL_3_MSB 0x0e
#define QT1050_KEY_SIGNAL_3_LSB 0x0f
#define QT1050_KEY_SIGNAL_4_MSB 0x10
#define QT1050_KEY_SIGNAL_4_LSB 0x11
/* Reference data */
#define QT1050_REF_DATA_0_MSB 0x14
#define QT1050_REF_DATA_0_LSB 0x15
#define QT1050_REF_DATA_1_MSB 0x16
#define QT1050_REF_DATA_1_LSB 0x17
#define QT1050_REF_DATA_2_MSB 0x1a
#define QT1050_REF_DATA_2_LSB 0x1b
#define QT1050_REF_DATA_3_MSB 0x1c
#define QT1050_REF_DATA_3_LSB 0x1d
#define QT1050_REF_DATA_4_MSB 0x1e
#define QT1050_REF_DATA_4_LSB 0x1f
/* Negative threshold level */
#define QT1050_NTHR_0 0x21
#define QT1050_NTHR_1 0x22
#define QT1050_NTHR_2 0x24
#define QT1050_NTHR_3 0x25
#define QT1050_NTHR_4 0x26
/* Pulse / Scale */
#define QT1050_PULSE_SCALE_0 0x28
#define QT1050_PULSE_SCALE_1 0x29
#define QT1050_PULSE_SCALE_2 0x2b
#define QT1050_PULSE_SCALE_3 0x2c
#define QT1050_PULSE_SCALE_4 0x2d
/* Detection integrator counter / AKS */
#define QT1050_DI_AKS_0 0x2f
#define QT1050_DI_AKS_1 0x30
#define QT1050_DI_AKS_2 0x32
#define QT1050_DI_AKS_3 0x33
#define QT1050_DI_AKS_4 0x34
/* Charge Share Delay */
#define QT1050_CSD_0 0x36
#define QT1050_CSD_1 0x37
#define QT1050_CSD_2 0x39
#define QT1050_CSD_3 0x3a
#define QT1050_CSD_4 0x3b
/* Low Power Mode */
#define QT1050_LPMODE 0x3d
/* Calibration and Reset */
#define QT1050_RES_CAL 0x3f
#define QT1050_RES_CAL_RESET BIT(7)
#define QT1050_RES_CAL_CALIBRATE BIT(1)
#define QT1050_MAX_KEYS 5
#define QT1050_RESET_TIME 255
struct qt1050_key_regs {
unsigned int nthr;
unsigned int pulse_scale;
unsigned int di_aks;
unsigned int csd;
};
struct qt1050_key {
u32 num;
u32 charge_delay;
u32 thr_cnt;
u32 samples;
u32 scale;
u32 keycode;
};
struct qt1050_priv {
struct i2c_client *client;
struct input_dev *input;
struct regmap *regmap;
struct qt1050_key keys[QT1050_MAX_KEYS];
unsigned short keycodes[QT1050_MAX_KEYS];
u8 reg_keys;
u8 last_keys;
};
static const struct qt1050_key_regs qt1050_key_regs_data[] = {
{
.nthr = QT1050_NTHR_0,
.pulse_scale = QT1050_PULSE_SCALE_0,
.di_aks = QT1050_DI_AKS_0,
.csd = QT1050_CSD_0,
}, {
.nthr = QT1050_NTHR_1,
.pulse_scale = QT1050_PULSE_SCALE_1,
.di_aks = QT1050_DI_AKS_1,
.csd = QT1050_CSD_1,
}, {
.nthr = QT1050_NTHR_2,
.pulse_scale = QT1050_PULSE_SCALE_2,
.di_aks = QT1050_DI_AKS_2,
.csd = QT1050_CSD_2,
}, {
.nthr = QT1050_NTHR_3,
.pulse_scale = QT1050_PULSE_SCALE_3,
.di_aks = QT1050_DI_AKS_3,
.csd = QT1050_CSD_3,
}, {
.nthr = QT1050_NTHR_4,
.pulse_scale = QT1050_PULSE_SCALE_4,
.di_aks = QT1050_DI_AKS_4,
.csd = QT1050_CSD_4,
}
};
static bool qt1050_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case QT1050_DET_STATUS:
case QT1050_KEY_STATUS:
case QT1050_KEY_SIGNAL_0_MSB:
case QT1050_KEY_SIGNAL_0_LSB:
case QT1050_KEY_SIGNAL_1_MSB:
case QT1050_KEY_SIGNAL_1_LSB:
case QT1050_KEY_SIGNAL_2_MSB:
case QT1050_KEY_SIGNAL_2_LSB:
case QT1050_KEY_SIGNAL_3_MSB:
case QT1050_KEY_SIGNAL_3_LSB:
case QT1050_KEY_SIGNAL_4_MSB:
case QT1050_KEY_SIGNAL_4_LSB:
return true;
default:
return false;
}
}
static const struct regmap_range qt1050_readable_ranges[] = {
regmap_reg_range(QT1050_CHIP_ID, QT1050_KEY_STATUS),
regmap_reg_range(QT1050_KEY_SIGNAL_0_MSB, QT1050_KEY_SIGNAL_1_LSB),
regmap_reg_range(QT1050_KEY_SIGNAL_2_MSB, QT1050_KEY_SIGNAL_4_LSB),
regmap_reg_range(QT1050_REF_DATA_0_MSB, QT1050_REF_DATA_1_LSB),
regmap_reg_range(QT1050_REF_DATA_2_MSB, QT1050_REF_DATA_4_LSB),
regmap_reg_range(QT1050_NTHR_0, QT1050_NTHR_1),
regmap_reg_range(QT1050_NTHR_2, QT1050_NTHR_4),
regmap_reg_range(QT1050_PULSE_SCALE_0, QT1050_PULSE_SCALE_1),
regmap_reg_range(QT1050_PULSE_SCALE_2, QT1050_PULSE_SCALE_4),
regmap_reg_range(QT1050_DI_AKS_0, QT1050_DI_AKS_1),
regmap_reg_range(QT1050_DI_AKS_2, QT1050_DI_AKS_4),
regmap_reg_range(QT1050_CSD_0, QT1050_CSD_1),
regmap_reg_range(QT1050_CSD_2, QT1050_RES_CAL),
};
static const struct regmap_access_table qt1050_readable_table = {
.yes_ranges = qt1050_readable_ranges,
.n_yes_ranges = ARRAY_SIZE(qt1050_readable_ranges),
};
static const struct regmap_range qt1050_writeable_ranges[] = {
regmap_reg_range(QT1050_NTHR_0, QT1050_NTHR_1),
regmap_reg_range(QT1050_NTHR_2, QT1050_NTHR_4),
regmap_reg_range(QT1050_PULSE_SCALE_0, QT1050_PULSE_SCALE_1),
regmap_reg_range(QT1050_PULSE_SCALE_2, QT1050_PULSE_SCALE_4),
regmap_reg_range(QT1050_DI_AKS_0, QT1050_DI_AKS_1),
regmap_reg_range(QT1050_DI_AKS_2, QT1050_DI_AKS_4),
regmap_reg_range(QT1050_CSD_0, QT1050_CSD_1),
regmap_reg_range(QT1050_CSD_2, QT1050_RES_CAL),
};
static const struct regmap_access_table qt1050_writeable_table = {
.yes_ranges = qt1050_writeable_ranges,
.n_yes_ranges = ARRAY_SIZE(qt1050_writeable_ranges),
};
static struct regmap_config qt1050_regmap_config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = QT1050_RES_CAL,
.cache_type = REGCACHE_RBTREE,
.wr_table = &qt1050_writeable_table,
.rd_table = &qt1050_readable_table,
.volatile_reg = qt1050_volatile_reg,
};
static bool qt1050_identify(struct qt1050_priv *ts)
{
unsigned int val;
int err;
/* Read Chip ID */
regmap_read(ts->regmap, QT1050_CHIP_ID, &val);
if (val != QT1050_CHIP_ID_VER) {
dev_err(&ts->client->dev, "ID %d not supported\n", val);
return false;
}
/* Read firmware version */
err = regmap_read(ts->regmap, QT1050_FW_VERSION, &val);
if (err) {
dev_err(&ts->client->dev, "could not read the firmware version\n");
return false;
}
dev_info(&ts->client->dev, "AT42QT1050 firmware version %1d.%1d\n",
val >> 4, val & 0xf);
return true;
}
static irqreturn_t qt1050_irq_threaded(int irq, void *dev_id)
{
struct qt1050_priv *ts = dev_id;
struct input_dev *input = ts->input;
unsigned long new_keys, changed;
unsigned int val;
int i, err;
/* Read the detected status register, thus clearing interrupt */
err = regmap_read(ts->regmap, QT1050_DET_STATUS, &val);
if (err) {
dev_err(&ts->client->dev, "Fail to read detection status: %d\n",
err);
return IRQ_NONE;
}
/* Read which key changed, keys are not continuous */
err = regmap_read(ts->regmap, QT1050_KEY_STATUS, &val);
if (err) {
dev_err(&ts->client->dev,
"Fail to determine the key status: %d\n", err);
return IRQ_NONE;
}
new_keys = (val & 0x70) >> 2 | (val & 0x6) >> 1;
changed = ts->last_keys ^ new_keys;
/* Report registered keys only */
changed &= ts->reg_keys;
for_each_set_bit(i, &changed, QT1050_MAX_KEYS)
input_report_key(input, ts->keys[i].keycode,
test_bit(i, &new_keys));
ts->last_keys = new_keys;
input_sync(input);
return IRQ_HANDLED;
}
static const struct qt1050_key_regs *qt1050_get_key_regs(int key_num)
{
return &qt1050_key_regs_data[key_num];
}
static int qt1050_set_key(struct regmap *map, int number, int on)
{
const struct qt1050_key_regs *key_regs;
key_regs = qt1050_get_key_regs(number);
return regmap_update_bits(map, key_regs->di_aks, 0xfc,
on ? BIT(4) : 0x00);
}
static int qt1050_apply_fw_data(struct qt1050_priv *ts)
{
struct regmap *map = ts->regmap;
struct qt1050_key *button = &ts->keys[0];
const struct qt1050_key_regs *key_regs;
int i, err;
/* Disable all keys and enable only the specified ones */
for (i = 0; i < QT1050_MAX_KEYS; i++) {
err = qt1050_set_key(map, i, 0);
if (err)
return err;
}
for (i = 0; i < QT1050_MAX_KEYS; i++, button++) {
/* Keep KEY_RESERVED keys off */
if (button->keycode == KEY_RESERVED)
continue;
err = qt1050_set_key(map, button->num, 1);
if (err)
return err;
key_regs = qt1050_get_key_regs(button->num);
err = regmap_write(map, key_regs->pulse_scale,
(button->samples << 4) | (button->scale));
if (err)
return err;
err = regmap_write(map, key_regs->csd, button->charge_delay);
if (err)
return err;
err = regmap_write(map, key_regs->nthr, button->thr_cnt);
if (err)
return err;
}
return 0;
}
static int qt1050_parse_fw(struct qt1050_priv *ts)
{
struct device *dev = &ts->client->dev;
struct fwnode_handle *child;
int nbuttons;
nbuttons = device_get_child_node_count(dev);
if (nbuttons == 0 || nbuttons > QT1050_MAX_KEYS)
return -ENODEV;
device_for_each_child_node(dev, child) {
struct qt1050_key button;
/* Required properties */
if (fwnode_property_read_u32(child, "linux,code",
&button.keycode)) {
dev_err(dev, "Button without keycode\n");
goto err;
}
if (button.keycode >= KEY_MAX) {
dev_err(dev, "Invalid keycode 0x%x\n",
button.keycode);
goto err;
}
if (fwnode_property_read_u32(child, "reg",
&button.num)) {
dev_err(dev, "Button without pad number\n");
goto err;
}
if (button.num < 0 || button.num > QT1050_MAX_KEYS - 1)
goto err;
ts->reg_keys |= BIT(button.num);
/* Optional properties */
if (fwnode_property_read_u32(child,
"microchip,pre-charge-time-ns",
&button.charge_delay)) {
button.charge_delay = 0;
} else {
if (button.charge_delay % 2500 == 0)
button.charge_delay =
button.charge_delay / 2500;
else
button.charge_delay = 0;
}
if (fwnode_property_read_u32(child, "microchip,average-samples",
&button.samples)) {
button.samples = 0;
} else {
if (is_power_of_2(button.samples))
button.samples = ilog2(button.samples);
else
button.samples = 0;
}
if (fwnode_property_read_u32(child, "microchip,average-scaling",
&button.scale)) {
button.scale = 0;
} else {
if (is_power_of_2(button.scale))
button.scale = ilog2(button.scale);
else
button.scale = 0;
}
if (fwnode_property_read_u32(child, "microchip,threshold",
&button.thr_cnt)) {
button.thr_cnt = 20;
} else {
if (button.thr_cnt > 255)
button.thr_cnt = 20;
}
ts->keys[button.num] = button;
}
return 0;
err:
fwnode_handle_put(child);
return -EINVAL;
}
static int qt1050_probe(struct i2c_client *client)
{
struct qt1050_priv *ts;
struct input_dev *input;
struct device *dev = &client->dev;
struct regmap *map;
unsigned int status, i;
int err;
/* Check basic functionality */
err = i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE);
if (!err) {
dev_err(&client->dev, "%s adapter not supported\n",
dev_driver_string(&client->adapter->dev));
return -ENODEV;
}
if (!client->irq) {
dev_err(dev, "assign a irq line to this device\n");
return -EINVAL;
}
ts = devm_kzalloc(dev, sizeof(*ts), GFP_KERNEL);
if (!ts)
return -ENOMEM;
input = devm_input_allocate_device(dev);
if (!input)
return -ENOMEM;
map = devm_regmap_init_i2c(client, &qt1050_regmap_config);
if (IS_ERR(map))
return PTR_ERR(map);
ts->client = client;
ts->input = input;
ts->regmap = map;
i2c_set_clientdata(client, ts);
/* Identify the qt1050 chip */
if (!qt1050_identify(ts))
return -ENODEV;
/* Get pdata */
err = qt1050_parse_fw(ts);
if (err) {
dev_err(dev, "Failed to parse firmware: %d\n", err);
return err;
}
input->name = "AT42QT1050 QTouch Sensor";
input->dev.parent = &client->dev;
input->id.bustype = BUS_I2C;
/* Add the keycode */
input->keycode = ts->keycodes;
input->keycodesize = sizeof(ts->keycodes[0]);
input->keycodemax = QT1050_MAX_KEYS;
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < QT1050_MAX_KEYS; i++) {
ts->keycodes[i] = ts->keys[i].keycode;
__set_bit(ts->keycodes[i], input->keybit);
}
/* Trigger re-calibration */
err = regmap_update_bits(ts->regmap, QT1050_RES_CAL, 0x7f,
QT1050_RES_CAL_CALIBRATE);
if (err) {
dev_err(dev, "Trigger calibration failed: %d\n", err);
return err;
}
err = regmap_read_poll_timeout(ts->regmap, QT1050_DET_STATUS, status,
status >> 7 == 1, 10000, 200000);
if (err) {
dev_err(dev, "Calibration failed: %d\n", err);
return err;
}
/* Soft reset to set defaults */
err = regmap_update_bits(ts->regmap, QT1050_RES_CAL,
QT1050_RES_CAL_RESET, QT1050_RES_CAL_RESET);
if (err) {
dev_err(dev, "Trigger soft reset failed: %d\n", err);
return err;
}
msleep(QT1050_RESET_TIME);
/* Set pdata */
err = qt1050_apply_fw_data(ts);
if (err) {
dev_err(dev, "Failed to set firmware data: %d\n", err);
return err;
}
err = devm_request_threaded_irq(dev, client->irq, NULL,
qt1050_irq_threaded, IRQF_ONESHOT,
"qt1050", ts);
if (err) {
dev_err(&client->dev, "Failed to request irq: %d\n", err);
return err;
}
/* Clear #CHANGE line */
err = regmap_read(ts->regmap, QT1050_DET_STATUS, &status);
if (err) {
dev_err(dev, "Failed to clear #CHANGE line level: %d\n", err);
return err;
}
/* Register the input device */
err = input_register_device(ts->input);
if (err) {
dev_err(&client->dev, "Failed to register input device: %d\n",
err);
return err;
}
return 0;
}
static int qt1050_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct qt1050_priv *ts = i2c_get_clientdata(client);
disable_irq(client->irq);
/*
* Set measurement interval to 1s (125 x 8ms) if wakeup is allowed
* else turn off. The 1s interval seems to be a good compromise between
* low power and response time.
*/
return regmap_write(ts->regmap, QT1050_LPMODE,
device_may_wakeup(dev) ? 125 : 0);
}
static int qt1050_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct qt1050_priv *ts = i2c_get_clientdata(client);
enable_irq(client->irq);
/* Set measurement interval back to 16ms (2 x 8ms) */
return regmap_write(ts->regmap, QT1050_LPMODE, 2);
}
static DEFINE_SIMPLE_DEV_PM_OPS(qt1050_pm_ops, qt1050_suspend, qt1050_resume);
static const struct of_device_id __maybe_unused qt1050_of_match[] = {
{ .compatible = "microchip,qt1050", },
{ },
};
MODULE_DEVICE_TABLE(of, qt1050_of_match);
static struct i2c_driver qt1050_driver = {
.driver = {
.name = "qt1050",
.of_match_table = of_match_ptr(qt1050_of_match),
.pm = pm_sleep_ptr(&qt1050_pm_ops),
},
.probe = qt1050_probe,
};
module_i2c_driver(qt1050_driver);
MODULE_AUTHOR("Marco Felsch <[email protected]");
MODULE_DESCRIPTION("Driver for AT42QT1050 QTouch sensor");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/keyboard/qt1050.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* max7359_keypad.c - MAX7359 Key Switch Controller Driver
*
* Copyright (C) 2009 Samsung Electronics
* Kim Kyuwon <[email protected]>
*
* Based on pxa27x_keypad.c
*
* Datasheet: http://www.maxim-ic.com/quick_view2.cfm/qv_pk/5456
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/pm.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#define MAX7359_MAX_KEY_ROWS 8
#define MAX7359_MAX_KEY_COLS 8
#define MAX7359_MAX_KEY_NUM (MAX7359_MAX_KEY_ROWS * MAX7359_MAX_KEY_COLS)
#define MAX7359_ROW_SHIFT 3
/*
* MAX7359 registers
*/
#define MAX7359_REG_KEYFIFO 0x00
#define MAX7359_REG_CONFIG 0x01
#define MAX7359_REG_DEBOUNCE 0x02
#define MAX7359_REG_INTERRUPT 0x03
#define MAX7359_REG_PORTS 0x04
#define MAX7359_REG_KEYREP 0x05
#define MAX7359_REG_SLEEP 0x06
/*
* Configuration register bits
*/
#define MAX7359_CFG_SLEEP (1 << 7)
#define MAX7359_CFG_INTERRUPT (1 << 5)
#define MAX7359_CFG_KEY_RELEASE (1 << 3)
#define MAX7359_CFG_WAKEUP (1 << 1)
#define MAX7359_CFG_TIMEOUT (1 << 0)
/*
* Autosleep register values (ms)
*/
#define MAX7359_AUTOSLEEP_8192 0x01
#define MAX7359_AUTOSLEEP_4096 0x02
#define MAX7359_AUTOSLEEP_2048 0x03
#define MAX7359_AUTOSLEEP_1024 0x04
#define MAX7359_AUTOSLEEP_512 0x05
#define MAX7359_AUTOSLEEP_256 0x06
struct max7359_keypad {
/* matrix key code map */
unsigned short keycodes[MAX7359_MAX_KEY_NUM];
struct input_dev *input_dev;
struct i2c_client *client;
};
static int max7359_write_reg(struct i2c_client *client, u8 reg, u8 val)
{
int ret = i2c_smbus_write_byte_data(client, reg, val);
if (ret < 0)
dev_err(&client->dev, "%s: reg 0x%x, val 0x%x, err %d\n",
__func__, reg, val, ret);
return ret;
}
static int max7359_read_reg(struct i2c_client *client, int reg)
{
int ret = i2c_smbus_read_byte_data(client, reg);
if (ret < 0)
dev_err(&client->dev, "%s: reg 0x%x, err %d\n",
__func__, reg, ret);
return ret;
}
/* runs in an IRQ thread -- can (and will!) sleep */
static irqreturn_t max7359_interrupt(int irq, void *dev_id)
{
struct max7359_keypad *keypad = dev_id;
struct input_dev *input_dev = keypad->input_dev;
int val, row, col, release, code;
val = max7359_read_reg(keypad->client, MAX7359_REG_KEYFIFO);
row = val & 0x7;
col = (val >> 3) & 0x7;
release = val & 0x40;
code = MATRIX_SCAN_CODE(row, col, MAX7359_ROW_SHIFT);
dev_dbg(&keypad->client->dev,
"key[%d:%d] %s\n", row, col, release ? "release" : "press");
input_event(input_dev, EV_MSC, MSC_SCAN, code);
input_report_key(input_dev, keypad->keycodes[code], !release);
input_sync(input_dev);
return IRQ_HANDLED;
}
/*
* Let MAX7359 fall into a deep sleep:
* If no keys are pressed, enter sleep mode for 8192 ms. And if any
* key is pressed, the MAX7359 returns to normal operating mode.
*/
static inline void max7359_fall_deepsleep(struct i2c_client *client)
{
max7359_write_reg(client, MAX7359_REG_SLEEP, MAX7359_AUTOSLEEP_8192);
}
/*
* Let MAX7359 take a catnap:
* Autosleep just for 256 ms.
*/
static inline void max7359_take_catnap(struct i2c_client *client)
{
max7359_write_reg(client, MAX7359_REG_SLEEP, MAX7359_AUTOSLEEP_256);
}
static int max7359_open(struct input_dev *dev)
{
struct max7359_keypad *keypad = input_get_drvdata(dev);
max7359_take_catnap(keypad->client);
return 0;
}
static void max7359_close(struct input_dev *dev)
{
struct max7359_keypad *keypad = input_get_drvdata(dev);
max7359_fall_deepsleep(keypad->client);
}
static void max7359_initialize(struct i2c_client *client)
{
max7359_write_reg(client, MAX7359_REG_CONFIG,
MAX7359_CFG_KEY_RELEASE | /* Key release enable */
MAX7359_CFG_WAKEUP); /* Key press wakeup enable */
/* Full key-scan functionality */
max7359_write_reg(client, MAX7359_REG_DEBOUNCE, 0x1F);
/* nINT asserts every debounce cycles */
max7359_write_reg(client, MAX7359_REG_INTERRUPT, 0x01);
max7359_fall_deepsleep(client);
}
static int max7359_probe(struct i2c_client *client)
{
const struct matrix_keymap_data *keymap_data =
dev_get_platdata(&client->dev);
struct max7359_keypad *keypad;
struct input_dev *input_dev;
int ret;
int error;
if (!client->irq) {
dev_err(&client->dev, "The irq number should not be zero\n");
return -EINVAL;
}
/* Detect MAX7359: The initial Keys FIFO value is '0x3F' */
ret = max7359_read_reg(client, MAX7359_REG_KEYFIFO);
if (ret < 0) {
dev_err(&client->dev, "failed to detect device\n");
return -ENODEV;
}
dev_dbg(&client->dev, "keys FIFO is 0x%02x\n", ret);
keypad = devm_kzalloc(&client->dev, sizeof(struct max7359_keypad),
GFP_KERNEL);
if (!keypad) {
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 input device\n");
return -ENOMEM;
}
keypad->client = client;
keypad->input_dev = input_dev;
input_dev->name = client->name;
input_dev->id.bustype = BUS_I2C;
input_dev->open = max7359_open;
input_dev->close = max7359_close;
input_dev->dev.parent = &client->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
input_dev->keycodesize = sizeof(keypad->keycodes[0]);
input_dev->keycodemax = ARRAY_SIZE(keypad->keycodes);
input_dev->keycode = keypad->keycodes;
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
input_set_drvdata(input_dev, keypad);
error = matrix_keypad_build_keymap(keymap_data, NULL,
MAX7359_MAX_KEY_ROWS,
MAX7359_MAX_KEY_COLS,
keypad->keycodes,
input_dev);
if (error) {
dev_err(&client->dev, "failed to build keymap\n");
return error;
}
error = devm_request_threaded_irq(&client->dev, client->irq, NULL,
max7359_interrupt,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
client->name, keypad);
if (error) {
dev_err(&client->dev, "failed to register interrupt\n");
return error;
}
/* Register the input device */
error = input_register_device(input_dev);
if (error) {
dev_err(&client->dev, "failed to register input device\n");
return error;
}
/* Initialize MAX7359 */
max7359_initialize(client);
device_init_wakeup(&client->dev, 1);
return 0;
}
static int max7359_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
max7359_fall_deepsleep(client);
if (device_may_wakeup(&client->dev))
enable_irq_wake(client->irq);
return 0;
}
static int max7359_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
if (device_may_wakeup(&client->dev))
disable_irq_wake(client->irq);
/* Restore the default setting */
max7359_take_catnap(client);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(max7359_pm, max7359_suspend, max7359_resume);
static const struct i2c_device_id max7359_ids[] = {
{ "max7359", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, max7359_ids);
static struct i2c_driver max7359_i2c_driver = {
.driver = {
.name = "max7359",
.pm = pm_sleep_ptr(&max7359_pm),
},
.probe = max7359_probe,
.id_table = max7359_ids,
};
module_i2c_driver(max7359_i2c_driver);
MODULE_AUTHOR("Kim Kyuwon <[email protected]>");
MODULE_DESCRIPTION("MAX7359 Key Switch Controller Driver");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/keyboard/max7359_keypad.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) ST-Ericsson SA 2010
*
* Author: Jayeeta Banerjee <[email protected]>
* Author: Sundar Iyer <[email protected]>
*
* TC35893 MFD Keypad Controller driver
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/platform_device.h>
#include <linux/input/matrix_keypad.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/mfd/tc3589x.h>
#include <linux/device.h>
/* Maximum supported keypad matrix row/columns size */
#define TC3589x_MAX_KPROW 8
#define TC3589x_MAX_KPCOL 12
/* keypad related Constants */
#define TC3589x_MAX_DEBOUNCE_SETTLE 0xFF
#define DEDICATED_KEY_VAL 0xFF
/* Pull up/down masks */
#define TC3589x_NO_PULL_MASK 0x0
#define TC3589x_PULL_DOWN_MASK 0x1
#define TC3589x_PULL_UP_MASK 0x2
#define TC3589x_PULLUP_ALL_MASK 0xAA
#define TC3589x_IO_PULL_VAL(index, mask) ((mask)<<((index)%4)*2)
/* Bit masks for IOCFG register */
#define IOCFG_BALLCFG 0x01
#define IOCFG_IG 0x08
#define KP_EVCODE_COL_MASK 0x0F
#define KP_EVCODE_ROW_MASK 0x70
#define KP_RELEASE_EVT_MASK 0x80
#define KP_ROW_SHIFT 4
#define KP_NO_VALID_KEY_MASK 0x7F
/* bit masks for RESTCTRL register */
#define TC3589x_KBDRST 0x2
#define TC3589x_IRQRST 0x10
#define TC3589x_RESET_ALL 0x1B
/* KBDMFS register bit mask */
#define TC3589x_KBDMFS_EN 0x1
/* CLKEN register bitmask */
#define KPD_CLK_EN 0x1
/* RSTINTCLR register bit mask */
#define IRQ_CLEAR 0x1
/* bit masks for keyboard interrupts*/
#define TC3589x_EVT_LOSS_INT 0x8
#define TC3589x_EVT_INT 0x4
#define TC3589x_KBD_LOSS_INT 0x2
#define TC3589x_KBD_INT 0x1
/* bit masks for keyboard interrupt clear*/
#define TC3589x_EVT_INT_CLR 0x2
#define TC3589x_KBD_INT_CLR 0x1
/**
* struct tc3589x_keypad_platform_data - platform specific keypad data
* @keymap_data: matrix scan code table for keycodes
* @krow: mask for available rows, value is 0xFF
* @kcol: mask for available columns, value is 0xFF
* @debounce_period: platform specific debounce time
* @settle_time: platform specific settle down time
* @irqtype: type of interrupt, falling or rising edge
* @enable_wakeup: specifies if keypad event can wake up system from sleep
* @no_autorepeat: flag for auto repetition
*/
struct tc3589x_keypad_platform_data {
const struct matrix_keymap_data *keymap_data;
u8 krow;
u8 kcol;
u8 debounce_period;
u8 settle_time;
unsigned long irqtype;
bool enable_wakeup;
bool no_autorepeat;
};
/**
* struct tc_keypad - data structure used by keypad driver
* @tc3589x: pointer to tc35893
* @input: pointer to input device object
* @board: keypad platform device
* @krow: number of rows
* @kcol: number of columns
* @keymap: matrix scan code table for keycodes
* @keypad_stopped: holds keypad status
*/
struct tc_keypad {
struct tc3589x *tc3589x;
struct input_dev *input;
const struct tc3589x_keypad_platform_data *board;
unsigned int krow;
unsigned int kcol;
unsigned short *keymap;
bool keypad_stopped;
};
static int tc3589x_keypad_init_key_hardware(struct tc_keypad *keypad)
{
int ret;
struct tc3589x *tc3589x = keypad->tc3589x;
const struct tc3589x_keypad_platform_data *board = keypad->board;
/* validate platform configuration */
if (board->kcol > TC3589x_MAX_KPCOL || board->krow > TC3589x_MAX_KPROW)
return -EINVAL;
/* configure KBDSIZE 4 LSbits for cols and 4 MSbits for rows */
ret = tc3589x_reg_write(tc3589x, TC3589x_KBDSIZE,
(board->krow << KP_ROW_SHIFT) | board->kcol);
if (ret < 0)
return ret;
/* configure dedicated key config, no dedicated key selected */
ret = tc3589x_reg_write(tc3589x, TC3589x_KBCFG_LSB, DEDICATED_KEY_VAL);
if (ret < 0)
return ret;
ret = tc3589x_reg_write(tc3589x, TC3589x_KBCFG_MSB, DEDICATED_KEY_VAL);
if (ret < 0)
return ret;
/* Configure settle time */
ret = tc3589x_reg_write(tc3589x, TC3589x_KBDSETTLE_REG,
board->settle_time);
if (ret < 0)
return ret;
/* Configure debounce time */
ret = tc3589x_reg_write(tc3589x, TC3589x_KBDBOUNCE,
board->debounce_period);
if (ret < 0)
return ret;
/* Start of initialise keypad GPIOs */
ret = tc3589x_set_bits(tc3589x, TC3589x_IOCFG, 0x0, IOCFG_IG);
if (ret < 0)
return ret;
/* Configure pull-up resistors for all row GPIOs */
ret = tc3589x_reg_write(tc3589x, TC3589x_IOPULLCFG0_LSB,
TC3589x_PULLUP_ALL_MASK);
if (ret < 0)
return ret;
ret = tc3589x_reg_write(tc3589x, TC3589x_IOPULLCFG0_MSB,
TC3589x_PULLUP_ALL_MASK);
if (ret < 0)
return ret;
/* Configure pull-up resistors for all column GPIOs */
ret = tc3589x_reg_write(tc3589x, TC3589x_IOPULLCFG1_LSB,
TC3589x_PULLUP_ALL_MASK);
if (ret < 0)
return ret;
ret = tc3589x_reg_write(tc3589x, TC3589x_IOPULLCFG1_MSB,
TC3589x_PULLUP_ALL_MASK);
if (ret < 0)
return ret;
ret = tc3589x_reg_write(tc3589x, TC3589x_IOPULLCFG2_LSB,
TC3589x_PULLUP_ALL_MASK);
return ret;
}
#define TC35893_DATA_REGS 4
#define TC35893_KEYCODE_FIFO_EMPTY 0x7f
#define TC35893_KEYCODE_FIFO_CLEAR 0xff
#define TC35893_KEYPAD_ROW_SHIFT 0x3
static irqreturn_t tc3589x_keypad_irq(int irq, void *dev)
{
struct tc_keypad *keypad = dev;
struct tc3589x *tc3589x = keypad->tc3589x;
u8 i, row_index, col_index, kbd_code, up;
u8 code;
for (i = 0; i < TC35893_DATA_REGS * 2; i++) {
kbd_code = tc3589x_reg_read(tc3589x, TC3589x_EVTCODE_FIFO);
/* loop till fifo is empty and no more keys are pressed */
if (kbd_code == TC35893_KEYCODE_FIFO_EMPTY ||
kbd_code == TC35893_KEYCODE_FIFO_CLEAR)
continue;
/* valid key is found */
col_index = kbd_code & KP_EVCODE_COL_MASK;
row_index = (kbd_code & KP_EVCODE_ROW_MASK) >> KP_ROW_SHIFT;
code = MATRIX_SCAN_CODE(row_index, col_index,
TC35893_KEYPAD_ROW_SHIFT);
up = kbd_code & KP_RELEASE_EVT_MASK;
input_event(keypad->input, EV_MSC, MSC_SCAN, code);
input_report_key(keypad->input, keypad->keymap[code], !up);
input_sync(keypad->input);
}
/* clear IRQ */
tc3589x_set_bits(tc3589x, TC3589x_KBDIC,
0x0, TC3589x_EVT_INT_CLR | TC3589x_KBD_INT_CLR);
/* enable IRQ */
tc3589x_set_bits(tc3589x, TC3589x_KBDMSK,
0x0, TC3589x_EVT_LOSS_INT | TC3589x_EVT_INT);
return IRQ_HANDLED;
}
static int tc3589x_keypad_enable(struct tc_keypad *keypad)
{
struct tc3589x *tc3589x = keypad->tc3589x;
int ret;
/* pull the keypad module out of reset */
ret = tc3589x_set_bits(tc3589x, TC3589x_RSTCTRL, TC3589x_KBDRST, 0x0);
if (ret < 0)
return ret;
/* configure KBDMFS */
ret = tc3589x_set_bits(tc3589x, TC3589x_KBDMFS, 0x0, TC3589x_KBDMFS_EN);
if (ret < 0)
return ret;
/* enable the keypad clock */
ret = tc3589x_set_bits(tc3589x, TC3589x_CLKEN, 0x0, KPD_CLK_EN);
if (ret < 0)
return ret;
/* clear pending IRQs */
ret = tc3589x_set_bits(tc3589x, TC3589x_RSTINTCLR, 0x0, 0x1);
if (ret < 0)
return ret;
/* enable the IRQs */
ret = tc3589x_set_bits(tc3589x, TC3589x_KBDMSK, 0x0,
TC3589x_EVT_LOSS_INT | TC3589x_EVT_INT);
if (ret < 0)
return ret;
keypad->keypad_stopped = false;
return ret;
}
static int tc3589x_keypad_disable(struct tc_keypad *keypad)
{
struct tc3589x *tc3589x = keypad->tc3589x;
int ret;
/* clear IRQ */
ret = tc3589x_set_bits(tc3589x, TC3589x_KBDIC,
0x0, TC3589x_EVT_INT_CLR | TC3589x_KBD_INT_CLR);
if (ret < 0)
return ret;
/* disable all interrupts */
ret = tc3589x_set_bits(tc3589x, TC3589x_KBDMSK,
~(TC3589x_EVT_LOSS_INT | TC3589x_EVT_INT), 0x0);
if (ret < 0)
return ret;
/* disable the keypad module */
ret = tc3589x_set_bits(tc3589x, TC3589x_CLKEN, 0x1, 0x0);
if (ret < 0)
return ret;
/* put the keypad module into reset */
ret = tc3589x_set_bits(tc3589x, TC3589x_RSTCTRL, TC3589x_KBDRST, 0x1);
keypad->keypad_stopped = true;
return ret;
}
static int tc3589x_keypad_open(struct input_dev *input)
{
int error;
struct tc_keypad *keypad = input_get_drvdata(input);
/* enable the keypad module */
error = tc3589x_keypad_enable(keypad);
if (error < 0) {
dev_err(&input->dev, "failed to enable keypad module\n");
return error;
}
error = tc3589x_keypad_init_key_hardware(keypad);
if (error < 0) {
dev_err(&input->dev, "failed to configure keypad module\n");
return error;
}
return 0;
}
static void tc3589x_keypad_close(struct input_dev *input)
{
struct tc_keypad *keypad = input_get_drvdata(input);
/* disable the keypad module */
tc3589x_keypad_disable(keypad);
}
static const struct tc3589x_keypad_platform_data *
tc3589x_keypad_of_probe(struct device *dev)
{
struct device_node *np = dev->of_node;
struct tc3589x_keypad_platform_data *plat;
u32 cols, rows;
u32 debounce_ms;
int proplen;
if (!np)
return ERR_PTR(-ENODEV);
plat = devm_kzalloc(dev, sizeof(*plat), GFP_KERNEL);
if (!plat)
return ERR_PTR(-ENOMEM);
of_property_read_u32(np, "keypad,num-columns", &cols);
of_property_read_u32(np, "keypad,num-rows", &rows);
plat->kcol = (u8) cols;
plat->krow = (u8) rows;
if (!plat->krow || !plat->kcol ||
plat->krow > TC_KPD_ROWS || plat->kcol > TC_KPD_COLUMNS) {
dev_err(dev,
"keypad columns/rows not properly specified (%ux%u)\n",
plat->kcol, plat->krow);
return ERR_PTR(-EINVAL);
}
if (!of_get_property(np, "linux,keymap", &proplen)) {
dev_err(dev, "property linux,keymap not found\n");
return ERR_PTR(-ENOENT);
}
plat->no_autorepeat = of_property_read_bool(np, "linux,no-autorepeat");
plat->enable_wakeup = of_property_read_bool(np, "wakeup-source") ||
/* legacy name */
of_property_read_bool(np, "linux,wakeup");
/* The custom delay format is ms/16 */
of_property_read_u32(np, "debounce-delay-ms", &debounce_ms);
if (debounce_ms)
plat->debounce_period = debounce_ms * 16;
else
plat->debounce_period = TC_KPD_DEBOUNCE_PERIOD;
plat->settle_time = TC_KPD_SETTLE_TIME;
/* FIXME: should be property of the IRQ resource? */
plat->irqtype = IRQF_TRIGGER_FALLING;
return plat;
}
static int tc3589x_keypad_probe(struct platform_device *pdev)
{
struct tc3589x *tc3589x = dev_get_drvdata(pdev->dev.parent);
struct tc_keypad *keypad;
struct input_dev *input;
const struct tc3589x_keypad_platform_data *plat;
int error, irq;
plat = tc3589x_keypad_of_probe(&pdev->dev);
if (IS_ERR(plat)) {
dev_err(&pdev->dev, "invalid keypad platform data\n");
return PTR_ERR(plat);
}
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
keypad = devm_kzalloc(&pdev->dev, sizeof(struct tc_keypad),
GFP_KERNEL);
if (!keypad)
return -ENOMEM;
input = devm_input_allocate_device(&pdev->dev);
if (!input) {
dev_err(&pdev->dev, "failed to allocate input device\n");
return -ENOMEM;
}
keypad->board = plat;
keypad->input = input;
keypad->tc3589x = tc3589x;
input->id.bustype = BUS_I2C;
input->name = pdev->name;
input->dev.parent = &pdev->dev;
input->open = tc3589x_keypad_open;
input->close = tc3589x_keypad_close;
error = matrix_keypad_build_keymap(plat->keymap_data, NULL,
TC3589x_MAX_KPROW, TC3589x_MAX_KPCOL,
NULL, input);
if (error) {
dev_err(&pdev->dev, "Failed to build keymap\n");
return error;
}
keypad->keymap = input->keycode;
input_set_capability(input, EV_MSC, MSC_SCAN);
if (!plat->no_autorepeat)
__set_bit(EV_REP, input->evbit);
input_set_drvdata(input, keypad);
tc3589x_keypad_disable(keypad);
error = devm_request_threaded_irq(&pdev->dev, irq,
NULL, tc3589x_keypad_irq,
plat->irqtype | IRQF_ONESHOT,
"tc3589x-keypad", keypad);
if (error) {
dev_err(&pdev->dev,
"Could not allocate irq %d,error %d\n",
irq, error);
return error;
}
error = input_register_device(input);
if (error) {
dev_err(&pdev->dev, "Could not register input device\n");
return error;
}
/* let platform decide if keypad is a wakeup source or not */
device_init_wakeup(&pdev->dev, plat->enable_wakeup);
device_set_wakeup_capable(&pdev->dev, plat->enable_wakeup);
platform_set_drvdata(pdev, keypad);
return 0;
}
static int tc3589x_keypad_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct tc_keypad *keypad = platform_get_drvdata(pdev);
int irq = platform_get_irq(pdev, 0);
/* keypad is already off; we do nothing */
if (keypad->keypad_stopped)
return 0;
/* if device is not a wakeup source, disable it for powersave */
if (!device_may_wakeup(&pdev->dev))
tc3589x_keypad_disable(keypad);
else
enable_irq_wake(irq);
return 0;
}
static int tc3589x_keypad_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct tc_keypad *keypad = platform_get_drvdata(pdev);
int irq = platform_get_irq(pdev, 0);
if (!keypad->keypad_stopped)
return 0;
/* enable the device to resume normal operations */
if (!device_may_wakeup(&pdev->dev))
tc3589x_keypad_enable(keypad);
else
disable_irq_wake(irq);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(tc3589x_keypad_dev_pm_ops,
tc3589x_keypad_suspend, tc3589x_keypad_resume);
static struct platform_driver tc3589x_keypad_driver = {
.driver = {
.name = "tc3589x-keypad",
.pm = pm_sleep_ptr(&tc3589x_keypad_dev_pm_ops),
},
.probe = tc3589x_keypad_probe,
};
module_platform_driver(tc3589x_keypad_driver);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Jayeeta Banerjee/Sundar Iyer");
MODULE_DESCRIPTION("TC35893 Keypad Driver");
MODULE_ALIAS("platform:tc3589x-keypad");
|
linux-master
|
drivers/input/keyboard/tc3589x-keypad.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (C) 2004 by Jan-Benedict Glaw <[email protected]>
*/
/*
* LK keyboard driver for Linux, based on sunkbd.c (C) by Vojtech Pavlik
*/
/*
* DEC LK201 and LK401 keyboard driver for Linux (primary for DECstations
* and VAXstations, but can also be used on any standard RS232 with an
* adaptor).
*
* DISCLAIMER: This works for _me_. If you break anything by using the
* information given below, I will _not_ be liable!
*
* RJ10 pinout: To DE9: Or DB25:
* 1 - RxD <----> Pin 3 (TxD) <-> Pin 2 (TxD)
* 2 - GND <----> Pin 5 (GND) <-> Pin 7 (GND)
* 4 - TxD <----> Pin 2 (RxD) <-> Pin 3 (RxD)
* 3 - +12V (from HDD drive connector), DON'T connect to DE9 or DB25!!!
*
* Pin numbers for DE9 and DB25 are noted on the plug (quite small:). For
* RJ10, it's like this:
*
* __=__ Hold the plug in front of you, cable downwards,
* /___/| nose is hidden behind the plug. Now, pin 1 is at
* |1234|| the left side, pin 4 at the right and 2 and 3 are
* |IIII|| in between, of course:)
* | ||
* |____|/
* || So the adaptor consists of three connected cables
* || for data transmission (RxD and TxD) and signal ground.
* Additionally, you have to get +12V from somewhere.
* Most easily, you'll get that from a floppy or HDD power connector.
* It's the yellow cable there (black is ground and red is +5V).
*
* The keyboard and all the commands it understands are documented in
* "VCB02 Video Subsystem - Technical Manual", EK-104AA-TM-001. This
* document is LK201 specific, but LK401 is mostly compatible. It comes
* up in LK201 mode and doesn't report any of the additional keys it
* has. These need to be switched on with the LK_CMD_ENABLE_LK401
* command. You'll find this document (scanned .pdf file) on MANX,
* a search engine specific to DEC documentation. Try
* http://www.vt100.net/manx/details?pn=EK-104AA-TM-001;id=21;cp=1
*/
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/workqueue.h>
#define DRIVER_DESC "LK keyboard driver"
MODULE_AUTHOR("Jan-Benedict Glaw <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Known parameters:
* bell_volume
* keyclick_volume
* ctrlclick_volume
*
* Please notice that there's not yet an API to set these at runtime.
*/
static int bell_volume = 100; /* % */
module_param(bell_volume, int, 0);
MODULE_PARM_DESC(bell_volume, "Bell volume (in %). default is 100%");
static int keyclick_volume = 100; /* % */
module_param(keyclick_volume, int, 0);
MODULE_PARM_DESC(keyclick_volume, "Keyclick volume (in %), default is 100%");
static int ctrlclick_volume = 100; /* % */
module_param(ctrlclick_volume, int, 0);
MODULE_PARM_DESC(ctrlclick_volume, "Ctrlclick volume (in %), default is 100%");
static int lk201_compose_is_alt;
module_param(lk201_compose_is_alt, int, 0);
MODULE_PARM_DESC(lk201_compose_is_alt,
"If set non-zero, LK201' Compose key will act as an Alt key");
#undef LKKBD_DEBUG
#ifdef LKKBD_DEBUG
#define DBG(x...) printk(x)
#else
#define DBG(x...) do {} while (0)
#endif
/* LED control */
#define LK_LED_WAIT 0x81
#define LK_LED_COMPOSE 0x82
#define LK_LED_SHIFTLOCK 0x84
#define LK_LED_SCROLLLOCK 0x88
#define LK_CMD_LED_ON 0x13
#define LK_CMD_LED_OFF 0x11
/* Mode control */
#define LK_MODE_DOWN 0x80
#define LK_MODE_AUTODOWN 0x82
#define LK_MODE_UPDOWN 0x86
#define LK_CMD_SET_MODE(mode, div) ((mode) | ((div) << 3))
/* Misc commands */
#define LK_CMD_ENABLE_KEYCLICK 0x1b
#define LK_CMD_DISABLE_KEYCLICK 0x99
#define LK_CMD_DISABLE_BELL 0xa1
#define LK_CMD_SOUND_BELL 0xa7
#define LK_CMD_ENABLE_BELL 0x23
#define LK_CMD_DISABLE_CTRCLICK 0xb9
#define LK_CMD_ENABLE_CTRCLICK 0xbb
#define LK_CMD_SET_DEFAULTS 0xd3
#define LK_CMD_POWERCYCLE_RESET 0xfd
#define LK_CMD_ENABLE_LK401 0xe9
#define LK_CMD_REQUEST_ID 0xab
/* Misc responses from keyboard */
#define LK_STUCK_KEY 0x3d
#define LK_SELFTEST_FAILED 0x3e
#define LK_ALL_KEYS_UP 0xb3
#define LK_METRONOME 0xb4
#define LK_OUTPUT_ERROR 0xb5
#define LK_INPUT_ERROR 0xb6
#define LK_KBD_LOCKED 0xb7
#define LK_KBD_TEST_MODE_ACK 0xb8
#define LK_PREFIX_KEY_DOWN 0xb9
#define LK_MODE_CHANGE_ACK 0xba
#define LK_RESPONSE_RESERVED 0xbb
#define LK_NUM_KEYCODES 256
#define LK_NUM_IGNORE_BYTES 6
static unsigned short lkkbd_keycode[LK_NUM_KEYCODES] = {
[0x56] = KEY_F1,
[0x57] = KEY_F2,
[0x58] = KEY_F3,
[0x59] = KEY_F4,
[0x5a] = KEY_F5,
[0x64] = KEY_F6,
[0x65] = KEY_F7,
[0x66] = KEY_F8,
[0x67] = KEY_F9,
[0x68] = KEY_F10,
[0x71] = KEY_F11,
[0x72] = KEY_F12,
[0x73] = KEY_F13,
[0x74] = KEY_F14,
[0x7c] = KEY_F15,
[0x7d] = KEY_F16,
[0x80] = KEY_F17,
[0x81] = KEY_F18,
[0x82] = KEY_F19,
[0x83] = KEY_F20,
[0x8a] = KEY_FIND,
[0x8b] = KEY_INSERT,
[0x8c] = KEY_DELETE,
[0x8d] = KEY_SELECT,
[0x8e] = KEY_PAGEUP,
[0x8f] = KEY_PAGEDOWN,
[0x92] = KEY_KP0,
[0x94] = KEY_KPDOT,
[0x95] = KEY_KPENTER,
[0x96] = KEY_KP1,
[0x97] = KEY_KP2,
[0x98] = KEY_KP3,
[0x99] = KEY_KP4,
[0x9a] = KEY_KP5,
[0x9b] = KEY_KP6,
[0x9c] = KEY_KPCOMMA,
[0x9d] = KEY_KP7,
[0x9e] = KEY_KP8,
[0x9f] = KEY_KP9,
[0xa0] = KEY_KPMINUS,
[0xa1] = KEY_PROG1,
[0xa2] = KEY_PROG2,
[0xa3] = KEY_PROG3,
[0xa4] = KEY_PROG4,
[0xa7] = KEY_LEFT,
[0xa8] = KEY_RIGHT,
[0xa9] = KEY_DOWN,
[0xaa] = KEY_UP,
[0xab] = KEY_RIGHTSHIFT,
[0xac] = KEY_LEFTALT,
[0xad] = KEY_COMPOSE, /* Right Compose, that is. */
[0xae] = KEY_LEFTSHIFT, /* Same as KEY_RIGHTSHIFT on LK201 */
[0xaf] = KEY_LEFTCTRL,
[0xb0] = KEY_CAPSLOCK,
[0xb1] = KEY_COMPOSE, /* Left Compose, that is. */
[0xb2] = KEY_RIGHTALT,
[0xbc] = KEY_BACKSPACE,
[0xbd] = KEY_ENTER,
[0xbe] = KEY_TAB,
[0xbf] = KEY_ESC,
[0xc0] = KEY_1,
[0xc1] = KEY_Q,
[0xc2] = KEY_A,
[0xc3] = KEY_Z,
[0xc5] = KEY_2,
[0xc6] = KEY_W,
[0xc7] = KEY_S,
[0xc8] = KEY_X,
[0xc9] = KEY_102ND,
[0xcb] = KEY_3,
[0xcc] = KEY_E,
[0xcd] = KEY_D,
[0xce] = KEY_C,
[0xd0] = KEY_4,
[0xd1] = KEY_R,
[0xd2] = KEY_F,
[0xd3] = KEY_V,
[0xd4] = KEY_SPACE,
[0xd6] = KEY_5,
[0xd7] = KEY_T,
[0xd8] = KEY_G,
[0xd9] = KEY_B,
[0xdb] = KEY_6,
[0xdc] = KEY_Y,
[0xdd] = KEY_H,
[0xde] = KEY_N,
[0xe0] = KEY_7,
[0xe1] = KEY_U,
[0xe2] = KEY_J,
[0xe3] = KEY_M,
[0xe5] = KEY_8,
[0xe6] = KEY_I,
[0xe7] = KEY_K,
[0xe8] = KEY_COMMA,
[0xea] = KEY_9,
[0xeb] = KEY_O,
[0xec] = KEY_L,
[0xed] = KEY_DOT,
[0xef] = KEY_0,
[0xf0] = KEY_P,
[0xf2] = KEY_SEMICOLON,
[0xf3] = KEY_SLASH,
[0xf5] = KEY_EQUAL,
[0xf6] = KEY_RIGHTBRACE,
[0xf7] = KEY_BACKSLASH,
[0xf9] = KEY_MINUS,
[0xfa] = KEY_LEFTBRACE,
[0xfb] = KEY_APOSTROPHE,
};
#define CHECK_LED(LK, VAR_ON, VAR_OFF, LED, BITS) do { \
if (test_bit(LED, (LK)->dev->led)) \
VAR_ON |= BITS; \
else \
VAR_OFF |= BITS; \
} while (0)
/*
* Per-keyboard data
*/
struct lkkbd {
unsigned short keycode[LK_NUM_KEYCODES];
int ignore_bytes;
unsigned char id[LK_NUM_IGNORE_BYTES];
struct input_dev *dev;
struct serio *serio;
struct work_struct tq;
char name[64];
char phys[32];
char type;
int bell_volume;
int keyclick_volume;
int ctrlclick_volume;
};
#ifdef LKKBD_DEBUG
/*
* Responses from the keyboard and mapping back to their names.
*/
static struct {
unsigned char value;
unsigned char *name;
} lk_response[] = {
#define RESPONSE(x) { .value = (x), .name = #x, }
RESPONSE(LK_STUCK_KEY),
RESPONSE(LK_SELFTEST_FAILED),
RESPONSE(LK_ALL_KEYS_UP),
RESPONSE(LK_METRONOME),
RESPONSE(LK_OUTPUT_ERROR),
RESPONSE(LK_INPUT_ERROR),
RESPONSE(LK_KBD_LOCKED),
RESPONSE(LK_KBD_TEST_MODE_ACK),
RESPONSE(LK_PREFIX_KEY_DOWN),
RESPONSE(LK_MODE_CHANGE_ACK),
RESPONSE(LK_RESPONSE_RESERVED),
#undef RESPONSE
};
static unsigned char *response_name(unsigned char value)
{
int i;
for (i = 0; i < ARRAY_SIZE(lk_response); i++)
if (lk_response[i].value == value)
return lk_response[i].name;
return "<unknown>";
}
#endif /* LKKBD_DEBUG */
/*
* Calculate volume parameter byte for a given volume.
*/
static unsigned char volume_to_hw(int volume_percent)
{
unsigned char ret = 0;
if (volume_percent < 0)
volume_percent = 0;
if (volume_percent > 100)
volume_percent = 100;
if (volume_percent >= 0)
ret = 7;
if (volume_percent >= 13) /* 12.5 */
ret = 6;
if (volume_percent >= 25)
ret = 5;
if (volume_percent >= 38) /* 37.5 */
ret = 4;
if (volume_percent >= 50)
ret = 3;
if (volume_percent >= 63) /* 62.5 */
ret = 2; /* This is the default volume */
if (volume_percent >= 75)
ret = 1;
if (volume_percent >= 88) /* 87.5 */
ret = 0;
ret |= 0x80;
return ret;
}
static void lkkbd_detection_done(struct lkkbd *lk)
{
int i;
/*
* Reset setting for Compose key. Let Compose be KEY_COMPOSE.
*/
lk->keycode[0xb1] = KEY_COMPOSE;
/*
* Print keyboard name and modify Compose=Alt on user's request.
*/
switch (lk->id[4]) {
case 1:
strscpy(lk->name, "DEC LK201 keyboard", sizeof(lk->name));
if (lk201_compose_is_alt)
lk->keycode[0xb1] = KEY_LEFTALT;
break;
case 2:
strscpy(lk->name, "DEC LK401 keyboard", sizeof(lk->name));
break;
default:
strscpy(lk->name, "Unknown DEC keyboard", sizeof(lk->name));
printk(KERN_ERR
"lkkbd: keyboard on %s is unknown, please report to "
"Jan-Benedict Glaw <[email protected]>\n", lk->phys);
printk(KERN_ERR "lkkbd: keyboard ID'ed as:");
for (i = 0; i < LK_NUM_IGNORE_BYTES; i++)
printk(" 0x%02x", lk->id[i]);
printk("\n");
break;
}
printk(KERN_INFO "lkkbd: keyboard on %s identified as: %s\n",
lk->phys, lk->name);
/*
* Report errors during keyboard boot-up.
*/
switch (lk->id[2]) {
case 0x00:
/* All okay */
break;
case LK_STUCK_KEY:
printk(KERN_ERR "lkkbd: Stuck key on keyboard at %s\n",
lk->phys);
break;
case LK_SELFTEST_FAILED:
printk(KERN_ERR
"lkkbd: Selftest failed on keyboard at %s, "
"keyboard may not work properly\n", lk->phys);
break;
default:
printk(KERN_ERR
"lkkbd: Unknown error %02x on keyboard at %s\n",
lk->id[2], lk->phys);
break;
}
/*
* Try to hint user if there's a stuck key.
*/
if (lk->id[2] == LK_STUCK_KEY && lk->id[3] != 0)
printk(KERN_ERR
"Scancode of stuck key is 0x%02x, keycode is 0x%04x\n",
lk->id[3], lk->keycode[lk->id[3]]);
}
/*
* lkkbd_interrupt() is called by the low level driver when a character
* is received.
*/
static irqreturn_t lkkbd_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct lkkbd *lk = serio_get_drvdata(serio);
struct input_dev *input_dev = lk->dev;
unsigned int keycode;
int i;
DBG(KERN_INFO "Got byte 0x%02x\n", data);
if (lk->ignore_bytes > 0) {
DBG(KERN_INFO "Ignoring a byte on %s\n", lk->name);
lk->id[LK_NUM_IGNORE_BYTES - lk->ignore_bytes--] = data;
if (lk->ignore_bytes == 0)
lkkbd_detection_done(lk);
return IRQ_HANDLED;
}
switch (data) {
case LK_ALL_KEYS_UP:
for (i = 0; i < ARRAY_SIZE(lkkbd_keycode); i++)
input_report_key(input_dev, lk->keycode[i], 0);
input_sync(input_dev);
break;
case 0x01:
DBG(KERN_INFO "Got 0x01, scheduling re-initialization\n");
lk->ignore_bytes = LK_NUM_IGNORE_BYTES;
lk->id[LK_NUM_IGNORE_BYTES - lk->ignore_bytes--] = data;
schedule_work(&lk->tq);
break;
case LK_METRONOME:
case LK_OUTPUT_ERROR:
case LK_INPUT_ERROR:
case LK_KBD_LOCKED:
case LK_KBD_TEST_MODE_ACK:
case LK_PREFIX_KEY_DOWN:
case LK_MODE_CHANGE_ACK:
case LK_RESPONSE_RESERVED:
DBG(KERN_INFO "Got %s and don't know how to handle...\n",
response_name(data));
break;
default:
keycode = lk->keycode[data];
if (keycode != KEY_RESERVED) {
input_report_key(input_dev, keycode,
!test_bit(keycode, input_dev->key));
input_sync(input_dev);
} else {
printk(KERN_WARNING
"%s: Unknown key with scancode 0x%02x on %s.\n",
__FILE__, data, lk->name);
}
}
return IRQ_HANDLED;
}
static void lkkbd_toggle_leds(struct lkkbd *lk)
{
struct serio *serio = lk->serio;
unsigned char leds_on = 0;
unsigned char leds_off = 0;
CHECK_LED(lk, leds_on, leds_off, LED_CAPSL, LK_LED_SHIFTLOCK);
CHECK_LED(lk, leds_on, leds_off, LED_COMPOSE, LK_LED_COMPOSE);
CHECK_LED(lk, leds_on, leds_off, LED_SCROLLL, LK_LED_SCROLLLOCK);
CHECK_LED(lk, leds_on, leds_off, LED_SLEEP, LK_LED_WAIT);
if (leds_on != 0) {
serio_write(serio, LK_CMD_LED_ON);
serio_write(serio, leds_on);
}
if (leds_off != 0) {
serio_write(serio, LK_CMD_LED_OFF);
serio_write(serio, leds_off);
}
}
static void lkkbd_toggle_keyclick(struct lkkbd *lk, bool on)
{
struct serio *serio = lk->serio;
if (on) {
DBG("%s: Activating key clicks\n", __func__);
serio_write(serio, LK_CMD_ENABLE_KEYCLICK);
serio_write(serio, volume_to_hw(lk->keyclick_volume));
serio_write(serio, LK_CMD_ENABLE_CTRCLICK);
serio_write(serio, volume_to_hw(lk->ctrlclick_volume));
} else {
DBG("%s: Deactivating key clicks\n", __func__);
serio_write(serio, LK_CMD_DISABLE_KEYCLICK);
serio_write(serio, LK_CMD_DISABLE_CTRCLICK);
}
}
/*
* lkkbd_event() handles events from the input module.
*/
static int lkkbd_event(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
struct lkkbd *lk = input_get_drvdata(dev);
switch (type) {
case EV_LED:
lkkbd_toggle_leds(lk);
return 0;
case EV_SND:
switch (code) {
case SND_CLICK:
lkkbd_toggle_keyclick(lk, value);
return 0;
case SND_BELL:
if (value != 0)
serio_write(lk->serio, LK_CMD_SOUND_BELL);
return 0;
}
break;
default:
printk(KERN_ERR "%s(): Got unknown type %d, code %d, value %d\n",
__func__, type, code, value);
}
return -1;
}
/*
* lkkbd_reinit() sets leds and beeps to a state the computer remembers they
* were in.
*/
static void lkkbd_reinit(struct work_struct *work)
{
struct lkkbd *lk = container_of(work, struct lkkbd, tq);
int division;
/* Ask for ID */
serio_write(lk->serio, LK_CMD_REQUEST_ID);
/* Reset parameters */
serio_write(lk->serio, LK_CMD_SET_DEFAULTS);
/* Set LEDs */
lkkbd_toggle_leds(lk);
/*
* Try to activate extended LK401 mode. This command will
* only work with a LK401 keyboard and grants access to
* LAlt, RAlt, RCompose and RShift.
*/
serio_write(lk->serio, LK_CMD_ENABLE_LK401);
/* Set all keys to UPDOWN mode */
for (division = 1; division <= 14; division++)
serio_write(lk->serio,
LK_CMD_SET_MODE(LK_MODE_UPDOWN, division));
/* Enable bell and set volume */
serio_write(lk->serio, LK_CMD_ENABLE_BELL);
serio_write(lk->serio, volume_to_hw(lk->bell_volume));
/* Enable/disable keyclick (and possibly set volume) */
lkkbd_toggle_keyclick(lk, test_bit(SND_CLICK, lk->dev->snd));
/* Sound the bell if needed */
if (test_bit(SND_BELL, lk->dev->snd))
serio_write(lk->serio, LK_CMD_SOUND_BELL);
}
/*
* lkkbd_connect() probes for a LK keyboard and fills the necessary structures.
*/
static int lkkbd_connect(struct serio *serio, struct serio_driver *drv)
{
struct lkkbd *lk;
struct input_dev *input_dev;
int i;
int err;
lk = kzalloc(sizeof(struct lkkbd), GFP_KERNEL);
input_dev = input_allocate_device();
if (!lk || !input_dev) {
err = -ENOMEM;
goto fail1;
}
lk->serio = serio;
lk->dev = input_dev;
INIT_WORK(&lk->tq, lkkbd_reinit);
lk->bell_volume = bell_volume;
lk->keyclick_volume = keyclick_volume;
lk->ctrlclick_volume = ctrlclick_volume;
memcpy(lk->keycode, lkkbd_keycode, sizeof(lk->keycode));
strscpy(lk->name, "DEC LK keyboard", sizeof(lk->name));
snprintf(lk->phys, sizeof(lk->phys), "%s/input0", serio->phys);
input_dev->name = lk->name;
input_dev->phys = lk->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_LKKBD;
input_dev->id.product = 0;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->event = lkkbd_event;
input_set_drvdata(input_dev, lk);
__set_bit(EV_KEY, input_dev->evbit);
__set_bit(EV_LED, input_dev->evbit);
__set_bit(EV_SND, input_dev->evbit);
__set_bit(EV_REP, input_dev->evbit);
__set_bit(LED_CAPSL, input_dev->ledbit);
__set_bit(LED_SLEEP, input_dev->ledbit);
__set_bit(LED_COMPOSE, input_dev->ledbit);
__set_bit(LED_SCROLLL, input_dev->ledbit);
__set_bit(SND_BELL, input_dev->sndbit);
__set_bit(SND_CLICK, input_dev->sndbit);
input_dev->keycode = lk->keycode;
input_dev->keycodesize = sizeof(lk->keycode[0]);
input_dev->keycodemax = ARRAY_SIZE(lk->keycode);
for (i = 0; i < LK_NUM_KEYCODES; i++)
__set_bit(lk->keycode[i], input_dev->keybit);
__clear_bit(KEY_RESERVED, input_dev->keybit);
serio_set_drvdata(serio, lk);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(lk->dev);
if (err)
goto fail3;
serio_write(lk->serio, LK_CMD_POWERCYCLE_RESET);
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(lk);
return err;
}
/*
* lkkbd_disconnect() unregisters and closes behind us.
*/
static void lkkbd_disconnect(struct serio *serio)
{
struct lkkbd *lk = serio_get_drvdata(serio);
input_get_device(lk->dev);
input_unregister_device(lk->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(lk->dev);
kfree(lk);
}
static const struct serio_device_id lkkbd_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_LKKBD,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, lkkbd_serio_ids);
static struct serio_driver lkkbd_drv = {
.driver = {
.name = "lkkbd",
},
.description = DRIVER_DESC,
.id_table = lkkbd_serio_ids,
.connect = lkkbd_connect,
.disconnect = lkkbd_disconnect,
.interrupt = lkkbd_interrupt,
};
module_serio_driver(lkkbd_drv);
|
linux-master
|
drivers/input/keyboard/lkkbd.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Copyright (c) 1999-2001 Vojtech Pavlik
*/
/*
* XT keyboard driver for Linux
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/input.h>
#include <linux/serio.h>
#define DRIVER_DESC "XT keyboard driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
#define XTKBD_EMUL0 0xe0
#define XTKBD_EMUL1 0xe1
#define XTKBD_KEY 0x7f
#define XTKBD_RELEASE 0x80
static unsigned char xtkbd_keycode[256] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 0, 0, 0, 87, 88, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 87, 88, 0, 0, 0, 0,110,111,103,108,105,
106
};
struct xtkbd {
unsigned char keycode[256];
struct input_dev *dev;
struct serio *serio;
char phys[32];
};
static irqreturn_t xtkbd_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct xtkbd *xtkbd = serio_get_drvdata(serio);
switch (data) {
case XTKBD_EMUL0:
case XTKBD_EMUL1:
break;
default:
if (xtkbd->keycode[data & XTKBD_KEY]) {
input_report_key(xtkbd->dev, xtkbd->keycode[data & XTKBD_KEY], !(data & XTKBD_RELEASE));
input_sync(xtkbd->dev);
} else {
printk(KERN_WARNING "xtkbd.c: Unknown key (scancode %#x) %s.\n",
data & XTKBD_KEY, data & XTKBD_RELEASE ? "released" : "pressed");
}
}
return IRQ_HANDLED;
}
static int xtkbd_connect(struct serio *serio, struct serio_driver *drv)
{
struct xtkbd *xtkbd;
struct input_dev *input_dev;
int err = -ENOMEM;
int i;
xtkbd = kmalloc(sizeof(struct xtkbd), GFP_KERNEL);
input_dev = input_allocate_device();
if (!xtkbd || !input_dev)
goto fail1;
xtkbd->serio = serio;
xtkbd->dev = input_dev;
snprintf(xtkbd->phys, sizeof(xtkbd->phys), "%s/input0", serio->phys);
memcpy(xtkbd->keycode, xtkbd_keycode, sizeof(xtkbd->keycode));
input_dev->name = "XT Keyboard";
input_dev->phys = xtkbd->phys;
input_dev->id.bustype = BUS_XTKBD;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
input_dev->keycode = xtkbd->keycode;
input_dev->keycodesize = sizeof(unsigned char);
input_dev->keycodemax = ARRAY_SIZE(xtkbd_keycode);
for (i = 0; i < 255; i++)
set_bit(xtkbd->keycode[i], input_dev->keybit);
clear_bit(0, input_dev->keybit);
serio_set_drvdata(serio, xtkbd);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(xtkbd->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(xtkbd);
return err;
}
static void xtkbd_disconnect(struct serio *serio)
{
struct xtkbd *xtkbd = serio_get_drvdata(serio);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_unregister_device(xtkbd->dev);
kfree(xtkbd);
}
static const struct serio_device_id xtkbd_serio_ids[] = {
{
.type = SERIO_XT,
.proto = SERIO_ANY,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, xtkbd_serio_ids);
static struct serio_driver xtkbd_drv = {
.driver = {
.name = "xtkbd",
},
.description = DRIVER_DESC,
.id_table = xtkbd_serio_ids,
.interrupt = xtkbd_interrupt,
.connect = xtkbd_connect,
.disconnect = xtkbd_disconnect,
};
module_serio_driver(xtkbd_drv);
|
linux-master
|
drivers/input/keyboard/xtkbd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) ST-Ericsson SA 2010
*
* Author: Naveen Kumar G <[email protected]> for ST-Ericsson
* Author: Sundar Iyer <[email protected]> for ST-Ericsson
*
* Keypad controller driver for the SKE (Scroll Key Encoder) module used in
* the Nomadik 8815 and Ux500 platforms.
*/
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/io.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/module.h>
#include <linux/platform_data/keypad-nomadik-ske.h>
/* SKE_CR bits */
#define SKE_KPMLT (0x1 << 6)
#define SKE_KPCN (0x7 << 3)
#define SKE_KPASEN (0x1 << 2)
#define SKE_KPASON (0x1 << 7)
/* SKE_IMSC bits */
#define SKE_KPIMA (0x1 << 2)
/* SKE_ICR bits */
#define SKE_KPICS (0x1 << 3)
#define SKE_KPICA (0x1 << 2)
/* SKE_RIS bits */
#define SKE_KPRISA (0x1 << 2)
#define SKE_KEYPAD_ROW_SHIFT 3
#define SKE_KPD_NUM_ROWS 8
#define SKE_KPD_NUM_COLS 8
/* keypad auto scan registers */
#define SKE_ASR0 0x20
#define SKE_ASR1 0x24
#define SKE_ASR2 0x28
#define SKE_ASR3 0x2C
#define SKE_NUM_ASRX_REGISTERS (4)
#define KEY_PRESSED_DELAY 10
/**
* struct ske_keypad - data structure used by keypad driver
* @irq: irq no
* @reg_base: ske registers base address
* @input: pointer to input device object
* @board: keypad platform device
* @keymap: matrix scan code table for keycodes
* @clk: clock structure pointer
* @pclk: clock structure pointer
* @ske_keypad_lock: spinlock protecting the keypad read/writes
*/
struct ske_keypad {
int irq;
void __iomem *reg_base;
struct input_dev *input;
const struct ske_keypad_platform_data *board;
unsigned short keymap[SKE_KPD_NUM_ROWS * SKE_KPD_NUM_COLS];
struct clk *clk;
struct clk *pclk;
spinlock_t ske_keypad_lock;
};
static void ske_keypad_set_bits(struct ske_keypad *keypad, u16 addr,
u8 mask, u8 data)
{
u32 ret;
spin_lock(&keypad->ske_keypad_lock);
ret = readl(keypad->reg_base + addr);
ret &= ~mask;
ret |= data;
writel(ret, keypad->reg_base + addr);
spin_unlock(&keypad->ske_keypad_lock);
}
/*
* ske_keypad_chip_init: init keypad controller configuration
*
* Enable Multi key press detection, auto scan mode
*/
static int __init ske_keypad_chip_init(struct ske_keypad *keypad)
{
u32 value;
int timeout = keypad->board->debounce_ms;
/* check SKE_RIS to be 0 */
while ((readl(keypad->reg_base + SKE_RIS) != 0x00000000) && timeout--)
cpu_relax();
if (timeout == -1)
return -EINVAL;
/*
* set debounce value
* keypad dbounce is configured in DBCR[15:8]
* dbounce value in steps of 32/32.768 ms
*/
spin_lock(&keypad->ske_keypad_lock);
value = readl(keypad->reg_base + SKE_DBCR);
value = value & 0xff;
value |= ((keypad->board->debounce_ms * 32000)/32768) << 8;
writel(value, keypad->reg_base + SKE_DBCR);
spin_unlock(&keypad->ske_keypad_lock);
/* enable multi key detection */
ske_keypad_set_bits(keypad, SKE_CR, 0x0, SKE_KPMLT);
/*
* set up the number of columns
* KPCN[5:3] defines no. of keypad columns to be auto scanned
*/
value = (keypad->board->kcol - 1) << 3;
ske_keypad_set_bits(keypad, SKE_CR, SKE_KPCN, value);
/* clear keypad interrupt for auto(and pending SW) scans */
ske_keypad_set_bits(keypad, SKE_ICR, 0x0, SKE_KPICA | SKE_KPICS);
/* un-mask keypad interrupts */
ske_keypad_set_bits(keypad, SKE_IMSC, 0x0, SKE_KPIMA);
/* enable automatic scan */
ske_keypad_set_bits(keypad, SKE_CR, 0x0, SKE_KPASEN);
return 0;
}
static void ske_keypad_report(struct ske_keypad *keypad, u8 status, int col)
{
int row = 0, code, pos;
struct input_dev *input = keypad->input;
u32 ske_ris;
int key_pressed;
int num_of_rows;
/* find out the row */
num_of_rows = hweight8(status);
do {
pos = __ffs(status);
row = pos;
status &= ~(1 << pos);
code = MATRIX_SCAN_CODE(row, col, SKE_KEYPAD_ROW_SHIFT);
ske_ris = readl(keypad->reg_base + SKE_RIS);
key_pressed = ske_ris & SKE_KPRISA;
input_event(input, EV_MSC, MSC_SCAN, code);
input_report_key(input, keypad->keymap[code], key_pressed);
input_sync(input);
num_of_rows--;
} while (num_of_rows);
}
static void ske_keypad_read_data(struct ske_keypad *keypad)
{
u8 status;
int col = 0;
int ske_asr, i;
/*
* Read the auto scan registers
*
* Each SKE_ASRx (x=0 to x=3) contains two row values.
* lower byte contains row value for column 2*x,
* upper byte contains row value for column 2*x + 1
*/
for (i = 0; i < SKE_NUM_ASRX_REGISTERS; i++) {
ske_asr = readl(keypad->reg_base + SKE_ASR0 + (4 * i));
if (!ske_asr)
continue;
/* now that ASRx is zero, find out the coloumn x and row y */
status = ske_asr & 0xff;
if (status) {
col = i * 2;
ske_keypad_report(keypad, status, col);
}
status = (ske_asr & 0xff00) >> 8;
if (status) {
col = (i * 2) + 1;
ske_keypad_report(keypad, status, col);
}
}
}
static irqreturn_t ske_keypad_irq(int irq, void *dev_id)
{
struct ske_keypad *keypad = dev_id;
int timeout = keypad->board->debounce_ms;
/* disable auto scan interrupt; mask the interrupt generated */
ske_keypad_set_bits(keypad, SKE_IMSC, ~SKE_KPIMA, 0x0);
ske_keypad_set_bits(keypad, SKE_ICR, 0x0, SKE_KPICA);
while ((readl(keypad->reg_base + SKE_CR) & SKE_KPASON) && --timeout)
cpu_relax();
/* SKEx registers are stable and can be read */
ske_keypad_read_data(keypad);
/* wait until raw interrupt is clear */
while ((readl(keypad->reg_base + SKE_RIS)) && --timeout)
msleep(KEY_PRESSED_DELAY);
/* enable auto scan interrupts */
ske_keypad_set_bits(keypad, SKE_IMSC, 0x0, SKE_KPIMA);
return IRQ_HANDLED;
}
static void ske_keypad_board_exit(void *data)
{
struct ske_keypad *keypad = data;
keypad->board->exit();
}
static int __init ske_keypad_probe(struct platform_device *pdev)
{
const struct ske_keypad_platform_data *plat =
dev_get_platdata(&pdev->dev);
struct device *dev = &pdev->dev;
struct ske_keypad *keypad;
struct input_dev *input;
int irq;
int error;
if (!plat) {
dev_err(&pdev->dev, "invalid keypad platform data\n");
return -EINVAL;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
keypad = devm_kzalloc(dev, sizeof(struct ske_keypad),
GFP_KERNEL);
input = devm_input_allocate_device(dev);
if (!keypad || !input) {
dev_err(&pdev->dev, "failed to allocate keypad memory\n");
return -ENOMEM;
}
keypad->irq = irq;
keypad->board = plat;
keypad->input = input;
spin_lock_init(&keypad->ske_keypad_lock);
keypad->reg_base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(keypad->reg_base))
return PTR_ERR(keypad->reg_base);
keypad->pclk = devm_clk_get_enabled(dev, "apb_pclk");
if (IS_ERR(keypad->pclk)) {
dev_err(&pdev->dev, "failed to get pclk\n");
return PTR_ERR(keypad->pclk);
}
keypad->clk = devm_clk_get_enabled(dev, NULL);
if (IS_ERR(keypad->clk)) {
dev_err(&pdev->dev, "failed to get clk\n");
return PTR_ERR(keypad->clk);
}
input->id.bustype = BUS_HOST;
input->name = "ux500-ske-keypad";
input->dev.parent = &pdev->dev;
error = matrix_keypad_build_keymap(plat->keymap_data, NULL,
SKE_KPD_NUM_ROWS, SKE_KPD_NUM_COLS,
keypad->keymap, input);
if (error) {
dev_err(&pdev->dev, "Failed to build keymap\n");
return error;
}
input_set_capability(input, EV_MSC, MSC_SCAN);
if (!plat->no_autorepeat)
__set_bit(EV_REP, input->evbit);
/* go through board initialization helpers */
if (keypad->board->init)
keypad->board->init();
if (keypad->board->exit) {
error = devm_add_action_or_reset(dev, ske_keypad_board_exit,
keypad);
if (error)
return error;
}
error = ske_keypad_chip_init(keypad);
if (error) {
dev_err(&pdev->dev, "unable to init keypad hardware\n");
return error;
}
error = devm_request_threaded_irq(dev, keypad->irq,
NULL, ske_keypad_irq,
IRQF_ONESHOT, "ske-keypad", keypad);
if (error) {
dev_err(&pdev->dev, "allocate irq %d failed\n", keypad->irq);
return error;
}
error = input_register_device(input);
if (error) {
dev_err(&pdev->dev,
"unable to register input device: %d\n", error);
return error;
}
if (plat->wakeup_enable)
device_init_wakeup(&pdev->dev, true);
platform_set_drvdata(pdev, keypad);
return 0;
}
static int ske_keypad_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct ske_keypad *keypad = platform_get_drvdata(pdev);
int irq = platform_get_irq(pdev, 0);
if (device_may_wakeup(dev))
enable_irq_wake(irq);
else
ske_keypad_set_bits(keypad, SKE_IMSC, ~SKE_KPIMA, 0x0);
return 0;
}
static int ske_keypad_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct ske_keypad *keypad = platform_get_drvdata(pdev);
int irq = platform_get_irq(pdev, 0);
if (device_may_wakeup(dev))
disable_irq_wake(irq);
else
ske_keypad_set_bits(keypad, SKE_IMSC, 0x0, SKE_KPIMA);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(ske_keypad_dev_pm_ops,
ske_keypad_suspend, ske_keypad_resume);
static struct platform_driver ske_keypad_driver = {
.driver = {
.name = "nmk-ske-keypad",
.pm = pm_sleep_ptr(&ske_keypad_dev_pm_ops),
},
};
module_platform_driver_probe(ske_keypad_driver, ske_keypad_probe);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Naveen Kumar <[email protected]> / Sundar Iyer <[email protected]>");
MODULE_DESCRIPTION("Nomadik Scroll-Key-Encoder Keypad Driver");
MODULE_ALIAS("platform:nomadik-ske-keypad");
|
linux-master
|
drivers/input/keyboard/nomadik-ske-keypad.c
|
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (C) 2022 MediaTek Inc.
* Author Fengping Yu <[email protected]>
*/
#include <linux/bitops.h>
#include <linux/clk.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/property.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#define MTK_KPD_NAME "mt6779-keypad"
#define MTK_KPD_MEM 0x0004
#define MTK_KPD_DEBOUNCE 0x0018
#define MTK_KPD_DEBOUNCE_MASK GENMASK(13, 0)
#define MTK_KPD_DEBOUNCE_MAX_MS 256
#define MTK_KPD_SEL 0x0020
#define MTK_KPD_SEL_DOUBLE_KP_MODE BIT(0)
#define MTK_KPD_SEL_COL GENMASK(15, 10)
#define MTK_KPD_SEL_ROW GENMASK(9, 4)
#define MTK_KPD_SEL_COLMASK(c) GENMASK((c) + 9, 10)
#define MTK_KPD_SEL_ROWMASK(r) GENMASK((r) + 3, 4)
#define MTK_KPD_NUM_MEMS 5
#define MTK_KPD_NUM_BITS 136 /* 4*32+8 MEM5 only use 8 BITS */
struct mt6779_keypad {
struct regmap *regmap;
struct input_dev *input_dev;
struct clk *clk;
u32 n_rows;
u32 n_cols;
void (*calc_row_col)(unsigned int key,
unsigned int *row, unsigned int *col);
DECLARE_BITMAP(keymap_state, MTK_KPD_NUM_BITS);
};
static const struct regmap_config mt6779_keypad_regmap_cfg = {
.reg_bits = 32,
.val_bits = 32,
.reg_stride = sizeof(u32),
.max_register = 36,
};
static irqreturn_t mt6779_keypad_irq_handler(int irq, void *dev_id)
{
struct mt6779_keypad *keypad = dev_id;
const unsigned short *keycode = keypad->input_dev->keycode;
DECLARE_BITMAP(new_state, MTK_KPD_NUM_BITS);
DECLARE_BITMAP(change, MTK_KPD_NUM_BITS);
unsigned int bit_nr, key;
unsigned int row, col;
unsigned int scancode;
unsigned int row_shift = get_count_order(keypad->n_cols);
bool pressed;
regmap_bulk_read(keypad->regmap, MTK_KPD_MEM,
new_state, MTK_KPD_NUM_MEMS);
bitmap_xor(change, new_state, keypad->keymap_state, MTK_KPD_NUM_BITS);
for_each_set_bit(bit_nr, change, MTK_KPD_NUM_BITS) {
/*
* Registers are 32bits, but only bits [15:0] are used to
* indicate key status.
*/
if (bit_nr % 32 >= 16)
continue;
key = bit_nr / 32 * 16 + bit_nr % 32;
keypad->calc_row_col(key, &row, &col);
scancode = MATRIX_SCAN_CODE(row, col, row_shift);
/* 1: not pressed, 0: pressed */
pressed = !test_bit(bit_nr, new_state);
dev_dbg(&keypad->input_dev->dev, "%s",
pressed ? "pressed" : "released");
input_event(keypad->input_dev, EV_MSC, MSC_SCAN, scancode);
input_report_key(keypad->input_dev, keycode[scancode], pressed);
input_sync(keypad->input_dev);
dev_dbg(&keypad->input_dev->dev,
"report Linux keycode = %d\n", keycode[scancode]);
}
bitmap_copy(keypad->keymap_state, new_state, MTK_KPD_NUM_BITS);
return IRQ_HANDLED;
}
static void mt6779_keypad_clk_disable(void *data)
{
clk_disable_unprepare(data);
}
static void mt6779_keypad_calc_row_col_single(unsigned int key,
unsigned int *row,
unsigned int *col)
{
*row = key / 9;
*col = key % 9;
}
static void mt6779_keypad_calc_row_col_double(unsigned int key,
unsigned int *row,
unsigned int *col)
{
*row = key / 13;
*col = (key % 13) / 2;
}
static int mt6779_keypad_pdrv_probe(struct platform_device *pdev)
{
struct mt6779_keypad *keypad;
void __iomem *base;
int irq;
u32 debounce;
u32 keys_per_group;
bool wakeup;
int error;
keypad = devm_kzalloc(&pdev->dev, sizeof(*keypad), GFP_KERNEL);
if (!keypad)
return -ENOMEM;
base = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(base))
return PTR_ERR(base);
keypad->regmap = devm_regmap_init_mmio(&pdev->dev, base,
&mt6779_keypad_regmap_cfg);
if (IS_ERR(keypad->regmap)) {
dev_err(&pdev->dev,
"regmap init failed:%pe\n", keypad->regmap);
return PTR_ERR(keypad->regmap);
}
bitmap_fill(keypad->keymap_state, MTK_KPD_NUM_BITS);
keypad->input_dev = devm_input_allocate_device(&pdev->dev);
if (!keypad->input_dev) {
dev_err(&pdev->dev, "Failed to allocate input dev\n");
return -ENOMEM;
}
keypad->input_dev->name = MTK_KPD_NAME;
keypad->input_dev->id.bustype = BUS_HOST;
error = matrix_keypad_parse_properties(&pdev->dev, &keypad->n_rows,
&keypad->n_cols);
if (error) {
dev_err(&pdev->dev, "Failed to parse keypad params\n");
return error;
}
if (device_property_read_u32(&pdev->dev, "debounce-delay-ms",
&debounce))
debounce = 16;
if (debounce > MTK_KPD_DEBOUNCE_MAX_MS) {
dev_err(&pdev->dev,
"Debounce time exceeds the maximum allowed time %dms\n",
MTK_KPD_DEBOUNCE_MAX_MS);
return -EINVAL;
}
if (device_property_read_u32(&pdev->dev, "mediatek,keys-per-group",
&keys_per_group))
keys_per_group = 1;
switch (keys_per_group) {
case 1:
keypad->calc_row_col = mt6779_keypad_calc_row_col_single;
break;
case 2:
keypad->calc_row_col = mt6779_keypad_calc_row_col_double;
break;
default:
dev_err(&pdev->dev,
"Invalid keys-per-group: %d\n", keys_per_group);
return -EINVAL;
}
wakeup = device_property_read_bool(&pdev->dev, "wakeup-source");
dev_dbg(&pdev->dev, "n_row=%d n_col=%d debounce=%d\n",
keypad->n_rows, keypad->n_cols, debounce);
error = matrix_keypad_build_keymap(NULL, NULL,
keypad->n_rows, keypad->n_cols,
NULL, keypad->input_dev);
if (error) {
dev_err(&pdev->dev, "Failed to build keymap\n");
return error;
}
input_set_capability(keypad->input_dev, EV_MSC, MSC_SCAN);
regmap_write(keypad->regmap, MTK_KPD_DEBOUNCE,
(debounce * (1 << 5)) & MTK_KPD_DEBOUNCE_MASK);
if (keys_per_group == 2)
regmap_update_bits(keypad->regmap, MTK_KPD_SEL,
MTK_KPD_SEL_DOUBLE_KP_MODE,
MTK_KPD_SEL_DOUBLE_KP_MODE);
regmap_update_bits(keypad->regmap, MTK_KPD_SEL, MTK_KPD_SEL_ROW,
MTK_KPD_SEL_ROWMASK(keypad->n_rows));
regmap_update_bits(keypad->regmap, MTK_KPD_SEL, MTK_KPD_SEL_COL,
MTK_KPD_SEL_COLMASK(keypad->n_cols));
keypad->clk = devm_clk_get(&pdev->dev, "kpd");
if (IS_ERR(keypad->clk))
return PTR_ERR(keypad->clk);
error = clk_prepare_enable(keypad->clk);
if (error) {
dev_err(&pdev->dev, "cannot prepare/enable keypad clock\n");
return error;
}
error = devm_add_action_or_reset(&pdev->dev, mt6779_keypad_clk_disable,
keypad->clk);
if (error)
return error;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
error = devm_request_threaded_irq(&pdev->dev, irq,
NULL, mt6779_keypad_irq_handler,
IRQF_ONESHOT, MTK_KPD_NAME, keypad);
if (error) {
dev_err(&pdev->dev, "Failed to request IRQ#%d: %d\n",
irq, error);
return error;
}
error = input_register_device(keypad->input_dev);
if (error) {
dev_err(&pdev->dev, "Failed to register device\n");
return error;
}
error = device_init_wakeup(&pdev->dev, wakeup);
if (error)
dev_warn(&pdev->dev, "device_init_wakeup() failed: %d\n",
error);
return 0;
}
static const struct of_device_id mt6779_keypad_of_match[] = {
{ .compatible = "mediatek,mt6779-keypad" },
{ .compatible = "mediatek,mt6873-keypad" },
{ /* sentinel */ }
};
static struct platform_driver mt6779_keypad_pdrv = {
.probe = mt6779_keypad_pdrv_probe,
.driver = {
.name = MTK_KPD_NAME,
.of_match_table = mt6779_keypad_of_match,
},
};
module_platform_driver(mt6779_keypad_pdrv);
MODULE_AUTHOR("Mediatek Corporation");
MODULE_DESCRIPTION("MTK Keypad (KPD) Driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/mt6779-keypad.c
|
/*
* Driver for TCA8418 I2C keyboard
*
* Copyright (C) 2011 Fuel7, Inc. All rights reserved.
*
* Author: Kyle Manna <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License v2 as published by the Free Software Foundation.
*
* 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 021110-1307, USA.
*
* If you can't comply with GPLv2, alternative licensing terms may be
* arranged. Please contact Fuel7, Inc. (http://fuel7.com/) for proprietary
* alternative licensing inquiries.
*/
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/input/matrix_keypad.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/property.h>
#include <linux/slab.h>
#include <linux/types.h>
/* TCA8418 hardware limits */
#define TCA8418_MAX_ROWS 8
#define TCA8418_MAX_COLS 10
/* TCA8418 register offsets */
#define REG_CFG 0x01
#define REG_INT_STAT 0x02
#define REG_KEY_LCK_EC 0x03
#define REG_KEY_EVENT_A 0x04
#define REG_KEY_EVENT_B 0x05
#define REG_KEY_EVENT_C 0x06
#define REG_KEY_EVENT_D 0x07
#define REG_KEY_EVENT_E 0x08
#define REG_KEY_EVENT_F 0x09
#define REG_KEY_EVENT_G 0x0A
#define REG_KEY_EVENT_H 0x0B
#define REG_KEY_EVENT_I 0x0C
#define REG_KEY_EVENT_J 0x0D
#define REG_KP_LCK_TIMER 0x0E
#define REG_UNLOCK1 0x0F
#define REG_UNLOCK2 0x10
#define REG_GPIO_INT_STAT1 0x11
#define REG_GPIO_INT_STAT2 0x12
#define REG_GPIO_INT_STAT3 0x13
#define REG_GPIO_DAT_STAT1 0x14
#define REG_GPIO_DAT_STAT2 0x15
#define REG_GPIO_DAT_STAT3 0x16
#define REG_GPIO_DAT_OUT1 0x17
#define REG_GPIO_DAT_OUT2 0x18
#define REG_GPIO_DAT_OUT3 0x19
#define REG_GPIO_INT_EN1 0x1A
#define REG_GPIO_INT_EN2 0x1B
#define REG_GPIO_INT_EN3 0x1C
#define REG_KP_GPIO1 0x1D
#define REG_KP_GPIO2 0x1E
#define REG_KP_GPIO3 0x1F
#define REG_GPI_EM1 0x20
#define REG_GPI_EM2 0x21
#define REG_GPI_EM3 0x22
#define REG_GPIO_DIR1 0x23
#define REG_GPIO_DIR2 0x24
#define REG_GPIO_DIR3 0x25
#define REG_GPIO_INT_LVL1 0x26
#define REG_GPIO_INT_LVL2 0x27
#define REG_GPIO_INT_LVL3 0x28
#define REG_DEBOUNCE_DIS1 0x29
#define REG_DEBOUNCE_DIS2 0x2A
#define REG_DEBOUNCE_DIS3 0x2B
#define REG_GPIO_PULL1 0x2C
#define REG_GPIO_PULL2 0x2D
#define REG_GPIO_PULL3 0x2E
/* TCA8418 bit definitions */
#define CFG_AI BIT(7)
#define CFG_GPI_E_CFG BIT(6)
#define CFG_OVR_FLOW_M BIT(5)
#define CFG_INT_CFG BIT(4)
#define CFG_OVR_FLOW_IEN BIT(3)
#define CFG_K_LCK_IEN BIT(2)
#define CFG_GPI_IEN BIT(1)
#define CFG_KE_IEN BIT(0)
#define INT_STAT_CAD_INT BIT(4)
#define INT_STAT_OVR_FLOW_INT BIT(3)
#define INT_STAT_K_LCK_INT BIT(2)
#define INT_STAT_GPI_INT BIT(1)
#define INT_STAT_K_INT BIT(0)
/* TCA8418 register masks */
#define KEY_LCK_EC_KEC 0x7
#define KEY_EVENT_CODE 0x7f
#define KEY_EVENT_VALUE 0x80
struct tca8418_keypad {
struct i2c_client *client;
struct input_dev *input;
unsigned int row_shift;
};
/*
* Write a byte to the TCA8418
*/
static int tca8418_write_byte(struct tca8418_keypad *keypad_data,
int reg, u8 val)
{
int error;
error = i2c_smbus_write_byte_data(keypad_data->client, reg, val);
if (error < 0) {
dev_err(&keypad_data->client->dev,
"%s failed, reg: %d, val: %d, error: %d\n",
__func__, reg, val, error);
return error;
}
return 0;
}
/*
* Read a byte from the TCA8418
*/
static int tca8418_read_byte(struct tca8418_keypad *keypad_data,
int reg, u8 *val)
{
int error;
error = i2c_smbus_read_byte_data(keypad_data->client, reg);
if (error < 0) {
dev_err(&keypad_data->client->dev,
"%s failed, reg: %d, error: %d\n",
__func__, reg, error);
return error;
}
*val = (u8)error;
return 0;
}
static void tca8418_read_keypad(struct tca8418_keypad *keypad_data)
{
struct input_dev *input = keypad_data->input;
unsigned short *keymap = input->keycode;
int error, col, row;
u8 reg, state, code;
do {
error = tca8418_read_byte(keypad_data, REG_KEY_EVENT_A, ®);
if (error < 0) {
dev_err(&keypad_data->client->dev,
"unable to read REG_KEY_EVENT_A\n");
break;
}
/* Assume that key code 0 signifies empty FIFO */
if (reg <= 0)
break;
state = reg & KEY_EVENT_VALUE;
code = reg & KEY_EVENT_CODE;
row = code / TCA8418_MAX_COLS;
col = code % TCA8418_MAX_COLS;
row = (col) ? row : row - 1;
col = (col) ? col - 1 : TCA8418_MAX_COLS - 1;
code = MATRIX_SCAN_CODE(row, col, keypad_data->row_shift);
input_event(input, EV_MSC, MSC_SCAN, code);
input_report_key(input, keymap[code], state);
} while (1);
input_sync(input);
}
/*
* Threaded IRQ handler and this can (and will) sleep.
*/
static irqreturn_t tca8418_irq_handler(int irq, void *dev_id)
{
struct tca8418_keypad *keypad_data = dev_id;
u8 reg;
int error;
error = tca8418_read_byte(keypad_data, REG_INT_STAT, ®);
if (error) {
dev_err(&keypad_data->client->dev,
"unable to read REG_INT_STAT\n");
return IRQ_NONE;
}
if (!reg)
return IRQ_NONE;
if (reg & INT_STAT_OVR_FLOW_INT)
dev_warn(&keypad_data->client->dev, "overflow occurred\n");
if (reg & INT_STAT_K_INT)
tca8418_read_keypad(keypad_data);
/* Clear all interrupts, even IRQs we didn't check (GPI, CAD, LCK) */
reg = 0xff;
error = tca8418_write_byte(keypad_data, REG_INT_STAT, reg);
if (error)
dev_err(&keypad_data->client->dev,
"unable to clear REG_INT_STAT\n");
return IRQ_HANDLED;
}
/*
* Configure the TCA8418 for keypad operation
*/
static int tca8418_configure(struct tca8418_keypad *keypad_data,
u32 rows, u32 cols)
{
int reg, error = 0;
/* Assemble a mask for row and column registers */
reg = ~(~0 << rows);
reg += (~(~0 << cols)) << 8;
/* Set registers to keypad mode */
error |= tca8418_write_byte(keypad_data, REG_KP_GPIO1, reg);
error |= tca8418_write_byte(keypad_data, REG_KP_GPIO2, reg >> 8);
error |= tca8418_write_byte(keypad_data, REG_KP_GPIO3, reg >> 16);
/* Enable column debouncing */
error |= tca8418_write_byte(keypad_data, REG_DEBOUNCE_DIS1, reg);
error |= tca8418_write_byte(keypad_data, REG_DEBOUNCE_DIS2, reg >> 8);
error |= tca8418_write_byte(keypad_data, REG_DEBOUNCE_DIS3, reg >> 16);
if (error)
return error;
error = tca8418_write_byte(keypad_data, REG_CFG,
CFG_INT_CFG | CFG_OVR_FLOW_IEN | CFG_KE_IEN);
return error;
}
static int tca8418_keypad_probe(struct i2c_client *client)
{
struct device *dev = &client->dev;
struct tca8418_keypad *keypad_data;
struct input_dev *input;
u32 rows = 0, cols = 0;
int error, row_shift;
u8 reg;
/* Check i2c driver capabilities */
if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE)) {
dev_err(dev, "%s adapter not supported\n",
dev_driver_string(&client->adapter->dev));
return -ENODEV;
}
error = matrix_keypad_parse_properties(dev, &rows, &cols);
if (error)
return error;
if (!rows || rows > TCA8418_MAX_ROWS) {
dev_err(dev, "invalid rows\n");
return -EINVAL;
}
if (!cols || cols > TCA8418_MAX_COLS) {
dev_err(dev, "invalid columns\n");
return -EINVAL;
}
row_shift = get_count_order(cols);
/* Allocate memory for keypad_data and input device */
keypad_data = devm_kzalloc(dev, sizeof(*keypad_data), GFP_KERNEL);
if (!keypad_data)
return -ENOMEM;
keypad_data->client = client;
keypad_data->row_shift = row_shift;
/* Read key lock register, if this fails assume device not present */
error = tca8418_read_byte(keypad_data, REG_KEY_LCK_EC, ®);
if (error)
return -ENODEV;
/* Configure input device */
input = devm_input_allocate_device(dev);
if (!input)
return -ENOMEM;
keypad_data->input = input;
input->name = client->name;
input->id.bustype = BUS_I2C;
input->id.vendor = 0x0001;
input->id.product = 0x001;
input->id.version = 0x0001;
error = matrix_keypad_build_keymap(NULL, NULL, rows, cols, NULL, input);
if (error) {
dev_err(dev, "Failed to build keymap\n");
return error;
}
if (device_property_read_bool(dev, "keypad,autorepeat"))
__set_bit(EV_REP, input->evbit);
input_set_capability(input, EV_MSC, MSC_SCAN);
error = devm_request_threaded_irq(dev, client->irq,
NULL, tca8418_irq_handler,
IRQF_SHARED | IRQF_ONESHOT,
client->name, keypad_data);
if (error) {
dev_err(dev, "Unable to claim irq %d; error %d\n",
client->irq, error);
return error;
}
/* Initialize the chip */
error = tca8418_configure(keypad_data, rows, cols);
if (error < 0)
return error;
error = input_register_device(input);
if (error) {
dev_err(dev, "Unable to register input device, error: %d\n",
error);
return error;
}
return 0;
}
static const struct i2c_device_id tca8418_id[] = {
{ "tca8418", 8418, },
{ }
};
MODULE_DEVICE_TABLE(i2c, tca8418_id);
static const struct of_device_id tca8418_dt_ids[] = {
{ .compatible = "ti,tca8418", },
{ }
};
MODULE_DEVICE_TABLE(of, tca8418_dt_ids);
static struct i2c_driver tca8418_keypad_driver = {
.driver = {
.name = "tca8418_keypad",
.of_match_table = tca8418_dt_ids,
},
.probe = tca8418_keypad_probe,
.id_table = tca8418_id,
};
static int __init tca8418_keypad_init(void)
{
return i2c_add_driver(&tca8418_keypad_driver);
}
subsys_initcall(tca8418_keypad_init);
static void __exit tca8418_keypad_exit(void)
{
i2c_del_driver(&tca8418_keypad_driver);
}
module_exit(tca8418_keypad_exit);
MODULE_AUTHOR("Kyle Manna <[email protected]>");
MODULE_DESCRIPTION("Keypad driver for TCA8418");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/tca8418_keypad.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Input driver for resistor ladder connected on ADC
*
* Copyright (c) 2016 Alexandre Belloni
*/
#include <linux/err.h>
#include <linux/iio/consumer.h>
#include <linux/iio/types.h>
#include <linux/input.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/property.h>
#include <linux/slab.h>
struct adc_keys_button {
u32 voltage;
u32 keycode;
};
struct adc_keys_state {
struct iio_channel *channel;
u32 num_keys;
u32 last_key;
u32 keyup_voltage;
const struct adc_keys_button *map;
};
static void adc_keys_poll(struct input_dev *input)
{
struct adc_keys_state *st = input_get_drvdata(input);
int i, value, ret;
u32 diff, closest = 0xffffffff;
int keycode = 0;
ret = iio_read_channel_processed(st->channel, &value);
if (unlikely(ret < 0)) {
/* Forcibly release key if any was pressed */
value = st->keyup_voltage;
} else {
for (i = 0; i < st->num_keys; i++) {
diff = abs(st->map[i].voltage - value);
if (diff < closest) {
closest = diff;
keycode = st->map[i].keycode;
}
}
}
if (abs(st->keyup_voltage - value) < closest)
keycode = 0;
if (st->last_key && st->last_key != keycode)
input_report_key(input, st->last_key, 0);
if (keycode)
input_report_key(input, keycode, 1);
input_sync(input);
st->last_key = keycode;
}
static int adc_keys_load_keymap(struct device *dev, struct adc_keys_state *st)
{
struct adc_keys_button *map;
struct fwnode_handle *child;
int i;
st->num_keys = device_get_child_node_count(dev);
if (st->num_keys == 0) {
dev_err(dev, "keymap is missing\n");
return -EINVAL;
}
map = devm_kmalloc_array(dev, st->num_keys, sizeof(*map), GFP_KERNEL);
if (!map)
return -ENOMEM;
i = 0;
device_for_each_child_node(dev, child) {
if (fwnode_property_read_u32(child, "press-threshold-microvolt",
&map[i].voltage)) {
dev_err(dev, "Key with invalid or missing voltage\n");
fwnode_handle_put(child);
return -EINVAL;
}
map[i].voltage /= 1000;
if (fwnode_property_read_u32(child, "linux,code",
&map[i].keycode)) {
dev_err(dev, "Key with invalid or missing linux,code\n");
fwnode_handle_put(child);
return -EINVAL;
}
i++;
}
st->map = map;
return 0;
}
static int adc_keys_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct adc_keys_state *st;
struct input_dev *input;
enum iio_chan_type type;
int i, value;
int error;
st = devm_kzalloc(dev, sizeof(*st), GFP_KERNEL);
if (!st)
return -ENOMEM;
st->channel = devm_iio_channel_get(dev, "buttons");
if (IS_ERR(st->channel))
return PTR_ERR(st->channel);
if (!st->channel->indio_dev)
return -ENXIO;
error = iio_get_channel_type(st->channel, &type);
if (error < 0)
return error;
if (type != IIO_VOLTAGE) {
dev_err(dev, "Incompatible channel type %d\n", type);
return -EINVAL;
}
if (device_property_read_u32(dev, "keyup-threshold-microvolt",
&st->keyup_voltage)) {
dev_err(dev, "Invalid or missing keyup voltage\n");
return -EINVAL;
}
st->keyup_voltage /= 1000;
error = adc_keys_load_keymap(dev, st);
if (error)
return error;
input = devm_input_allocate_device(dev);
if (!input) {
dev_err(dev, "failed to allocate input device\n");
return -ENOMEM;
}
input_set_drvdata(input, st);
input->name = pdev->name;
input->phys = "adc-keys/input0";
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < st->num_keys; i++)
__set_bit(st->map[i].keycode, input->keybit);
if (device_property_read_bool(dev, "autorepeat"))
__set_bit(EV_REP, input->evbit);
error = input_setup_polling(input, adc_keys_poll);
if (error) {
dev_err(dev, "Unable to set up polling: %d\n", error);
return error;
}
if (!device_property_read_u32(dev, "poll-interval", &value))
input_set_poll_interval(input, value);
error = input_register_device(input);
if (error) {
dev_err(dev, "Unable to register input device: %d\n", error);
return error;
}
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id adc_keys_of_match[] = {
{ .compatible = "adc-keys", },
{ }
};
MODULE_DEVICE_TABLE(of, adc_keys_of_match);
#endif
static struct platform_driver adc_keys_driver = {
.driver = {
.name = "adc_keys",
.of_match_table = of_match_ptr(adc_keys_of_match),
},
.probe = adc_keys_probe,
};
module_platform_driver(adc_keys_driver);
MODULE_AUTHOR("Alexandre Belloni <[email protected]>");
MODULE_DESCRIPTION("Input driver for resistor ladder connected on ADC");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/keyboard/adc-keys.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* drivers/i2c/chips/lm8323.c
*
* Copyright (C) 2007-2009 Nokia Corporation
*
* Written by Daniel Stone <[email protected]>
* Timo O. Karjalainen <[email protected]>
*
* Updated by Felipe Balbi <[email protected]>
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/leds.h>
#include <linux/platform_data/lm8323.h>
#include <linux/pm.h>
#include <linux/slab.h>
/* Commands to send to the chip. */
#define LM8323_CMD_READ_ID 0x80 /* Read chip ID. */
#define LM8323_CMD_WRITE_CFG 0x81 /* Set configuration item. */
#define LM8323_CMD_READ_INT 0x82 /* Get interrupt status. */
#define LM8323_CMD_RESET 0x83 /* Reset, same as external one */
#define LM8323_CMD_WRITE_PORT_SEL 0x85 /* Set GPIO in/out. */
#define LM8323_CMD_WRITE_PORT_STATE 0x86 /* Set GPIO pullup. */
#define LM8323_CMD_READ_PORT_SEL 0x87 /* Get GPIO in/out. */
#define LM8323_CMD_READ_PORT_STATE 0x88 /* Get GPIO pullup. */
#define LM8323_CMD_READ_FIFO 0x89 /* Read byte from FIFO. */
#define LM8323_CMD_RPT_READ_FIFO 0x8a /* Read FIFO (no increment). */
#define LM8323_CMD_SET_ACTIVE 0x8b /* Set active time. */
#define LM8323_CMD_READ_ERR 0x8c /* Get error status. */
#define LM8323_CMD_READ_ROTATOR 0x8e /* Read rotator status. */
#define LM8323_CMD_SET_DEBOUNCE 0x8f /* Set debouncing time. */
#define LM8323_CMD_SET_KEY_SIZE 0x90 /* Set keypad size. */
#define LM8323_CMD_READ_KEY_SIZE 0x91 /* Get keypad size. */
#define LM8323_CMD_READ_CFG 0x92 /* Get configuration item. */
#define LM8323_CMD_WRITE_CLOCK 0x93 /* Set clock config. */
#define LM8323_CMD_READ_CLOCK 0x94 /* Get clock config. */
#define LM8323_CMD_PWM_WRITE 0x95 /* Write PWM script. */
#define LM8323_CMD_START_PWM 0x96 /* Start PWM engine. */
#define LM8323_CMD_STOP_PWM 0x97 /* Stop PWM engine. */
/* Interrupt status. */
#define INT_KEYPAD 0x01 /* Key event. */
#define INT_ROTATOR 0x02 /* Rotator event. */
#define INT_ERROR 0x08 /* Error: use CMD_READ_ERR. */
#define INT_NOINIT 0x10 /* Lost configuration. */
#define INT_PWM1 0x20 /* PWM1 stopped. */
#define INT_PWM2 0x40 /* PWM2 stopped. */
#define INT_PWM3 0x80 /* PWM3 stopped. */
/* Errors (signalled by INT_ERROR, read with CMD_READ_ERR). */
#define ERR_BADPAR 0x01 /* Bad parameter. */
#define ERR_CMDUNK 0x02 /* Unknown command. */
#define ERR_KEYOVR 0x04 /* Too many keys pressed. */
#define ERR_FIFOOVER 0x40 /* FIFO overflow. */
/* Configuration keys (CMD_{WRITE,READ}_CFG). */
#define CFG_MUX1SEL 0x01 /* Select MUX1_OUT input. */
#define CFG_MUX1EN 0x02 /* Enable MUX1_OUT. */
#define CFG_MUX2SEL 0x04 /* Select MUX2_OUT input. */
#define CFG_MUX2EN 0x08 /* Enable MUX2_OUT. */
#define CFG_PSIZE 0x20 /* Package size (must be 0). */
#define CFG_ROTEN 0x40 /* Enable rotator. */
/* Clock settings (CMD_{WRITE,READ}_CLOCK). */
#define CLK_RCPWM_INTERNAL 0x00
#define CLK_RCPWM_EXTERNAL 0x03
#define CLK_SLOWCLKEN 0x08 /* Enable 32.768kHz clock. */
#define CLK_SLOWCLKOUT 0x40 /* Enable slow pulse output. */
/* The possible addresses corresponding to CONFIG1 and CONFIG2 pin wirings. */
#define LM8323_I2C_ADDR00 (0x84 >> 1) /* 1000 010x */
#define LM8323_I2C_ADDR01 (0x86 >> 1) /* 1000 011x */
#define LM8323_I2C_ADDR10 (0x88 >> 1) /* 1000 100x */
#define LM8323_I2C_ADDR11 (0x8A >> 1) /* 1000 101x */
/* Key event fifo length */
#define LM8323_FIFO_LEN 15
/* Commands for PWM engine; feed in with PWM_WRITE. */
/* Load ramp counter from duty cycle field (range 0 - 0xff). */
#define PWM_SET(v) (0x4000 | ((v) & 0xff))
/* Go to start of script. */
#define PWM_GOTOSTART 0x0000
/*
* Stop engine (generates interrupt). If reset is 1, clear the program
* counter, else leave it.
*/
#define PWM_END(reset) (0xc000 | (!!(reset) << 11))
/*
* Ramp. If s is 1, divide clock by 512, else divide clock by 16.
* Take t clock scales (up to 63) per step, for n steps (up to 126).
* If u is set, ramp up, else ramp down.
*/
#define PWM_RAMP(s, t, n, u) ((!!(s) << 14) | ((t) & 0x3f) << 8 | \
((n) & 0x7f) | ((u) ? 0 : 0x80))
/*
* Loop (i.e. jump back to pos) for a given number of iterations (up to 63).
* If cnt is zero, execute until PWM_END is encountered.
*/
#define PWM_LOOP(cnt, pos) (0xa000 | (((cnt) & 0x3f) << 7) | \
((pos) & 0x3f))
/*
* Wait for trigger. Argument is a mask of channels, shifted by the channel
* number, e.g. 0xa for channels 3 and 1. Note that channels are numbered
* from 1, not 0.
*/
#define PWM_WAIT_TRIG(chans) (0xe000 | (((chans) & 0x7) << 6))
/* Send trigger. Argument is same as PWM_WAIT_TRIG. */
#define PWM_SEND_TRIG(chans) (0xe000 | ((chans) & 0x7))
struct lm8323_pwm {
int id;
int fade_time;
int brightness;
int desired_brightness;
bool enabled;
bool running;
/* pwm lock */
struct mutex lock;
struct work_struct work;
struct led_classdev cdev;
struct lm8323_chip *chip;
};
struct lm8323_chip {
/* device lock */
struct mutex lock;
struct i2c_client *client;
struct input_dev *idev;
bool kp_enabled;
bool pm_suspend;
unsigned keys_down;
char phys[32];
unsigned short keymap[LM8323_KEYMAP_SIZE];
int size_x;
int size_y;
int debounce_time;
int active_time;
struct lm8323_pwm pwm[LM8323_NUM_PWMS];
};
#define client_to_lm8323(c) container_of(c, struct lm8323_chip, client)
#define dev_to_lm8323(d) container_of(d, struct lm8323_chip, client->dev)
#define cdev_to_pwm(c) container_of(c, struct lm8323_pwm, cdev)
#define work_to_pwm(w) container_of(w, struct lm8323_pwm, work)
#define LM8323_MAX_DATA 8
/*
* To write, we just access the chip's address in write mode, and dump the
* command and data out on the bus. The command byte and data are taken as
* sequential u8s out of varargs, to a maximum of LM8323_MAX_DATA.
*/
static int lm8323_write(struct lm8323_chip *lm, int len, ...)
{
int ret, i;
va_list ap;
u8 data[LM8323_MAX_DATA];
va_start(ap, len);
if (unlikely(len > LM8323_MAX_DATA)) {
dev_err(&lm->client->dev, "tried to send %d bytes\n", len);
va_end(ap);
return 0;
}
for (i = 0; i < len; i++)
data[i] = va_arg(ap, int);
va_end(ap);
/*
* If the host is asleep while we send the data, we can get a NACK
* back while it wakes up, so try again, once.
*/
ret = i2c_master_send(lm->client, data, len);
if (unlikely(ret == -EREMOTEIO))
ret = i2c_master_send(lm->client, data, len);
if (unlikely(ret != len))
dev_err(&lm->client->dev, "sent %d bytes of %d total\n",
len, ret);
return ret;
}
/*
* To read, we first send the command byte to the chip and end the transaction,
* then access the chip in read mode, at which point it will send the data.
*/
static int lm8323_read(struct lm8323_chip *lm, u8 cmd, u8 *buf, int len)
{
int ret;
/*
* If the host is asleep while we send the byte, we can get a NACK
* back while it wakes up, so try again, once.
*/
ret = i2c_master_send(lm->client, &cmd, 1);
if (unlikely(ret == -EREMOTEIO))
ret = i2c_master_send(lm->client, &cmd, 1);
if (unlikely(ret != 1)) {
dev_err(&lm->client->dev, "sending read cmd 0x%02x failed\n",
cmd);
return 0;
}
ret = i2c_master_recv(lm->client, buf, len);
if (unlikely(ret != len))
dev_err(&lm->client->dev, "wanted %d bytes, got %d\n",
len, ret);
return ret;
}
/*
* Set the chip active time (idle time before it enters halt).
*/
static void lm8323_set_active_time(struct lm8323_chip *lm, int time)
{
lm8323_write(lm, 2, LM8323_CMD_SET_ACTIVE, time >> 2);
}
/*
* The signals are AT-style: the low 7 bits are the keycode, and the top
* bit indicates the state (1 for down, 0 for up).
*/
static inline u8 lm8323_whichkey(u8 event)
{
return event & 0x7f;
}
static inline int lm8323_ispress(u8 event)
{
return (event & 0x80) ? 1 : 0;
}
static void process_keys(struct lm8323_chip *lm)
{
u8 event;
u8 key_fifo[LM8323_FIFO_LEN + 1];
int old_keys_down = lm->keys_down;
int ret;
int i = 0;
/*
* Read all key events from the FIFO at once. Next READ_FIFO clears the
* FIFO even if we didn't read all events previously.
*/
ret = lm8323_read(lm, LM8323_CMD_READ_FIFO, key_fifo, LM8323_FIFO_LEN);
if (ret < 0) {
dev_err(&lm->client->dev, "Failed reading fifo \n");
return;
}
key_fifo[ret] = 0;
while ((event = key_fifo[i++])) {
u8 key = lm8323_whichkey(event);
int isdown = lm8323_ispress(event);
unsigned short keycode = lm->keymap[key];
dev_vdbg(&lm->client->dev, "key 0x%02x %s\n",
key, isdown ? "down" : "up");
if (lm->kp_enabled) {
input_event(lm->idev, EV_MSC, MSC_SCAN, key);
input_report_key(lm->idev, keycode, isdown);
input_sync(lm->idev);
}
if (isdown)
lm->keys_down++;
else
lm->keys_down--;
}
/*
* Errata: We need to ensure that the chip never enters halt mode
* during a keypress, so set active time to 0. When it's released,
* we can enter halt again, so set the active time back to normal.
*/
if (!old_keys_down && lm->keys_down)
lm8323_set_active_time(lm, 0);
if (old_keys_down && !lm->keys_down)
lm8323_set_active_time(lm, lm->active_time);
}
static void lm8323_process_error(struct lm8323_chip *lm)
{
u8 error;
if (lm8323_read(lm, LM8323_CMD_READ_ERR, &error, 1) == 1) {
if (error & ERR_FIFOOVER)
dev_vdbg(&lm->client->dev, "fifo overflow!\n");
if (error & ERR_KEYOVR)
dev_vdbg(&lm->client->dev,
"more than two keys pressed\n");
if (error & ERR_CMDUNK)
dev_vdbg(&lm->client->dev,
"unknown command submitted\n");
if (error & ERR_BADPAR)
dev_vdbg(&lm->client->dev, "bad command parameter\n");
}
}
static void lm8323_reset(struct lm8323_chip *lm)
{
/* The docs say we must pass 0xAA as the data byte. */
lm8323_write(lm, 2, LM8323_CMD_RESET, 0xAA);
}
static int lm8323_configure(struct lm8323_chip *lm)
{
int keysize = (lm->size_x << 4) | lm->size_y;
int clock = (CLK_SLOWCLKEN | CLK_RCPWM_EXTERNAL);
int debounce = lm->debounce_time >> 2;
int active = lm->active_time >> 2;
/*
* Active time must be greater than the debounce time: if it's
* a close-run thing, give ourselves a 12ms buffer.
*/
if (debounce >= active)
active = debounce + 3;
lm8323_write(lm, 2, LM8323_CMD_WRITE_CFG, 0);
lm8323_write(lm, 2, LM8323_CMD_WRITE_CLOCK, clock);
lm8323_write(lm, 2, LM8323_CMD_SET_KEY_SIZE, keysize);
lm8323_set_active_time(lm, lm->active_time);
lm8323_write(lm, 2, LM8323_CMD_SET_DEBOUNCE, debounce);
lm8323_write(lm, 3, LM8323_CMD_WRITE_PORT_STATE, 0xff, 0xff);
lm8323_write(lm, 3, LM8323_CMD_WRITE_PORT_SEL, 0, 0);
/*
* Not much we can do about errors at this point, so just hope
* for the best.
*/
return 0;
}
static void pwm_done(struct lm8323_pwm *pwm)
{
mutex_lock(&pwm->lock);
pwm->running = false;
if (pwm->desired_brightness != pwm->brightness)
schedule_work(&pwm->work);
mutex_unlock(&pwm->lock);
}
/*
* Bottom half: handle the interrupt by posting key events, or dealing with
* errors appropriately.
*/
static irqreturn_t lm8323_irq(int irq, void *_lm)
{
struct lm8323_chip *lm = _lm;
u8 ints;
int i;
mutex_lock(&lm->lock);
while ((lm8323_read(lm, LM8323_CMD_READ_INT, &ints, 1) == 1) && ints) {
if (likely(ints & INT_KEYPAD))
process_keys(lm);
if (ints & INT_ROTATOR) {
/* We don't currently support the rotator. */
dev_vdbg(&lm->client->dev, "rotator fired\n");
}
if (ints & INT_ERROR) {
dev_vdbg(&lm->client->dev, "error!\n");
lm8323_process_error(lm);
}
if (ints & INT_NOINIT) {
dev_err(&lm->client->dev, "chip lost config; "
"reinitialising\n");
lm8323_configure(lm);
}
for (i = 0; i < LM8323_NUM_PWMS; i++) {
if (ints & (INT_PWM1 << i)) {
dev_vdbg(&lm->client->dev,
"pwm%d engine completed\n", i);
pwm_done(&lm->pwm[i]);
}
}
}
mutex_unlock(&lm->lock);
return IRQ_HANDLED;
}
/*
* Read the chip ID.
*/
static int lm8323_read_id(struct lm8323_chip *lm, u8 *buf)
{
int bytes;
bytes = lm8323_read(lm, LM8323_CMD_READ_ID, buf, 2);
if (unlikely(bytes != 2))
return -EIO;
return 0;
}
static void lm8323_write_pwm_one(struct lm8323_pwm *pwm, int pos, u16 cmd)
{
lm8323_write(pwm->chip, 4, LM8323_CMD_PWM_WRITE, (pos << 2) | pwm->id,
(cmd & 0xff00) >> 8, cmd & 0x00ff);
}
/*
* Write a script into a given PWM engine, concluding with PWM_END.
* If 'kill' is nonzero, the engine will be shut down at the end
* of the script, producing a zero output. Otherwise the engine
* will be kept running at the final PWM level indefinitely.
*/
static void lm8323_write_pwm(struct lm8323_pwm *pwm, int kill,
int len, const u16 *cmds)
{
int i;
for (i = 0; i < len; i++)
lm8323_write_pwm_one(pwm, i, cmds[i]);
lm8323_write_pwm_one(pwm, i++, PWM_END(kill));
lm8323_write(pwm->chip, 2, LM8323_CMD_START_PWM, pwm->id);
pwm->running = true;
}
static void lm8323_pwm_work(struct work_struct *work)
{
struct lm8323_pwm *pwm = work_to_pwm(work);
int div512, perstep, steps, hz, up, kill;
u16 pwm_cmds[3];
int num_cmds = 0;
mutex_lock(&pwm->lock);
/*
* Do nothing if we're already at the requested level,
* or previous setting is not yet complete. In the latter
* case we will be called again when the previous PWM script
* finishes.
*/
if (pwm->running || pwm->desired_brightness == pwm->brightness)
goto out;
kill = (pwm->desired_brightness == 0);
up = (pwm->desired_brightness > pwm->brightness);
steps = abs(pwm->desired_brightness - pwm->brightness);
/*
* Convert time (in ms) into a divisor (512 or 16 on a refclk of
* 32768Hz), and number of ticks per step.
*/
if ((pwm->fade_time / steps) > (32768 / 512)) {
div512 = 1;
hz = 32768 / 512;
} else {
div512 = 0;
hz = 32768 / 16;
}
perstep = (hz * pwm->fade_time) / (steps * 1000);
if (perstep == 0)
perstep = 1;
else if (perstep > 63)
perstep = 63;
while (steps) {
int s;
s = min(126, steps);
pwm_cmds[num_cmds++] = PWM_RAMP(div512, perstep, s, up);
steps -= s;
}
lm8323_write_pwm(pwm, kill, num_cmds, pwm_cmds);
pwm->brightness = pwm->desired_brightness;
out:
mutex_unlock(&pwm->lock);
}
static void lm8323_pwm_set_brightness(struct led_classdev *led_cdev,
enum led_brightness brightness)
{
struct lm8323_pwm *pwm = cdev_to_pwm(led_cdev);
struct lm8323_chip *lm = pwm->chip;
mutex_lock(&pwm->lock);
pwm->desired_brightness = brightness;
mutex_unlock(&pwm->lock);
if (in_interrupt()) {
schedule_work(&pwm->work);
} else {
/*
* Schedule PWM work as usual unless we are going into suspend
*/
mutex_lock(&lm->lock);
if (likely(!lm->pm_suspend))
schedule_work(&pwm->work);
else
lm8323_pwm_work(&pwm->work);
mutex_unlock(&lm->lock);
}
}
static ssize_t lm8323_pwm_show_time(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm8323_pwm *pwm = cdev_to_pwm(led_cdev);
return sprintf(buf, "%d\n", pwm->fade_time);
}
static ssize_t lm8323_pwm_store_time(struct device *dev,
struct device_attribute *attr, const char *buf, size_t len)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct lm8323_pwm *pwm = cdev_to_pwm(led_cdev);
int ret, time;
ret = kstrtoint(buf, 10, &time);
/* Numbers only, please. */
if (ret)
return ret;
pwm->fade_time = time;
return strlen(buf);
}
static DEVICE_ATTR(time, 0644, lm8323_pwm_show_time, lm8323_pwm_store_time);
static struct attribute *lm8323_pwm_attrs[] = {
&dev_attr_time.attr,
NULL
};
ATTRIBUTE_GROUPS(lm8323_pwm);
static int init_pwm(struct lm8323_chip *lm, int id, struct device *dev,
const char *name)
{
struct lm8323_pwm *pwm;
int err;
BUG_ON(id > 3);
pwm = &lm->pwm[id - 1];
pwm->id = id;
pwm->fade_time = 0;
pwm->brightness = 0;
pwm->desired_brightness = 0;
pwm->running = false;
pwm->enabled = false;
INIT_WORK(&pwm->work, lm8323_pwm_work);
mutex_init(&pwm->lock);
pwm->chip = lm;
if (name) {
pwm->cdev.name = name;
pwm->cdev.brightness_set = lm8323_pwm_set_brightness;
pwm->cdev.groups = lm8323_pwm_groups;
err = devm_led_classdev_register(dev, &pwm->cdev);
if (err) {
dev_err(dev, "couldn't register PWM %d: %d\n", id, err);
return err;
}
pwm->enabled = true;
}
return 0;
}
static ssize_t lm8323_show_disable(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct lm8323_chip *lm = dev_get_drvdata(dev);
return sprintf(buf, "%u\n", !lm->kp_enabled);
}
static ssize_t lm8323_set_disable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct lm8323_chip *lm = dev_get_drvdata(dev);
int ret;
unsigned int i;
ret = kstrtouint(buf, 10, &i);
if (ret)
return ret;
mutex_lock(&lm->lock);
lm->kp_enabled = !i;
mutex_unlock(&lm->lock);
return count;
}
static DEVICE_ATTR(disable_kp, 0644, lm8323_show_disable, lm8323_set_disable);
static struct attribute *lm8323_attrs[] = {
&dev_attr_disable_kp.attr,
NULL,
};
ATTRIBUTE_GROUPS(lm8323);
static int lm8323_probe(struct i2c_client *client)
{
struct lm8323_platform_data *pdata = dev_get_platdata(&client->dev);
struct input_dev *idev;
struct lm8323_chip *lm;
int pwm;
int i, err;
unsigned long tmo;
u8 data[2];
if (!pdata || !pdata->size_x || !pdata->size_y) {
dev_err(&client->dev, "missing platform_data\n");
return -EINVAL;
}
if (pdata->size_x > 8) {
dev_err(&client->dev, "invalid x size %d specified\n",
pdata->size_x);
return -EINVAL;
}
if (pdata->size_y > 12) {
dev_err(&client->dev, "invalid y size %d specified\n",
pdata->size_y);
return -EINVAL;
}
lm = devm_kzalloc(&client->dev, sizeof(*lm), GFP_KERNEL);
if (!lm)
return -ENOMEM;
idev = devm_input_allocate_device(&client->dev);
if (!idev)
return -ENOMEM;
lm->client = client;
lm->idev = idev;
mutex_init(&lm->lock);
lm->size_x = pdata->size_x;
lm->size_y = pdata->size_y;
dev_vdbg(&client->dev, "Keypad size: %d x %d\n",
lm->size_x, lm->size_y);
lm->debounce_time = pdata->debounce_time;
lm->active_time = pdata->active_time;
lm8323_reset(lm);
/*
* Nothing's set up to service the IRQ yet, so just spin for max.
* 100ms until we can configure.
*/
tmo = jiffies + msecs_to_jiffies(100);
while (lm8323_read(lm, LM8323_CMD_READ_INT, data, 1) == 1) {
if (data[0] & INT_NOINIT)
break;
if (time_after(jiffies, tmo)) {
dev_err(&client->dev,
"timeout waiting for initialisation\n");
break;
}
msleep(1);
}
lm8323_configure(lm);
/* If a true probe check the device */
if (lm8323_read_id(lm, data) != 0) {
dev_err(&client->dev, "device not found\n");
return -ENODEV;
}
for (pwm = 0; pwm < LM8323_NUM_PWMS; pwm++) {
err = init_pwm(lm, pwm + 1, &client->dev,
pdata->pwm_names[pwm]);
if (err)
return err;
}
lm->kp_enabled = true;
idev->name = pdata->name ? : "LM8323 keypad";
snprintf(lm->phys, sizeof(lm->phys),
"%s/input-kp", dev_name(&client->dev));
idev->phys = lm->phys;
idev->evbit[0] = BIT(EV_KEY) | BIT(EV_MSC);
__set_bit(MSC_SCAN, idev->mscbit);
for (i = 0; i < LM8323_KEYMAP_SIZE; i++) {
__set_bit(pdata->keymap[i], idev->keybit);
lm->keymap[i] = pdata->keymap[i];
}
__clear_bit(KEY_RESERVED, idev->keybit);
if (pdata->repeat)
__set_bit(EV_REP, idev->evbit);
err = input_register_device(idev);
if (err) {
dev_dbg(&client->dev, "error registering input device\n");
return err;
}
err = devm_request_threaded_irq(&client->dev, client->irq,
NULL, lm8323_irq,
IRQF_TRIGGER_LOW | IRQF_ONESHOT,
"lm8323", lm);
if (err) {
dev_err(&client->dev, "could not get IRQ %d\n", client->irq);
return err;
}
i2c_set_clientdata(client, lm);
device_init_wakeup(&client->dev, 1);
enable_irq_wake(client->irq);
return 0;
}
/*
* We don't need to explicitly suspend the chip, as it already switches off
* when there's no activity.
*/
static int lm8323_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm8323_chip *lm = i2c_get_clientdata(client);
int i;
irq_set_irq_wake(client->irq, 0);
disable_irq(client->irq);
mutex_lock(&lm->lock);
lm->pm_suspend = true;
mutex_unlock(&lm->lock);
for (i = 0; i < 3; i++)
if (lm->pwm[i].enabled)
led_classdev_suspend(&lm->pwm[i].cdev);
return 0;
}
static int lm8323_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct lm8323_chip *lm = i2c_get_clientdata(client);
int i;
mutex_lock(&lm->lock);
lm->pm_suspend = false;
mutex_unlock(&lm->lock);
for (i = 0; i < 3; i++)
if (lm->pwm[i].enabled)
led_classdev_resume(&lm->pwm[i].cdev);
enable_irq(client->irq);
irq_set_irq_wake(client->irq, 1);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(lm8323_pm_ops, lm8323_suspend, lm8323_resume);
static const struct i2c_device_id lm8323_id[] = {
{ "lm8323", 0 },
{ }
};
static struct i2c_driver lm8323_i2c_driver = {
.driver = {
.name = "lm8323",
.pm = pm_sleep_ptr(&lm8323_pm_ops),
.dev_groups = lm8323_groups,
},
.probe = lm8323_probe,
.id_table = lm8323_id,
};
MODULE_DEVICE_TABLE(i2c, lm8323_id);
module_i2c_driver(lm8323_i2c_driver);
MODULE_AUTHOR("Timo O. Karjalainen <[email protected]>");
MODULE_AUTHOR("Daniel Stone");
MODULE_AUTHOR("Felipe Balbi <[email protected]>");
MODULE_DESCRIPTION("LM8323 keypad driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/lm8323.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* drivers/input/keyboard/jornada720_kbd.c
*
* HP Jornada 720 keyboard platform driver
*
* Copyright (C) 2006/2007 Kristoffer Ericson <[email protected]>
*
* Copyright (C) 2006 jornada 720 kbd driver by
Filip Zyzniewsk <[email protected]
* based on (C) 2004 jornada 720 kbd driver by
Alex Lange <[email protected]>
*/
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <mach/jornada720.h>
MODULE_AUTHOR("Kristoffer Ericson <[email protected]>");
MODULE_DESCRIPTION("HP Jornada 710/720/728 keyboard driver");
MODULE_LICENSE("GPL v2");
static unsigned short jornada_std_keymap[128] = { /* ROW */
0, KEY_ESC, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, /* #1 */
KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_VOLUMEUP, KEY_VOLUMEDOWN, KEY_MUTE, /* -> */
0, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, /* #2 */
KEY_0, KEY_MINUS, KEY_EQUAL,0, 0, 0, /* -> */
0, KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T, KEY_Y, KEY_U, KEY_I, KEY_O, /* #3 */
KEY_P, KEY_BACKSLASH, KEY_BACKSPACE, 0, 0, 0, /* -> */
0, KEY_A, KEY_S, KEY_D, KEY_F, KEY_G, KEY_H, KEY_J, KEY_K, KEY_L, /* #4 */
KEY_SEMICOLON, KEY_LEFTBRACE, KEY_RIGHTBRACE, 0, 0, 0, /* -> */
0, KEY_Z, KEY_X, KEY_C, KEY_V, KEY_B, KEY_N, KEY_M, KEY_COMMA, /* #5 */
KEY_DOT, KEY_KPMINUS, KEY_APOSTROPHE, KEY_ENTER, 0, 0,0, /* -> */
0, KEY_TAB, 0, KEY_LEFTSHIFT, 0, KEY_APOSTROPHE, 0, 0, 0, 0, /* #6 */
KEY_UP, 0, KEY_RIGHTSHIFT, 0, 0, 0,0, 0, 0, 0, 0, KEY_LEFTALT, KEY_GRAVE, /* -> */
0, 0, KEY_LEFT, KEY_DOWN, KEY_RIGHT, 0, 0, 0, 0,0, KEY_KPASTERISK, /* -> */
KEY_LEFTCTRL, 0, KEY_SPACE, 0, 0, 0, KEY_SLASH, KEY_DELETE, 0, 0, /* -> */
0, 0, 0, KEY_POWER, /* -> */
};
struct jornadakbd {
unsigned short keymap[ARRAY_SIZE(jornada_std_keymap)];
struct input_dev *input;
};
static irqreturn_t jornada720_kbd_interrupt(int irq, void *dev_id)
{
struct platform_device *pdev = dev_id;
struct jornadakbd *jornadakbd = platform_get_drvdata(pdev);
struct input_dev *input = jornadakbd->input;
u8 count, kbd_data, scan_code;
/* startup ssp with spinlock */
jornada_ssp_start();
if (jornada_ssp_inout(GETSCANKEYCODE) != TXDUMMY) {
dev_dbg(&pdev->dev,
"GetKeycode command failed with ETIMEDOUT, flushed bus\n");
} else {
/* How many keycodes are waiting for us? */
count = jornada_ssp_byte(TXDUMMY);
/* Lets drag them out one at a time */
while (count--) {
/* Exchange TxDummy for location (keymap[kbddata]) */
kbd_data = jornada_ssp_byte(TXDUMMY);
scan_code = kbd_data & 0x7f;
input_event(input, EV_MSC, MSC_SCAN, scan_code);
input_report_key(input, jornadakbd->keymap[scan_code],
!(kbd_data & 0x80));
input_sync(input);
}
}
/* release spinlock and turn off ssp */
jornada_ssp_end();
return IRQ_HANDLED;
};
static int jornada720_kbd_probe(struct platform_device *pdev)
{
struct jornadakbd *jornadakbd;
struct input_dev *input_dev;
int i, err, irq;
irq = platform_get_irq(pdev, 0);
if (irq <= 0)
return irq < 0 ? irq : -EINVAL;
jornadakbd = devm_kzalloc(&pdev->dev, sizeof(*jornadakbd), GFP_KERNEL);
input_dev = devm_input_allocate_device(&pdev->dev);
if (!jornadakbd || !input_dev)
return -ENOMEM;
platform_set_drvdata(pdev, jornadakbd);
memcpy(jornadakbd->keymap, jornada_std_keymap,
sizeof(jornada_std_keymap));
jornadakbd->input = input_dev;
input_dev->evbit[0] = BIT(EV_KEY) | BIT(EV_REP);
input_dev->name = "HP Jornada 720 keyboard";
input_dev->phys = "jornadakbd/input0";
input_dev->keycode = jornadakbd->keymap;
input_dev->keycodesize = sizeof(unsigned short);
input_dev->keycodemax = ARRAY_SIZE(jornada_std_keymap);
input_dev->id.bustype = BUS_HOST;
input_dev->dev.parent = &pdev->dev;
for (i = 0; i < ARRAY_SIZE(jornadakbd->keymap); i++)
__set_bit(jornadakbd->keymap[i], input_dev->keybit);
__clear_bit(KEY_RESERVED, input_dev->keybit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
err = devm_request_irq(&pdev->dev, irq, jornada720_kbd_interrupt,
IRQF_TRIGGER_FALLING, "jornadakbd", pdev);
if (err) {
dev_err(&pdev->dev, "unable to grab IRQ%d: %d\n", irq, err);
return err;
}
return input_register_device(jornadakbd->input);
};
/* work with hotplug and coldplug */
MODULE_ALIAS("platform:jornada720_kbd");
static struct platform_driver jornada720_kbd_driver = {
.driver = {
.name = "jornada720_kbd",
},
.probe = jornada720_kbd_probe,
};
module_platform_driver(jornada720_kbd_driver);
|
linux-master
|
drivers/input/keyboard/jornada720_kbd.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) ST-Ericsson SA 2010
*
* Author: Rabin Vincent <[email protected]> for ST-Ericsson
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/input/matrix_keypad.h>
#include <linux/mfd/stmpe.h>
/* These are at the same addresses in all STMPE variants */
#define STMPE_KPC_COL 0x60
#define STMPE_KPC_ROW_MSB 0x61
#define STMPE_KPC_ROW_LSB 0x62
#define STMPE_KPC_CTRL_MSB 0x63
#define STMPE_KPC_CTRL_LSB 0x64
#define STMPE_KPC_COMBI_KEY_0 0x65
#define STMPE_KPC_COMBI_KEY_1 0x66
#define STMPE_KPC_COMBI_KEY_2 0x67
#define STMPE_KPC_DATA_BYTE0 0x68
#define STMPE_KPC_DATA_BYTE1 0x69
#define STMPE_KPC_DATA_BYTE2 0x6a
#define STMPE_KPC_DATA_BYTE3 0x6b
#define STMPE_KPC_DATA_BYTE4 0x6c
#define STMPE_KPC_CTRL_LSB_SCAN (0x1 << 0)
#define STMPE_KPC_CTRL_LSB_DEBOUNCE (0x7f << 1)
#define STMPE_KPC_CTRL_MSB_SCAN_COUNT (0xf << 4)
#define STMPE_KPC_ROW_MSB_ROWS 0xff
#define STMPE_KPC_DATA_UP (0x1 << 7)
#define STMPE_KPC_DATA_ROW (0xf << 3)
#define STMPE_KPC_DATA_COL (0x7 << 0)
#define STMPE_KPC_DATA_NOKEY_MASK 0x78
#define STMPE_KEYPAD_MAX_DEBOUNCE 127
#define STMPE_KEYPAD_MAX_SCAN_COUNT 15
#define STMPE_KEYPAD_MAX_ROWS 8
#define STMPE_KEYPAD_MAX_COLS 8
#define STMPE_KEYPAD_ROW_SHIFT 3
#define STMPE_KEYPAD_KEYMAP_MAX_SIZE \
(STMPE_KEYPAD_MAX_ROWS * STMPE_KEYPAD_MAX_COLS)
#define STMPE1601_NUM_DATA 5
#define STMPE2401_NUM_DATA 3
#define STMPE2403_NUM_DATA 5
/* Make sure it covers all cases above */
#define MAX_NUM_DATA 5
/**
* struct stmpe_keypad_variant - model-specific attributes
* @auto_increment: whether the KPC_DATA_BYTE register address
* auto-increments on multiple read
* @set_pullup: whether the pins need to have their pull-ups set
* @num_data: number of data bytes
* @num_normal_data: number of normal keys' data bytes
* @max_cols: maximum number of columns supported
* @max_rows: maximum number of rows supported
* @col_gpios: bitmask of gpios which can be used for columns
* @row_gpios: bitmask of gpios which can be used for rows
*/
struct stmpe_keypad_variant {
bool auto_increment;
bool set_pullup;
int num_data;
int num_normal_data;
int max_cols;
int max_rows;
unsigned int col_gpios;
unsigned int row_gpios;
};
static const struct stmpe_keypad_variant stmpe_keypad_variants[] = {
[STMPE1601] = {
.auto_increment = true,
.num_data = STMPE1601_NUM_DATA,
.num_normal_data = 3,
.max_cols = 8,
.max_rows = 8,
.col_gpios = 0x000ff, /* GPIO 0 - 7 */
.row_gpios = 0x0ff00, /* GPIO 8 - 15 */
},
[STMPE2401] = {
.auto_increment = false,
.set_pullup = true,
.num_data = STMPE2401_NUM_DATA,
.num_normal_data = 2,
.max_cols = 8,
.max_rows = 12,
.col_gpios = 0x0000ff, /* GPIO 0 - 7*/
.row_gpios = 0x1f7f00, /* GPIO 8-14, 16-20 */
},
[STMPE2403] = {
.auto_increment = true,
.set_pullup = true,
.num_data = STMPE2403_NUM_DATA,
.num_normal_data = 3,
.max_cols = 8,
.max_rows = 12,
.col_gpios = 0x0000ff, /* GPIO 0 - 7*/
.row_gpios = 0x1fef00, /* GPIO 8-14, 16-20 */
},
};
/**
* struct stmpe_keypad - STMPE keypad state container
* @stmpe: pointer to parent STMPE device
* @input: spawned input device
* @variant: STMPE variant
* @debounce_ms: debounce interval, in ms. Maximum is
* %STMPE_KEYPAD_MAX_DEBOUNCE.
* @scan_count: number of key scanning cycles to confirm key data.
* Maximum is %STMPE_KEYPAD_MAX_SCAN_COUNT.
* @no_autorepeat: disable key autorepeat
* @rows: bitmask for the rows
* @cols: bitmask for the columns
* @keymap: the keymap
*/
struct stmpe_keypad {
struct stmpe *stmpe;
struct input_dev *input;
const struct stmpe_keypad_variant *variant;
unsigned int debounce_ms;
unsigned int scan_count;
bool no_autorepeat;
unsigned int rows;
unsigned int cols;
unsigned short keymap[STMPE_KEYPAD_KEYMAP_MAX_SIZE];
};
static int stmpe_keypad_read_data(struct stmpe_keypad *keypad, u8 *data)
{
const struct stmpe_keypad_variant *variant = keypad->variant;
struct stmpe *stmpe = keypad->stmpe;
int ret;
int i;
if (variant->auto_increment)
return stmpe_block_read(stmpe, STMPE_KPC_DATA_BYTE0,
variant->num_data, data);
for (i = 0; i < variant->num_data; i++) {
ret = stmpe_reg_read(stmpe, STMPE_KPC_DATA_BYTE0 + i);
if (ret < 0)
return ret;
data[i] = ret;
}
return 0;
}
static irqreturn_t stmpe_keypad_irq(int irq, void *dev)
{
struct stmpe_keypad *keypad = dev;
struct input_dev *input = keypad->input;
const struct stmpe_keypad_variant *variant = keypad->variant;
u8 fifo[MAX_NUM_DATA];
int ret;
int i;
ret = stmpe_keypad_read_data(keypad, fifo);
if (ret < 0)
return IRQ_NONE;
for (i = 0; i < variant->num_normal_data; i++) {
u8 data = fifo[i];
int row = (data & STMPE_KPC_DATA_ROW) >> 3;
int col = data & STMPE_KPC_DATA_COL;
int code = MATRIX_SCAN_CODE(row, col, STMPE_KEYPAD_ROW_SHIFT);
bool up = data & STMPE_KPC_DATA_UP;
if ((data & STMPE_KPC_DATA_NOKEY_MASK)
== STMPE_KPC_DATA_NOKEY_MASK)
continue;
input_event(input, EV_MSC, MSC_SCAN, code);
input_report_key(input, keypad->keymap[code], !up);
input_sync(input);
}
return IRQ_HANDLED;
}
static int stmpe_keypad_altfunc_init(struct stmpe_keypad *keypad)
{
const struct stmpe_keypad_variant *variant = keypad->variant;
unsigned int col_gpios = variant->col_gpios;
unsigned int row_gpios = variant->row_gpios;
struct stmpe *stmpe = keypad->stmpe;
u8 pureg = stmpe->regs[STMPE_IDX_GPPUR_LSB];
unsigned int pins = 0;
unsigned int pu_pins = 0;
int ret;
int i;
/*
* Figure out which pins need to be set to the keypad alternate
* function.
*
* {cols,rows}_gpios are bitmasks of which pins on the chip can be used
* for the keypad.
*
* keypad->{cols,rows} are a bitmask of which pins (of the ones useable
* for the keypad) are used on the board.
*/
for (i = 0; i < variant->max_cols; i++) {
int num = __ffs(col_gpios);
if (keypad->cols & (1 << i)) {
pins |= 1 << num;
pu_pins |= 1 << num;
}
col_gpios &= ~(1 << num);
}
for (i = 0; i < variant->max_rows; i++) {
int num = __ffs(row_gpios);
if (keypad->rows & (1 << i))
pins |= 1 << num;
row_gpios &= ~(1 << num);
}
ret = stmpe_set_altfunc(stmpe, pins, STMPE_BLOCK_KEYPAD);
if (ret)
return ret;
/*
* On STMPE24xx, set pin bias to pull-up on all keypad input
* pins (columns), this incidentally happen to be maximum 8 pins
* and placed at GPIO0-7 so only the LSB of the pull up register
* ever needs to be written.
*/
if (variant->set_pullup) {
u8 val;
ret = stmpe_reg_read(stmpe, pureg);
if (ret)
return ret;
/* Do not touch unused pins, may be used for GPIO */
val = ret & ~pu_pins;
val |= pu_pins;
ret = stmpe_reg_write(stmpe, pureg, val);
}
return 0;
}
static int stmpe_keypad_chip_init(struct stmpe_keypad *keypad)
{
const struct stmpe_keypad_variant *variant = keypad->variant;
struct stmpe *stmpe = keypad->stmpe;
int ret;
if (keypad->debounce_ms > STMPE_KEYPAD_MAX_DEBOUNCE)
return -EINVAL;
if (keypad->scan_count > STMPE_KEYPAD_MAX_SCAN_COUNT)
return -EINVAL;
ret = stmpe_enable(stmpe, STMPE_BLOCK_KEYPAD);
if (ret < 0)
return ret;
ret = stmpe_keypad_altfunc_init(keypad);
if (ret < 0)
return ret;
ret = stmpe_reg_write(stmpe, STMPE_KPC_COL, keypad->cols);
if (ret < 0)
return ret;
ret = stmpe_reg_write(stmpe, STMPE_KPC_ROW_LSB, keypad->rows);
if (ret < 0)
return ret;
if (variant->max_rows > 8) {
ret = stmpe_set_bits(stmpe, STMPE_KPC_ROW_MSB,
STMPE_KPC_ROW_MSB_ROWS,
keypad->rows >> 8);
if (ret < 0)
return ret;
}
ret = stmpe_set_bits(stmpe, STMPE_KPC_CTRL_MSB,
STMPE_KPC_CTRL_MSB_SCAN_COUNT,
keypad->scan_count << 4);
if (ret < 0)
return ret;
return stmpe_set_bits(stmpe, STMPE_KPC_CTRL_LSB,
STMPE_KPC_CTRL_LSB_SCAN |
STMPE_KPC_CTRL_LSB_DEBOUNCE,
STMPE_KPC_CTRL_LSB_SCAN |
(keypad->debounce_ms << 1));
}
static void stmpe_keypad_fill_used_pins(struct stmpe_keypad *keypad,
u32 used_rows, u32 used_cols)
{
int row, col;
for (row = 0; row < used_rows; row++) {
for (col = 0; col < used_cols; col++) {
int code = MATRIX_SCAN_CODE(row, col,
STMPE_KEYPAD_ROW_SHIFT);
if (keypad->keymap[code] != KEY_RESERVED) {
keypad->rows |= 1 << row;
keypad->cols |= 1 << col;
}
}
}
}
static int stmpe_keypad_probe(struct platform_device *pdev)
{
struct stmpe *stmpe = dev_get_drvdata(pdev->dev.parent);
struct device_node *np = pdev->dev.of_node;
struct stmpe_keypad *keypad;
struct input_dev *input;
u32 rows;
u32 cols;
int error;
int irq;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
keypad = devm_kzalloc(&pdev->dev, sizeof(struct stmpe_keypad),
GFP_KERNEL);
if (!keypad)
return -ENOMEM;
keypad->stmpe = stmpe;
keypad->variant = &stmpe_keypad_variants[stmpe->partnum];
of_property_read_u32(np, "debounce-interval", &keypad->debounce_ms);
of_property_read_u32(np, "st,scan-count", &keypad->scan_count);
keypad->no_autorepeat = of_property_read_bool(np, "st,no-autorepeat");
input = devm_input_allocate_device(&pdev->dev);
if (!input)
return -ENOMEM;
input->name = "STMPE keypad";
input->id.bustype = BUS_I2C;
input->dev.parent = &pdev->dev;
error = matrix_keypad_parse_properties(&pdev->dev, &rows, &cols);
if (error)
return error;
error = matrix_keypad_build_keymap(NULL, NULL, rows, cols,
keypad->keymap, input);
if (error)
return error;
input_set_capability(input, EV_MSC, MSC_SCAN);
if (!keypad->no_autorepeat)
__set_bit(EV_REP, input->evbit);
stmpe_keypad_fill_used_pins(keypad, rows, cols);
keypad->input = input;
error = stmpe_keypad_chip_init(keypad);
if (error < 0)
return error;
error = devm_request_threaded_irq(&pdev->dev, irq,
NULL, stmpe_keypad_irq,
IRQF_ONESHOT, "stmpe-keypad", keypad);
if (error) {
dev_err(&pdev->dev, "unable to get irq: %d\n", error);
return error;
}
error = input_register_device(input);
if (error) {
dev_err(&pdev->dev,
"unable to register input device: %d\n", error);
return error;
}
platform_set_drvdata(pdev, keypad);
return 0;
}
static int stmpe_keypad_remove(struct platform_device *pdev)
{
struct stmpe_keypad *keypad = platform_get_drvdata(pdev);
stmpe_disable(keypad->stmpe, STMPE_BLOCK_KEYPAD);
return 0;
}
static struct platform_driver stmpe_keypad_driver = {
.driver.name = "stmpe-keypad",
.driver.owner = THIS_MODULE,
.probe = stmpe_keypad_probe,
.remove = stmpe_keypad_remove,
};
module_platform_driver(stmpe_keypad_driver);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("STMPExxxx keypad driver");
MODULE_AUTHOR("Rabin Vincent <[email protected]>");
|
linux-master
|
drivers/input/keyboard/stmpe-keypad.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Cirrus Logic CLPS711X Keypad driver
*
* Copyright (C) 2014 Alexander Shiyan <[email protected]>
*/
#include <linux/input.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/gpio/consumer.h>
#include <linux/platform_device.h>
#include <linux/property.h>
#include <linux/regmap.h>
#include <linux/sched.h>
#include <linux/input/matrix_keypad.h>
#include <linux/mfd/syscon.h>
#include <linux/mfd/syscon/clps711x.h>
#define CLPS711X_KEYPAD_COL_COUNT 8
struct clps711x_gpio_data {
struct gpio_desc *desc;
DECLARE_BITMAP(last_state, CLPS711X_KEYPAD_COL_COUNT);
};
struct clps711x_keypad_data {
struct regmap *syscon;
int row_count;
unsigned int row_shift;
struct clps711x_gpio_data *gpio_data;
};
static void clps711x_keypad_poll(struct input_dev *input)
{
const unsigned short *keycodes = input->keycode;
struct clps711x_keypad_data *priv = input_get_drvdata(input);
bool sync = false;
int col, row;
for (col = 0; col < CLPS711X_KEYPAD_COL_COUNT; col++) {
/* Assert column */
regmap_update_bits(priv->syscon, SYSCON_OFFSET,
SYSCON1_KBDSCAN_MASK,
SYSCON1_KBDSCAN(8 + col));
/* Scan rows */
for (row = 0; row < priv->row_count; row++) {
struct clps711x_gpio_data *data = &priv->gpio_data[row];
bool state, state1;
/* Read twice for protection against fluctuations */
do {
state = gpiod_get_value_cansleep(data->desc);
cond_resched();
state1 = gpiod_get_value_cansleep(data->desc);
} while (state != state1);
if (test_bit(col, data->last_state) != state) {
int code = MATRIX_SCAN_CODE(row, col,
priv->row_shift);
if (state) {
set_bit(col, data->last_state);
input_event(input,
EV_MSC, MSC_SCAN, code);
} else {
clear_bit(col, data->last_state);
}
if (keycodes[code])
input_report_key(input,
keycodes[code], state);
sync = true;
}
}
/* Set all columns to low */
regmap_update_bits(priv->syscon, SYSCON_OFFSET,
SYSCON1_KBDSCAN_MASK, SYSCON1_KBDSCAN(1));
}
if (sync)
input_sync(input);
}
static int clps711x_keypad_probe(struct platform_device *pdev)
{
struct clps711x_keypad_data *priv;
struct device *dev = &pdev->dev;
struct input_dev *input;
u32 poll_interval;
int i, err;
priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->syscon = syscon_regmap_lookup_by_phandle(dev->of_node, "syscon");
if (IS_ERR(priv->syscon))
return PTR_ERR(priv->syscon);
priv->row_count = gpiod_count(dev, "row");
if (priv->row_count < 1)
return -EINVAL;
priv->gpio_data = devm_kcalloc(dev,
priv->row_count, sizeof(*priv->gpio_data),
GFP_KERNEL);
if (!priv->gpio_data)
return -ENOMEM;
priv->row_shift = get_count_order(CLPS711X_KEYPAD_COL_COUNT);
for (i = 0; i < priv->row_count; i++) {
struct clps711x_gpio_data *data = &priv->gpio_data[i];
data->desc = devm_gpiod_get_index(dev, "row", i, GPIOD_IN);
if (IS_ERR(data->desc))
return PTR_ERR(data->desc);
}
err = device_property_read_u32(dev, "poll-interval", &poll_interval);
if (err)
return err;
input = devm_input_allocate_device(dev);
if (!input)
return -ENOMEM;
input_set_drvdata(input, priv);
input->name = pdev->name;
input->dev.parent = dev;
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0100;
err = matrix_keypad_build_keymap(NULL, NULL, priv->row_count,
CLPS711X_KEYPAD_COL_COUNT,
NULL, input);
if (err)
return err;
input_set_capability(input, EV_MSC, MSC_SCAN);
if (device_property_read_bool(dev, "autorepeat"))
__set_bit(EV_REP, input->evbit);
/* Set all columns to low */
regmap_update_bits(priv->syscon, SYSCON_OFFSET, SYSCON1_KBDSCAN_MASK,
SYSCON1_KBDSCAN(1));
err = input_setup_polling(input, clps711x_keypad_poll);
if (err)
return err;
input_set_poll_interval(input, poll_interval);
err = input_register_device(input);
if (err)
return err;
return 0;
}
static const struct of_device_id clps711x_keypad_of_match[] = {
{ .compatible = "cirrus,ep7209-keypad", },
{ }
};
MODULE_DEVICE_TABLE(of, clps711x_keypad_of_match);
static struct platform_driver clps711x_keypad_driver = {
.driver = {
.name = "clps711x-keypad",
.of_match_table = clps711x_keypad_of_match,
},
.probe = clps711x_keypad_probe,
};
module_platform_driver(clps711x_keypad_driver);
MODULE_AUTHOR("Alexander Shiyan <[email protected]>");
MODULE_DESCRIPTION("Cirrus Logic CLPS711X Keypad driver");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/clps711x-keypad.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* AT and PS/2 keyboard driver
*
* Copyright (c) 1999-2002 Vojtech Pavlik
*/
/*
* This driver can handle standard AT keyboards and PS/2 keyboards in
* Translated and Raw Set 2 and Set 3, as well as AT keyboards on dumb
* input-only controllers and AT keyboards connected over a one way RS232
* converter.
*/
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/input.h>
#include <linux/input/vivaldi-fmap.h>
#include <linux/serio.h>
#include <linux/workqueue.h>
#include <linux/libps2.h>
#include <linux/mutex.h>
#include <linux/dmi.h>
#include <linux/property.h>
#define DRIVER_DESC "AT and PS/2 keyboard driver"
MODULE_AUTHOR("Vojtech Pavlik <[email protected]>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static int atkbd_set = 2;
module_param_named(set, atkbd_set, int, 0);
MODULE_PARM_DESC(set, "Select keyboard code set (2 = default, 3 = PS/2 native)");
#if defined(__i386__) || defined(__x86_64__) || defined(__hppa__)
static bool atkbd_reset;
#else
static bool atkbd_reset = true;
#endif
module_param_named(reset, atkbd_reset, bool, 0);
MODULE_PARM_DESC(reset, "Reset keyboard during initialization");
static bool atkbd_softrepeat;
module_param_named(softrepeat, atkbd_softrepeat, bool, 0);
MODULE_PARM_DESC(softrepeat, "Use software keyboard repeat");
static bool atkbd_softraw = true;
module_param_named(softraw, atkbd_softraw, bool, 0);
MODULE_PARM_DESC(softraw, "Use software generated rawmode");
static bool atkbd_scroll;
module_param_named(scroll, atkbd_scroll, bool, 0);
MODULE_PARM_DESC(scroll, "Enable scroll-wheel on MS Office and similar keyboards");
static bool atkbd_extra;
module_param_named(extra, atkbd_extra, bool, 0);
MODULE_PARM_DESC(extra, "Enable extra LEDs and keys on IBM RapidAcces, EzKey and similar keyboards");
static bool atkbd_terminal;
module_param_named(terminal, atkbd_terminal, bool, 0);
MODULE_PARM_DESC(terminal, "Enable break codes on an IBM Terminal keyboard connected via AT/PS2");
#define SCANCODE(keymap) ((keymap >> 16) & 0xFFFF)
#define KEYCODE(keymap) (keymap & 0xFFFF)
/*
* Scancode to keycode tables. These are just the default setting, and
* are loadable via a userland utility.
*/
#define ATKBD_KEYMAP_SIZE 512
static const unsigned short atkbd_set2_keycode[ATKBD_KEYMAP_SIZE] = {
#ifdef CONFIG_KEYBOARD_ATKBD_HP_KEYCODES
/* XXX: need a more general approach */
#include "hpps2atkbd.h" /* include the keyboard scancodes */
#else
0, 67, 65, 63, 61, 59, 60, 88, 0, 68, 66, 64, 62, 15, 41,117,
0, 56, 42, 93, 29, 16, 2, 0, 0, 0, 44, 31, 30, 17, 3, 0,
0, 46, 45, 32, 18, 5, 4, 95, 0, 57, 47, 33, 20, 19, 6,183,
0, 49, 48, 35, 34, 21, 7,184, 0, 0, 50, 36, 22, 8, 9,185,
0, 51, 37, 23, 24, 11, 10, 0, 0, 52, 53, 38, 39, 25, 12, 0,
0, 89, 40, 0, 26, 13, 0, 0, 58, 54, 28, 27, 0, 43, 0, 85,
0, 86, 91, 90, 92, 0, 14, 94, 0, 79,124, 75, 71,121, 0, 0,
82, 83, 80, 76, 77, 72, 1, 69, 87, 78, 81, 74, 55, 73, 70, 99,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
217,100,255, 0, 97,165, 0, 0,156, 0, 0, 0, 0, 0, 0,125,
173,114, 0,113, 0, 0, 0,126,128, 0, 0,140, 0, 0, 0,127,
159, 0,115, 0,164, 0, 0,116,158, 0,172,166, 0, 0, 0,142,
157, 0, 0, 0, 0, 0, 0, 0,155, 0, 98, 0, 0,163, 0, 0,
226, 0, 0, 0, 0, 0, 0, 0, 0,255, 96, 0, 0, 0,143, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,107, 0,105,102, 0, 0,112,
110,111,108,112,106,103, 0,119, 0,118,109, 0, 99,104,119, 0,
0, 0, 0, 65, 99,
#endif
};
static const unsigned short atkbd_set3_keycode[ATKBD_KEYMAP_SIZE] = {
0, 0, 0, 0, 0, 0, 0, 59, 1,138,128,129,130, 15, 41, 60,
131, 29, 42, 86, 58, 16, 2, 61,133, 56, 44, 31, 30, 17, 3, 62,
134, 46, 45, 32, 18, 5, 4, 63,135, 57, 47, 33, 20, 19, 6, 64,
136, 49, 48, 35, 34, 21, 7, 65,137,100, 50, 36, 22, 8, 9, 66,
125, 51, 37, 23, 24, 11, 10, 67,126, 52, 53, 38, 39, 25, 12, 68,
113,114, 40, 43, 26, 13, 87, 99, 97, 54, 28, 27, 43, 43, 88, 70,
108,105,119,103,111,107, 14,110, 0, 79,106, 75, 71,109,102,104,
82, 83, 80, 76, 77, 72, 69, 98, 0, 96, 81, 0, 78, 73, 55,183,
184,185,186,187, 74, 94, 92, 93, 0, 0, 0,125,126,127,112, 0,
0,139,172,163,165,115,152,172,166,140,160,154,113,114,167,168,
148,149,147,140
};
static const unsigned short atkbd_unxlate_table[128] = {
0,118, 22, 30, 38, 37, 46, 54, 61, 62, 70, 69, 78, 85,102, 13,
21, 29, 36, 45, 44, 53, 60, 67, 68, 77, 84, 91, 90, 20, 28, 27,
35, 43, 52, 51, 59, 66, 75, 76, 82, 14, 18, 93, 26, 34, 33, 42,
50, 49, 58, 65, 73, 74, 89,124, 17, 41, 88, 5, 6, 4, 12, 3,
11, 2, 10, 1, 9,119,126,108,117,125,123,107,115,116,121,105,
114,122,112,113,127, 96, 97,120, 7, 15, 23, 31, 39, 47, 55, 63,
71, 79, 86, 94, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 87,111,
19, 25, 57, 81, 83, 92, 95, 98, 99,100,101,103,104,106,109,110
};
#define ATKBD_CMD_SETLEDS 0x10ed
#define ATKBD_CMD_GSCANSET 0x11f0
#define ATKBD_CMD_SSCANSET 0x10f0
#define ATKBD_CMD_GETID 0x02f2
#define ATKBD_CMD_SETREP 0x10f3
#define ATKBD_CMD_ENABLE 0x00f4
#define ATKBD_CMD_RESET_DIS 0x00f5 /* Reset to defaults and disable */
#define ATKBD_CMD_RESET_DEF 0x00f6 /* Reset to defaults */
#define ATKBD_CMD_SETALL_MB 0x00f8 /* Set all keys to give break codes */
#define ATKBD_CMD_SETALL_MBR 0x00fa /* ... and repeat */
#define ATKBD_CMD_RESET_BAT 0x02ff
#define ATKBD_CMD_RESEND 0x00fe
#define ATKBD_CMD_EX_ENABLE 0x10ea
#define ATKBD_CMD_EX_SETLEDS 0x20eb
#define ATKBD_CMD_OK_GETID 0x02e8
#define ATKBD_RET_ACK 0xfa
#define ATKBD_RET_NAK 0xfe
#define ATKBD_RET_BAT 0xaa
#define ATKBD_RET_EMUL0 0xe0
#define ATKBD_RET_EMUL1 0xe1
#define ATKBD_RET_RELEASE 0xf0
#define ATKBD_RET_HANJA 0xf1
#define ATKBD_RET_HANGEUL 0xf2
#define ATKBD_RET_ERR 0xff
#define ATKBD_KEY_UNKNOWN 0
#define ATKBD_KEY_NULL 255
#define ATKBD_SCR_1 0xfffe
#define ATKBD_SCR_2 0xfffd
#define ATKBD_SCR_4 0xfffc
#define ATKBD_SCR_8 0xfffb
#define ATKBD_SCR_CLICK 0xfffa
#define ATKBD_SCR_LEFT 0xfff9
#define ATKBD_SCR_RIGHT 0xfff8
#define ATKBD_SPECIAL ATKBD_SCR_RIGHT
#define ATKBD_LED_EVENT_BIT 0
#define ATKBD_REP_EVENT_BIT 1
#define ATKBD_XL_ERR 0x01
#define ATKBD_XL_BAT 0x02
#define ATKBD_XL_ACK 0x04
#define ATKBD_XL_NAK 0x08
#define ATKBD_XL_HANGEUL 0x10
#define ATKBD_XL_HANJA 0x20
static const struct {
unsigned short keycode;
unsigned char set2;
} atkbd_scroll_keys[] = {
{ ATKBD_SCR_1, 0xc5 },
{ ATKBD_SCR_2, 0x9d },
{ ATKBD_SCR_4, 0xa4 },
{ ATKBD_SCR_8, 0x9b },
{ ATKBD_SCR_CLICK, 0xe0 },
{ ATKBD_SCR_LEFT, 0xcb },
{ ATKBD_SCR_RIGHT, 0xd2 },
};
/*
* The atkbd control structure
*/
struct atkbd {
struct ps2dev ps2dev;
struct input_dev *dev;
/* Written only during init */
char name[64];
char phys[32];
unsigned short id;
unsigned short keycode[ATKBD_KEYMAP_SIZE];
DECLARE_BITMAP(force_release_mask, ATKBD_KEYMAP_SIZE);
unsigned char set;
bool translated;
bool extra;
bool write;
bool softrepeat;
bool softraw;
bool scroll;
bool enabled;
/* Accessed only from interrupt */
unsigned char emul;
bool resend;
bool release;
unsigned long xl_bit;
unsigned int last;
unsigned long time;
unsigned long err_count;
struct delayed_work event_work;
unsigned long event_jiffies;
unsigned long event_mask;
/* Serializes reconnect(), attr->set() and event work */
struct mutex mutex;
struct vivaldi_data vdata;
};
/*
* System-specific keymap fixup routine
*/
static void (*atkbd_platform_fixup)(struct atkbd *, const void *data);
static void *atkbd_platform_fixup_data;
static unsigned int (*atkbd_platform_scancode_fixup)(struct atkbd *, unsigned int);
/*
* Certain keyboards to not like ATKBD_CMD_RESET_DIS and stop responding
* to many commands until full reset (ATKBD_CMD_RESET_BAT) is performed.
*/
static bool atkbd_skip_deactivate;
static ssize_t atkbd_attr_show_helper(struct device *dev, char *buf,
ssize_t (*handler)(struct atkbd *, char *));
static ssize_t atkbd_attr_set_helper(struct device *dev, const char *buf, size_t count,
ssize_t (*handler)(struct atkbd *, const char *, size_t));
#define ATKBD_DEFINE_ATTR(_name) \
static ssize_t atkbd_show_##_name(struct atkbd *, char *); \
static ssize_t atkbd_set_##_name(struct atkbd *, const char *, size_t); \
static ssize_t atkbd_do_show_##_name(struct device *d, \
struct device_attribute *attr, char *b) \
{ \
return atkbd_attr_show_helper(d, b, atkbd_show_##_name); \
} \
static ssize_t atkbd_do_set_##_name(struct device *d, \
struct device_attribute *attr, const char *b, size_t s) \
{ \
return atkbd_attr_set_helper(d, b, s, atkbd_set_##_name); \
} \
static struct device_attribute atkbd_attr_##_name = \
__ATTR(_name, S_IWUSR | S_IRUGO, atkbd_do_show_##_name, atkbd_do_set_##_name);
ATKBD_DEFINE_ATTR(extra);
ATKBD_DEFINE_ATTR(force_release);
ATKBD_DEFINE_ATTR(scroll);
ATKBD_DEFINE_ATTR(set);
ATKBD_DEFINE_ATTR(softrepeat);
ATKBD_DEFINE_ATTR(softraw);
#define ATKBD_DEFINE_RO_ATTR(_name) \
static ssize_t atkbd_show_##_name(struct atkbd *, char *); \
static ssize_t atkbd_do_show_##_name(struct device *d, \
struct device_attribute *attr, char *b) \
{ \
return atkbd_attr_show_helper(d, b, atkbd_show_##_name); \
} \
static struct device_attribute atkbd_attr_##_name = \
__ATTR(_name, S_IRUGO, atkbd_do_show_##_name, NULL);
ATKBD_DEFINE_RO_ATTR(err_count);
ATKBD_DEFINE_RO_ATTR(function_row_physmap);
static struct attribute *atkbd_attributes[] = {
&atkbd_attr_extra.attr,
&atkbd_attr_force_release.attr,
&atkbd_attr_scroll.attr,
&atkbd_attr_set.attr,
&atkbd_attr_softrepeat.attr,
&atkbd_attr_softraw.attr,
&atkbd_attr_err_count.attr,
&atkbd_attr_function_row_physmap.attr,
NULL
};
static ssize_t atkbd_show_function_row_physmap(struct atkbd *atkbd, char *buf)
{
return vivaldi_function_row_physmap_show(&atkbd->vdata, buf);
}
static struct atkbd *atkbd_from_serio(struct serio *serio)
{
struct ps2dev *ps2dev = serio_get_drvdata(serio);
return container_of(ps2dev, struct atkbd, ps2dev);
}
static umode_t atkbd_attr_is_visible(struct kobject *kobj,
struct attribute *attr, int i)
{
struct device *dev = kobj_to_dev(kobj);
struct serio *serio = to_serio_port(dev);
struct atkbd *atkbd = atkbd_from_serio(serio);
if (attr == &atkbd_attr_function_row_physmap.attr &&
!atkbd->vdata.num_function_row_keys)
return 0;
return attr->mode;
}
static const struct attribute_group atkbd_attribute_group = {
.attrs = atkbd_attributes,
.is_visible = atkbd_attr_is_visible,
};
__ATTRIBUTE_GROUPS(atkbd_attribute);
static const unsigned int xl_table[] = {
ATKBD_RET_BAT, ATKBD_RET_ERR, ATKBD_RET_ACK,
ATKBD_RET_NAK, ATKBD_RET_HANJA, ATKBD_RET_HANGEUL,
};
/*
* Checks if we should mangle the scancode to extract 'release' bit
* in translated mode.
*/
static bool atkbd_need_xlate(unsigned long xl_bit, unsigned char code)
{
int i;
if (code == ATKBD_RET_EMUL0 || code == ATKBD_RET_EMUL1)
return false;
for (i = 0; i < ARRAY_SIZE(xl_table); i++)
if (code == xl_table[i])
return test_bit(i, &xl_bit);
return true;
}
/*
* Calculates new value of xl_bit so the driver can distinguish
* between make/break pair of scancodes for select keys and PS/2
* protocol responses.
*/
static void atkbd_calculate_xl_bit(struct atkbd *atkbd, unsigned char code)
{
int i;
for (i = 0; i < ARRAY_SIZE(xl_table); i++) {
if (!((code ^ xl_table[i]) & 0x7f)) {
if (code & 0x80)
__clear_bit(i, &atkbd->xl_bit);
else
__set_bit(i, &atkbd->xl_bit);
break;
}
}
}
/*
* Encode the scancode, 0xe0 prefix, and high bit into a single integer,
* keeping kernel 2.4 compatibility for set 2
*/
static unsigned int atkbd_compat_scancode(struct atkbd *atkbd, unsigned int code)
{
if (atkbd->set == 3) {
if (atkbd->emul == 1)
code |= 0x100;
} else {
code = (code & 0x7f) | ((code & 0x80) << 1);
if (atkbd->emul == 1)
code |= 0x80;
}
return code;
}
/*
* Tries to handle frame or parity error by requesting the keyboard controller
* to resend the last byte. This historically not done on x86 as controllers
* there typically do not implement this command.
*/
static bool __maybe_unused atkbd_handle_frame_error(struct ps2dev *ps2dev,
u8 data, unsigned int flags)
{
struct atkbd *atkbd = container_of(ps2dev, struct atkbd, ps2dev);
struct serio *serio = ps2dev->serio;
if ((flags & (SERIO_FRAME | SERIO_PARITY)) &&
(~flags & SERIO_TIMEOUT) &&
!atkbd->resend && atkbd->write) {
dev_warn(&serio->dev, "Frame/parity error: %02x\n", flags);
serio_write(serio, ATKBD_CMD_RESEND);
atkbd->resend = true;
return true;
}
if (!flags && data == ATKBD_RET_ACK)
atkbd->resend = false;
return false;
}
static enum ps2_disposition atkbd_pre_receive_byte(struct ps2dev *ps2dev,
u8 data, unsigned int flags)
{
struct serio *serio = ps2dev->serio;
dev_dbg(&serio->dev, "Received %02x flags %02x\n", data, flags);
#if !defined(__i386__) && !defined (__x86_64__)
if (atkbd_handle_frame_error(ps2dev, data, flags))
return PS2_IGNORE;
#endif
return PS2_PROCESS;
}
static void atkbd_receive_byte(struct ps2dev *ps2dev, u8 data)
{
struct serio *serio = ps2dev->serio;
struct atkbd *atkbd = container_of(ps2dev, struct atkbd, ps2dev);
struct input_dev *dev = atkbd->dev;
unsigned int code = data;
int scroll = 0, hscroll = 0, click = -1;
int value;
unsigned short keycode;
pm_wakeup_event(&serio->dev, 0);
if (!atkbd->enabled)
return;
input_event(dev, EV_MSC, MSC_RAW, code);
if (atkbd_platform_scancode_fixup)
code = atkbd_platform_scancode_fixup(atkbd, code);
if (atkbd->translated) {
if (atkbd->emul || atkbd_need_xlate(atkbd->xl_bit, code)) {
atkbd->release = code >> 7;
code &= 0x7f;
}
if (!atkbd->emul)
atkbd_calculate_xl_bit(atkbd, data);
}
switch (code) {
case ATKBD_RET_BAT:
atkbd->enabled = false;
serio_reconnect(atkbd->ps2dev.serio);
return;
case ATKBD_RET_EMUL0:
atkbd->emul = 1;
return;
case ATKBD_RET_EMUL1:
atkbd->emul = 2;
return;
case ATKBD_RET_RELEASE:
atkbd->release = true;
return;
case ATKBD_RET_ACK:
case ATKBD_RET_NAK:
if (printk_ratelimit())
dev_warn(&serio->dev,
"Spurious %s on %s. "
"Some program might be trying to access hardware directly.\n",
data == ATKBD_RET_ACK ? "ACK" : "NAK", serio->phys);
return;
case ATKBD_RET_ERR:
atkbd->err_count++;
dev_dbg(&serio->dev, "Keyboard on %s reports too many keys pressed.\n",
serio->phys);
return;
}
code = atkbd_compat_scancode(atkbd, code);
if (atkbd->emul && --atkbd->emul)
return;
keycode = atkbd->keycode[code];
if (!(atkbd->release && test_bit(code, atkbd->force_release_mask)))
if (keycode != ATKBD_KEY_NULL)
input_event(dev, EV_MSC, MSC_SCAN, code);
switch (keycode) {
case ATKBD_KEY_NULL:
break;
case ATKBD_KEY_UNKNOWN:
dev_warn(&serio->dev,
"Unknown key %s (%s set %d, code %#x on %s).\n",
atkbd->release ? "released" : "pressed",
atkbd->translated ? "translated" : "raw",
atkbd->set, code, serio->phys);
dev_warn(&serio->dev,
"Use 'setkeycodes %s%02x <keycode>' to make it known.\n",
code & 0x80 ? "e0" : "", code & 0x7f);
input_sync(dev);
break;
case ATKBD_SCR_1:
scroll = 1;
break;
case ATKBD_SCR_2:
scroll = 2;
break;
case ATKBD_SCR_4:
scroll = 4;
break;
case ATKBD_SCR_8:
scroll = 8;
break;
case ATKBD_SCR_CLICK:
click = !atkbd->release;
break;
case ATKBD_SCR_LEFT:
hscroll = -1;
break;
case ATKBD_SCR_RIGHT:
hscroll = 1;
break;
default:
if (atkbd->release) {
value = 0;
atkbd->last = 0;
} else if (!atkbd->softrepeat && test_bit(keycode, dev->key)) {
/* Workaround Toshiba laptop multiple keypress */
value = time_before(jiffies, atkbd->time) && atkbd->last == code ? 1 : 2;
} else {
value = 1;
atkbd->last = code;
atkbd->time = jiffies + msecs_to_jiffies(dev->rep[REP_DELAY]) / 2;
}
input_event(dev, EV_KEY, keycode, value);
input_sync(dev);
if (value && test_bit(code, atkbd->force_release_mask)) {
input_event(dev, EV_MSC, MSC_SCAN, code);
input_report_key(dev, keycode, 0);
input_sync(dev);
}
}
if (atkbd->scroll) {
if (click != -1)
input_report_key(dev, BTN_MIDDLE, click);
input_report_rel(dev, REL_WHEEL,
atkbd->release ? -scroll : scroll);
input_report_rel(dev, REL_HWHEEL, hscroll);
input_sync(dev);
}
atkbd->release = false;
}
static int atkbd_set_repeat_rate(struct atkbd *atkbd)
{
const short period[32] =
{ 33, 37, 42, 46, 50, 54, 58, 63, 67, 75, 83, 92, 100, 109, 116, 125,
133, 149, 167, 182, 200, 217, 232, 250, 270, 303, 333, 370, 400, 435, 470, 500 };
const short delay[4] =
{ 250, 500, 750, 1000 };
struct input_dev *dev = atkbd->dev;
unsigned char param;
int i = 0, j = 0;
while (i < ARRAY_SIZE(period) - 1 && period[i] < dev->rep[REP_PERIOD])
i++;
dev->rep[REP_PERIOD] = period[i];
while (j < ARRAY_SIZE(delay) - 1 && delay[j] < dev->rep[REP_DELAY])
j++;
dev->rep[REP_DELAY] = delay[j];
param = i | (j << 5);
return ps2_command(&atkbd->ps2dev, ¶m, ATKBD_CMD_SETREP);
}
static int atkbd_set_leds(struct atkbd *atkbd)
{
struct input_dev *dev = atkbd->dev;
unsigned char param[2];
param[0] = (test_bit(LED_SCROLLL, dev->led) ? 1 : 0)
| (test_bit(LED_NUML, dev->led) ? 2 : 0)
| (test_bit(LED_CAPSL, dev->led) ? 4 : 0);
if (ps2_command(&atkbd->ps2dev, param, ATKBD_CMD_SETLEDS))
return -1;
if (atkbd->extra) {
param[0] = 0;
param[1] = (test_bit(LED_COMPOSE, dev->led) ? 0x01 : 0)
| (test_bit(LED_SLEEP, dev->led) ? 0x02 : 0)
| (test_bit(LED_SUSPEND, dev->led) ? 0x04 : 0)
| (test_bit(LED_MISC, dev->led) ? 0x10 : 0)
| (test_bit(LED_MUTE, dev->led) ? 0x20 : 0);
if (ps2_command(&atkbd->ps2dev, param, ATKBD_CMD_EX_SETLEDS))
return -1;
}
return 0;
}
/*
* atkbd_event_work() is used to complete processing of events that
* can not be processed by input_event() which is often called from
* interrupt context.
*/
static void atkbd_event_work(struct work_struct *work)
{
struct atkbd *atkbd = container_of(work, struct atkbd, event_work.work);
mutex_lock(&atkbd->mutex);
if (!atkbd->enabled) {
/*
* Serio ports are resumed asynchronously so while driver core
* thinks that device is already fully operational in reality
* it may not be ready yet. In this case we need to keep
* rescheduling till reconnect completes.
*/
schedule_delayed_work(&atkbd->event_work,
msecs_to_jiffies(100));
} else {
if (test_and_clear_bit(ATKBD_LED_EVENT_BIT, &atkbd->event_mask))
atkbd_set_leds(atkbd);
if (test_and_clear_bit(ATKBD_REP_EVENT_BIT, &atkbd->event_mask))
atkbd_set_repeat_rate(atkbd);
}
mutex_unlock(&atkbd->mutex);
}
/*
* Schedule switch for execution. We need to throttle requests,
* otherwise keyboard may become unresponsive.
*/
static void atkbd_schedule_event_work(struct atkbd *atkbd, int event_bit)
{
unsigned long delay = msecs_to_jiffies(50);
if (time_after(jiffies, atkbd->event_jiffies + delay))
delay = 0;
atkbd->event_jiffies = jiffies;
set_bit(event_bit, &atkbd->event_mask);
mb();
schedule_delayed_work(&atkbd->event_work, delay);
}
/*
* Event callback from the input module. Events that change the state of
* the hardware are processed here. If action can not be performed in
* interrupt context it is offloaded to atkbd_event_work.
*/
static int atkbd_event(struct input_dev *dev,
unsigned int type, unsigned int code, int value)
{
struct atkbd *atkbd = input_get_drvdata(dev);
if (!atkbd->write)
return -1;
switch (type) {
case EV_LED:
atkbd_schedule_event_work(atkbd, ATKBD_LED_EVENT_BIT);
return 0;
case EV_REP:
if (!atkbd->softrepeat)
atkbd_schedule_event_work(atkbd, ATKBD_REP_EVENT_BIT);
return 0;
default:
return -1;
}
}
/*
* atkbd_enable() signals that interrupt handler is allowed to
* generate input events.
*/
static inline void atkbd_enable(struct atkbd *atkbd)
{
serio_pause_rx(atkbd->ps2dev.serio);
atkbd->enabled = true;
serio_continue_rx(atkbd->ps2dev.serio);
}
/*
* atkbd_disable() tells input handler that all incoming data except
* for ACKs and command response should be dropped.
*/
static inline void atkbd_disable(struct atkbd *atkbd)
{
serio_pause_rx(atkbd->ps2dev.serio);
atkbd->enabled = false;
serio_continue_rx(atkbd->ps2dev.serio);
}
static int atkbd_activate(struct atkbd *atkbd)
{
struct ps2dev *ps2dev = &atkbd->ps2dev;
/*
* Enable the keyboard to receive keystrokes.
*/
if (ps2_command(ps2dev, NULL, ATKBD_CMD_ENABLE)) {
dev_err(&ps2dev->serio->dev,
"Failed to enable keyboard on %s\n",
ps2dev->serio->phys);
return -1;
}
return 0;
}
/*
* atkbd_deactivate() resets and disables the keyboard from sending
* keystrokes.
*/
static void atkbd_deactivate(struct atkbd *atkbd)
{
struct ps2dev *ps2dev = &atkbd->ps2dev;
if (ps2_command(ps2dev, NULL, ATKBD_CMD_RESET_DIS))
dev_err(&ps2dev->serio->dev,
"Failed to deactivate keyboard on %s\n",
ps2dev->serio->phys);
}
/*
* atkbd_probe() probes for an AT keyboard on a serio port.
*/
static int atkbd_probe(struct atkbd *atkbd)
{
struct ps2dev *ps2dev = &atkbd->ps2dev;
unsigned char param[2];
/*
* Some systems, where the bit-twiddling when testing the io-lines of the
* controller may confuse the keyboard need a full reset of the keyboard. On
* these systems the BIOS also usually doesn't do it for us.
*/
if (atkbd_reset)
if (ps2_command(ps2dev, NULL, ATKBD_CMD_RESET_BAT))
dev_warn(&ps2dev->serio->dev,
"keyboard reset failed on %s\n",
ps2dev->serio->phys);
/*
* Then we check the keyboard ID. We should get 0xab83 under normal conditions.
* Some keyboards report different values, but the first byte is always 0xab or
* 0xac. Some old AT keyboards don't report anything. If a mouse is connected, this
* should make sure we don't try to set the LEDs on it.
*/
param[0] = param[1] = 0xa5; /* initialize with invalid values */
if (ps2_command(ps2dev, param, ATKBD_CMD_GETID)) {
/*
* If the get ID command failed, we check if we can at least set the LEDs on
* the keyboard. This should work on every keyboard out there. It also turns
* the LEDs off, which we want anyway.
*/
param[0] = 0;
if (ps2_command(ps2dev, param, ATKBD_CMD_SETLEDS))
return -1;
atkbd->id = 0xabba;
return 0;
}
if (!ps2_is_keyboard_id(param[0]))
return -1;
atkbd->id = (param[0] << 8) | param[1];
if (atkbd->id == 0xaca1 && atkbd->translated) {
dev_err(&ps2dev->serio->dev,
"NCD terminal keyboards are only supported on non-translating controllers. "
"Use i8042.direct=1 to disable translation.\n");
return -1;
}
/*
* Make sure nothing is coming from the keyboard and disturbs our
* internal state.
*/
if (!atkbd_skip_deactivate)
atkbd_deactivate(atkbd);
return 0;
}
/*
* atkbd_select_set checks if a keyboard has a working Set 3 support, and
* sets it into that. Unfortunately there are keyboards that can be switched
* to Set 3, but don't work well in that (BTC Multimedia ...)
*/
static int atkbd_select_set(struct atkbd *atkbd, int target_set, int allow_extra)
{
struct ps2dev *ps2dev = &atkbd->ps2dev;
unsigned char param[2];
atkbd->extra = false;
/*
* For known special keyboards we can go ahead and set the correct set.
* We check for NCD PS/2 Sun, NorthGate OmniKey 101 and
* IBM RapidAccess / IBM EzButton / Chicony KBP-8993 keyboards.
*/
if (atkbd->translated)
return 2;
if (atkbd->id == 0xaca1) {
param[0] = 3;
ps2_command(ps2dev, param, ATKBD_CMD_SSCANSET);
return 3;
}
if (allow_extra) {
param[0] = 0x71;
if (!ps2_command(ps2dev, param, ATKBD_CMD_EX_ENABLE)) {
atkbd->extra = true;
return 2;
}
}
if (atkbd_terminal) {
ps2_command(ps2dev, param, ATKBD_CMD_SETALL_MB);
return 3;
}
if (target_set != 3)
return 2;
if (!ps2_command(ps2dev, param, ATKBD_CMD_OK_GETID)) {
atkbd->id = param[0] << 8 | param[1];
return 2;
}
param[0] = 3;
if (ps2_command(ps2dev, param, ATKBD_CMD_SSCANSET))
return 2;
param[0] = 0;
if (ps2_command(ps2dev, param, ATKBD_CMD_GSCANSET))
return 2;
if (param[0] != 3) {
param[0] = 2;
if (ps2_command(ps2dev, param, ATKBD_CMD_SSCANSET))
return 2;
}
ps2_command(ps2dev, param, ATKBD_CMD_SETALL_MBR);
return 3;
}
static int atkbd_reset_state(struct atkbd *atkbd)
{
struct ps2dev *ps2dev = &atkbd->ps2dev;
unsigned char param[1];
/*
* Set the LEDs to a predefined state (all off).
*/
param[0] = 0;
if (ps2_command(ps2dev, param, ATKBD_CMD_SETLEDS))
return -1;
/*
* Set autorepeat to fastest possible.
*/
param[0] = 0;
if (ps2_command(ps2dev, param, ATKBD_CMD_SETREP))
return -1;
return 0;
}
/*
* atkbd_cleanup() restores the keyboard state so that BIOS is happy after a
* reboot.
*/
static void atkbd_cleanup(struct serio *serio)
{
struct atkbd *atkbd = atkbd_from_serio(serio);
atkbd_disable(atkbd);
ps2_command(&atkbd->ps2dev, NULL, ATKBD_CMD_RESET_DEF);
}
/*
* atkbd_disconnect() closes and frees.
*/
static void atkbd_disconnect(struct serio *serio)
{
struct atkbd *atkbd = atkbd_from_serio(serio);
atkbd_disable(atkbd);
input_unregister_device(atkbd->dev);
/*
* Make sure we don't have a command in flight.
* Note that since atkbd->enabled is false event work will keep
* rescheduling itself until it gets canceled and will not try
* accessing freed input device or serio port.
*/
cancel_delayed_work_sync(&atkbd->event_work);
serio_close(serio);
serio_set_drvdata(serio, NULL);
kfree(atkbd);
}
/*
* generate release events for the keycodes given in data
*/
static void atkbd_apply_forced_release_keylist(struct atkbd* atkbd,
const void *data)
{
const unsigned int *keys = data;
unsigned int i;
if (atkbd->set == 2)
for (i = 0; keys[i] != -1U; i++)
__set_bit(keys[i], atkbd->force_release_mask);
}
/*
* Most special keys (Fn+F?) on Dell laptops do not generate release
* events so we have to do it ourselves.
*/
static unsigned int atkbd_dell_laptop_forced_release_keys[] = {
0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8f, 0x93, -1U
};
/*
* Perform fixup for HP system that doesn't generate release
* for its video switch
*/
static unsigned int atkbd_hp_forced_release_keys[] = {
0x94, -1U
};
/*
* Samsung NC10,NC20 with Fn+F? key release not working
*/
static unsigned int atkbd_samsung_forced_release_keys[] = {
0x82, 0x83, 0x84, 0x86, 0x88, 0x89, 0xb3, 0xf7, 0xf9, -1U
};
/*
* Amilo Pi 3525 key release for Fn+Volume keys not working
*/
static unsigned int atkbd_amilo_pi3525_forced_release_keys[] = {
0x20, 0xa0, 0x2e, 0xae, 0x30, 0xb0, -1U
};
/*
* Amilo Xi 3650 key release for light touch bar not working
*/
static unsigned int atkbd_amilo_xi3650_forced_release_keys[] = {
0x67, 0xed, 0x90, 0xa2, 0x99, 0xa4, 0xae, 0xb0, -1U
};
/*
* Soltech TA12 system with broken key release on volume keys and mute key
*/
static unsigned int atkdb_soltech_ta12_forced_release_keys[] = {
0xa0, 0xae, 0xb0, -1U
};
/*
* Many notebooks don't send key release event for volume up/down
* keys, with key list below common among them
*/
static unsigned int atkbd_volume_forced_release_keys[] = {
0xae, 0xb0, -1U
};
/*
* OQO 01+ multimedia keys (64--66) generate e0 6x upon release whereas
* they should be generating e4-e6 (0x80 | code).
*/
static unsigned int atkbd_oqo_01plus_scancode_fixup(struct atkbd *atkbd,
unsigned int code)
{
if (atkbd->translated && atkbd->emul == 1 &&
(code == 0x64 || code == 0x65 || code == 0x66)) {
atkbd->emul = 0;
code |= 0x80;
}
return code;
}
static int atkbd_get_keymap_from_fwnode(struct atkbd *atkbd)
{
struct device *dev = &atkbd->ps2dev.serio->dev;
int i, n;
u32 *ptr;
u16 scancode, keycode;
/* Parse "linux,keymap" property */
n = device_property_count_u32(dev, "linux,keymap");
if (n <= 0 || n > ATKBD_KEYMAP_SIZE)
return -ENXIO;
ptr = kcalloc(n, sizeof(u32), GFP_KERNEL);
if (!ptr)
return -ENOMEM;
if (device_property_read_u32_array(dev, "linux,keymap", ptr, n)) {
dev_err(dev, "problem parsing FW keymap property\n");
kfree(ptr);
return -EINVAL;
}
memset(atkbd->keycode, 0, sizeof(atkbd->keycode));
for (i = 0; i < n; i++) {
scancode = SCANCODE(ptr[i]);
keycode = KEYCODE(ptr[i]);
atkbd->keycode[scancode] = keycode;
}
kfree(ptr);
return 0;
}
/*
* atkbd_set_keycode_table() initializes keyboard's keycode table
* according to the selected scancode set
*/
static void atkbd_set_keycode_table(struct atkbd *atkbd)
{
struct device *dev = &atkbd->ps2dev.serio->dev;
unsigned int scancode;
int i, j;
memset(atkbd->keycode, 0, sizeof(atkbd->keycode));
bitmap_zero(atkbd->force_release_mask, ATKBD_KEYMAP_SIZE);
if (!atkbd_get_keymap_from_fwnode(atkbd)) {
dev_dbg(dev, "Using FW keymap\n");
} else if (atkbd->translated) {
for (i = 0; i < 128; i++) {
scancode = atkbd_unxlate_table[i];
atkbd->keycode[i] = atkbd_set2_keycode[scancode];
atkbd->keycode[i | 0x80] = atkbd_set2_keycode[scancode | 0x80];
if (atkbd->scroll)
for (j = 0; j < ARRAY_SIZE(atkbd_scroll_keys); j++)
if ((scancode | 0x80) == atkbd_scroll_keys[j].set2)
atkbd->keycode[i | 0x80] = atkbd_scroll_keys[j].keycode;
}
} else if (atkbd->set == 3) {
memcpy(atkbd->keycode, atkbd_set3_keycode, sizeof(atkbd->keycode));
} else {
memcpy(atkbd->keycode, atkbd_set2_keycode, sizeof(atkbd->keycode));
if (atkbd->scroll)
for (i = 0; i < ARRAY_SIZE(atkbd_scroll_keys); i++) {
scancode = atkbd_scroll_keys[i].set2;
atkbd->keycode[scancode] = atkbd_scroll_keys[i].keycode;
}
}
/*
* HANGEUL and HANJA keys do not send release events so we need to
* generate such events ourselves
*/
scancode = atkbd_compat_scancode(atkbd, ATKBD_RET_HANGEUL);
atkbd->keycode[scancode] = KEY_HANGEUL;
__set_bit(scancode, atkbd->force_release_mask);
scancode = atkbd_compat_scancode(atkbd, ATKBD_RET_HANJA);
atkbd->keycode[scancode] = KEY_HANJA;
__set_bit(scancode, atkbd->force_release_mask);
/*
* Perform additional fixups
*/
if (atkbd_platform_fixup)
atkbd_platform_fixup(atkbd, atkbd_platform_fixup_data);
}
/*
* atkbd_set_device_attrs() sets up keyboard's input device structure
*/
static void atkbd_set_device_attrs(struct atkbd *atkbd)
{
struct input_dev *input_dev = atkbd->dev;
int i;
if (atkbd->extra)
snprintf(atkbd->name, sizeof(atkbd->name),
"AT Set 2 Extra keyboard");
else
snprintf(atkbd->name, sizeof(atkbd->name),
"AT %s Set %d keyboard",
atkbd->translated ? "Translated" : "Raw", atkbd->set);
snprintf(atkbd->phys, sizeof(atkbd->phys),
"%s/input0", atkbd->ps2dev.serio->phys);
input_dev->name = atkbd->name;
input_dev->phys = atkbd->phys;
input_dev->id.bustype = BUS_I8042;
input_dev->id.vendor = 0x0001;
input_dev->id.product = atkbd->translated ? 1 : atkbd->set;
input_dev->id.version = atkbd->id;
input_dev->event = atkbd_event;
input_dev->dev.parent = &atkbd->ps2dev.serio->dev;
input_set_drvdata(input_dev, atkbd);
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP) |
BIT_MASK(EV_MSC);
if (atkbd->write) {
input_dev->evbit[0] |= BIT_MASK(EV_LED);
input_dev->ledbit[0] = BIT_MASK(LED_NUML) |
BIT_MASK(LED_CAPSL) | BIT_MASK(LED_SCROLLL);
}
if (atkbd->extra)
input_dev->ledbit[0] |= BIT_MASK(LED_COMPOSE) |
BIT_MASK(LED_SUSPEND) | BIT_MASK(LED_SLEEP) |
BIT_MASK(LED_MUTE) | BIT_MASK(LED_MISC);
if (!atkbd->softrepeat) {
input_dev->rep[REP_DELAY] = 250;
input_dev->rep[REP_PERIOD] = 33;
}
input_dev->mscbit[0] = atkbd->softraw ? BIT_MASK(MSC_SCAN) :
BIT_MASK(MSC_RAW) | BIT_MASK(MSC_SCAN);
if (atkbd->scroll) {
input_dev->evbit[0] |= BIT_MASK(EV_REL);
input_dev->relbit[0] = BIT_MASK(REL_WHEEL) |
BIT_MASK(REL_HWHEEL);
__set_bit(BTN_MIDDLE, input_dev->keybit);
}
input_dev->keycode = atkbd->keycode;
input_dev->keycodesize = sizeof(unsigned short);
input_dev->keycodemax = ARRAY_SIZE(atkbd_set2_keycode);
for (i = 0; i < ATKBD_KEYMAP_SIZE; i++) {
if (atkbd->keycode[i] != KEY_RESERVED &&
atkbd->keycode[i] != ATKBD_KEY_NULL &&
atkbd->keycode[i] < ATKBD_SPECIAL) {
__set_bit(atkbd->keycode[i], input_dev->keybit);
}
}
}
static void atkbd_parse_fwnode_data(struct serio *serio)
{
struct atkbd *atkbd = atkbd_from_serio(serio);
struct device *dev = &serio->dev;
int n;
/* Parse "function-row-physmap" property */
n = device_property_count_u32(dev, "function-row-physmap");
if (n > 0 && n <= VIVALDI_MAX_FUNCTION_ROW_KEYS &&
!device_property_read_u32_array(dev, "function-row-physmap",
atkbd->vdata.function_row_physmap,
n)) {
atkbd->vdata.num_function_row_keys = n;
dev_dbg(dev, "FW reported %d function-row key locations\n", n);
}
}
/*
* atkbd_connect() is called when the serio module finds an interface
* that isn't handled yet by an appropriate device driver. We check if
* there is an AT keyboard out there and if yes, we register ourselves
* to the input module.
*/
static int atkbd_connect(struct serio *serio, struct serio_driver *drv)
{
struct atkbd *atkbd;
struct input_dev *dev;
int err = -ENOMEM;
atkbd = kzalloc(sizeof(struct atkbd), GFP_KERNEL);
dev = input_allocate_device();
if (!atkbd || !dev)
goto fail1;
atkbd->dev = dev;
ps2_init(&atkbd->ps2dev, serio,
atkbd_pre_receive_byte, atkbd_receive_byte);
INIT_DELAYED_WORK(&atkbd->event_work, atkbd_event_work);
mutex_init(&atkbd->mutex);
switch (serio->id.type) {
case SERIO_8042_XL:
atkbd->translated = true;
fallthrough;
case SERIO_8042:
if (serio->write)
atkbd->write = true;
break;
}
atkbd->softraw = atkbd_softraw;
atkbd->softrepeat = atkbd_softrepeat;
atkbd->scroll = atkbd_scroll;
if (atkbd->softrepeat)
atkbd->softraw = true;
serio_set_drvdata(serio, atkbd);
err = serio_open(serio, drv);
if (err)
goto fail2;
if (atkbd->write) {
if (atkbd_probe(atkbd)) {
err = -ENODEV;
goto fail3;
}
atkbd->set = atkbd_select_set(atkbd, atkbd_set, atkbd_extra);
atkbd_reset_state(atkbd);
} else {
atkbd->set = 2;
atkbd->id = 0xab00;
}
atkbd_parse_fwnode_data(serio);
atkbd_set_keycode_table(atkbd);
atkbd_set_device_attrs(atkbd);
atkbd_enable(atkbd);
if (serio->write)
atkbd_activate(atkbd);
err = input_register_device(atkbd->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(dev);
kfree(atkbd);
return err;
}
/*
* atkbd_reconnect() tries to restore keyboard into a sane state and is
* most likely called on resume.
*/
static int atkbd_reconnect(struct serio *serio)
{
struct atkbd *atkbd = atkbd_from_serio(serio);
struct serio_driver *drv = serio->drv;
int retval = -1;
if (!atkbd || !drv) {
dev_dbg(&serio->dev,
"reconnect request, but serio is disconnected, ignoring...\n");
return -1;
}
mutex_lock(&atkbd->mutex);
atkbd_disable(atkbd);
if (atkbd->write) {
if (atkbd_probe(atkbd))
goto out;
if (atkbd->set != atkbd_select_set(atkbd, atkbd->set, atkbd->extra))
goto out;
/*
* Restore LED state and repeat rate. While input core
* will do this for us at resume time reconnect may happen
* because user requested it via sysfs or simply because
* keyboard was unplugged and plugged in again so we need
* to do it ourselves here.
*/
atkbd_set_leds(atkbd);
if (!atkbd->softrepeat)
atkbd_set_repeat_rate(atkbd);
}
/*
* Reset our state machine in case reconnect happened in the middle
* of multi-byte scancode.
*/
atkbd->xl_bit = 0;
atkbd->emul = 0;
atkbd_enable(atkbd);
if (atkbd->write)
atkbd_activate(atkbd);
retval = 0;
out:
mutex_unlock(&atkbd->mutex);
return retval;
}
static const struct serio_device_id atkbd_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,
},
{
.type = SERIO_RS232,
.proto = SERIO_PS2SER,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, atkbd_serio_ids);
static struct serio_driver atkbd_drv = {
.driver = {
.name = "atkbd",
.dev_groups = atkbd_attribute_groups,
},
.description = DRIVER_DESC,
.id_table = atkbd_serio_ids,
.interrupt = ps2_interrupt,
.connect = atkbd_connect,
.reconnect = atkbd_reconnect,
.disconnect = atkbd_disconnect,
.cleanup = atkbd_cleanup,
};
static ssize_t atkbd_attr_show_helper(struct device *dev, char *buf,
ssize_t (*handler)(struct atkbd *, char *))
{
struct serio *serio = to_serio_port(dev);
struct atkbd *atkbd = atkbd_from_serio(serio);
return handler(atkbd, buf);
}
static ssize_t atkbd_attr_set_helper(struct device *dev, const char *buf, size_t count,
ssize_t (*handler)(struct atkbd *, const char *, size_t))
{
struct serio *serio = to_serio_port(dev);
struct atkbd *atkbd = atkbd_from_serio(serio);
int retval;
retval = mutex_lock_interruptible(&atkbd->mutex);
if (retval)
return retval;
atkbd_disable(atkbd);
retval = handler(atkbd, buf, count);
atkbd_enable(atkbd);
mutex_unlock(&atkbd->mutex);
return retval;
}
static ssize_t atkbd_show_extra(struct atkbd *atkbd, char *buf)
{
return sprintf(buf, "%d\n", atkbd->extra ? 1 : 0);
}
static ssize_t atkbd_set_extra(struct atkbd *atkbd, const char *buf, size_t count)
{
struct input_dev *old_dev, *new_dev;
unsigned int value;
int err;
bool old_extra;
unsigned char old_set;
if (!atkbd->write)
return -EIO;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
if (atkbd->extra != value) {
/*
* Since device's properties will change we need to
* unregister old device. But allocate and register
* new one first to make sure we have it.
*/
old_dev = atkbd->dev;
old_extra = atkbd->extra;
old_set = atkbd->set;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
atkbd->dev = new_dev;
atkbd->set = atkbd_select_set(atkbd, atkbd->set, value);
atkbd_reset_state(atkbd);
atkbd_activate(atkbd);
atkbd_set_keycode_table(atkbd);
atkbd_set_device_attrs(atkbd);
err = input_register_device(atkbd->dev);
if (err) {
input_free_device(new_dev);
atkbd->dev = old_dev;
atkbd->set = atkbd_select_set(atkbd, old_set, old_extra);
atkbd_set_keycode_table(atkbd);
atkbd_set_device_attrs(atkbd);
return err;
}
input_unregister_device(old_dev);
}
return count;
}
static ssize_t atkbd_show_force_release(struct atkbd *atkbd, char *buf)
{
size_t len = scnprintf(buf, PAGE_SIZE - 1, "%*pbl",
ATKBD_KEYMAP_SIZE, atkbd->force_release_mask);
buf[len++] = '\n';
buf[len] = '\0';
return len;
}
static ssize_t atkbd_set_force_release(struct atkbd *atkbd,
const char *buf, size_t count)
{
/* 64 bytes on stack should be acceptable */
DECLARE_BITMAP(new_mask, ATKBD_KEYMAP_SIZE);
int err;
err = bitmap_parselist(buf, new_mask, ATKBD_KEYMAP_SIZE);
if (err)
return err;
memcpy(atkbd->force_release_mask, new_mask, sizeof(atkbd->force_release_mask));
return count;
}
static ssize_t atkbd_show_scroll(struct atkbd *atkbd, char *buf)
{
return sprintf(buf, "%d\n", atkbd->scroll ? 1 : 0);
}
static ssize_t atkbd_set_scroll(struct atkbd *atkbd, const char *buf, size_t count)
{
struct input_dev *old_dev, *new_dev;
unsigned int value;
int err;
bool old_scroll;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
if (atkbd->scroll != value) {
old_dev = atkbd->dev;
old_scroll = atkbd->scroll;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
atkbd->dev = new_dev;
atkbd->scroll = value;
atkbd_set_keycode_table(atkbd);
atkbd_set_device_attrs(atkbd);
err = input_register_device(atkbd->dev);
if (err) {
input_free_device(new_dev);
atkbd->scroll = old_scroll;
atkbd->dev = old_dev;
atkbd_set_keycode_table(atkbd);
atkbd_set_device_attrs(atkbd);
return err;
}
input_unregister_device(old_dev);
}
return count;
}
static ssize_t atkbd_show_set(struct atkbd *atkbd, char *buf)
{
return sprintf(buf, "%d\n", atkbd->set);
}
static ssize_t atkbd_set_set(struct atkbd *atkbd, const char *buf, size_t count)
{
struct input_dev *old_dev, *new_dev;
unsigned int value;
int err;
unsigned char old_set;
bool old_extra;
if (!atkbd->write)
return -EIO;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value != 2 && value != 3)
return -EINVAL;
if (atkbd->set != value) {
old_dev = atkbd->dev;
old_extra = atkbd->extra;
old_set = atkbd->set;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
atkbd->dev = new_dev;
atkbd->set = atkbd_select_set(atkbd, value, atkbd->extra);
atkbd_reset_state(atkbd);
atkbd_activate(atkbd);
atkbd_set_keycode_table(atkbd);
atkbd_set_device_attrs(atkbd);
err = input_register_device(atkbd->dev);
if (err) {
input_free_device(new_dev);
atkbd->dev = old_dev;
atkbd->set = atkbd_select_set(atkbd, old_set, old_extra);
atkbd_set_keycode_table(atkbd);
atkbd_set_device_attrs(atkbd);
return err;
}
input_unregister_device(old_dev);
}
return count;
}
static ssize_t atkbd_show_softrepeat(struct atkbd *atkbd, char *buf)
{
return sprintf(buf, "%d\n", atkbd->softrepeat ? 1 : 0);
}
static ssize_t atkbd_set_softrepeat(struct atkbd *atkbd, const char *buf, size_t count)
{
struct input_dev *old_dev, *new_dev;
unsigned int value;
int err;
bool old_softrepeat, old_softraw;
if (!atkbd->write)
return -EIO;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
if (atkbd->softrepeat != value) {
old_dev = atkbd->dev;
old_softrepeat = atkbd->softrepeat;
old_softraw = atkbd->softraw;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
atkbd->dev = new_dev;
atkbd->softrepeat = value;
if (atkbd->softrepeat)
atkbd->softraw = true;
atkbd_set_device_attrs(atkbd);
err = input_register_device(atkbd->dev);
if (err) {
input_free_device(new_dev);
atkbd->dev = old_dev;
atkbd->softrepeat = old_softrepeat;
atkbd->softraw = old_softraw;
atkbd_set_device_attrs(atkbd);
return err;
}
input_unregister_device(old_dev);
}
return count;
}
static ssize_t atkbd_show_softraw(struct atkbd *atkbd, char *buf)
{
return sprintf(buf, "%d\n", atkbd->softraw ? 1 : 0);
}
static ssize_t atkbd_set_softraw(struct atkbd *atkbd, const char *buf, size_t count)
{
struct input_dev *old_dev, *new_dev;
unsigned int value;
int err;
bool old_softraw;
err = kstrtouint(buf, 10, &value);
if (err)
return err;
if (value > 1)
return -EINVAL;
if (atkbd->softraw != value) {
old_dev = atkbd->dev;
old_softraw = atkbd->softraw;
new_dev = input_allocate_device();
if (!new_dev)
return -ENOMEM;
atkbd->dev = new_dev;
atkbd->softraw = value;
atkbd_set_device_attrs(atkbd);
err = input_register_device(atkbd->dev);
if (err) {
input_free_device(new_dev);
atkbd->dev = old_dev;
atkbd->softraw = old_softraw;
atkbd_set_device_attrs(atkbd);
return err;
}
input_unregister_device(old_dev);
}
return count;
}
static ssize_t atkbd_show_err_count(struct atkbd *atkbd, char *buf)
{
return sprintf(buf, "%lu\n", atkbd->err_count);
}
static int __init atkbd_setup_forced_release(const struct dmi_system_id *id)
{
atkbd_platform_fixup = atkbd_apply_forced_release_keylist;
atkbd_platform_fixup_data = id->driver_data;
return 1;
}
static int __init atkbd_setup_scancode_fixup(const struct dmi_system_id *id)
{
atkbd_platform_scancode_fixup = id->driver_data;
return 1;
}
static int __init atkbd_deactivate_fixup(const struct dmi_system_id *id)
{
atkbd_skip_deactivate = true;
return 1;
}
/*
* NOTE: do not add any more "force release" quirks to this table. The
* task of adjusting list of keys that should be "released" automatically
* by the driver is now delegated to userspace tools, such as udev, so
* submit such quirks there.
*/
static const struct dmi_system_id atkbd_dmi_quirk_table[] __initconst = {
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Dell Inc."),
DMI_MATCH(DMI_CHASSIS_TYPE, "8"), /* Portable */
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_dell_laptop_forced_release_keys,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Dell Computer Corporation"),
DMI_MATCH(DMI_CHASSIS_TYPE, "8"), /* Portable */
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_dell_laptop_forced_release_keys,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "HP 2133"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_hp_forced_release_keys,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "Pavilion ZV6100"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_volume_forced_release_keys,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "Presario R4000"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_volume_forced_release_keys,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "Presario R4100"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_volume_forced_release_keys,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Hewlett-Packard"),
DMI_MATCH(DMI_PRODUCT_NAME, "Presario R4200"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_volume_forced_release_keys,
},
{
/* Inventec Symphony */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "INVENTEC"),
DMI_MATCH(DMI_PRODUCT_NAME, "SYMPHONY 6.0/7.0"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_volume_forced_release_keys,
},
{
/* Samsung NC10 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC10"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_samsung_forced_release_keys,
},
{
/* Samsung NC20 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "NC20"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_samsung_forced_release_keys,
},
{
/* Samsung SQ45S70S */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "SAMSUNG ELECTRONICS CO., LTD."),
DMI_MATCH(DMI_PRODUCT_NAME, "SQ45S70S"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_samsung_forced_release_keys,
},
{
/* Fujitsu Amilo PA 1510 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Pa 1510"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_volume_forced_release_keys,
},
{
/* Fujitsu Amilo Pi 3525 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Pi 3525"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_amilo_pi3525_forced_release_keys,
},
{
/* Fujitsu Amilo Xi 3650 */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "FUJITSU SIEMENS"),
DMI_MATCH(DMI_PRODUCT_NAME, "AMILO Xi 3650"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkbd_amilo_xi3650_forced_release_keys,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "Soltech Corporation"),
DMI_MATCH(DMI_PRODUCT_NAME, "TA12"),
},
.callback = atkbd_setup_forced_release,
.driver_data = atkdb_soltech_ta12_forced_release_keys,
},
{
/* OQO Model 01+ */
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "OQO"),
DMI_MATCH(DMI_PRODUCT_NAME, "ZEPTO"),
},
.callback = atkbd_setup_scancode_fixup,
.driver_data = atkbd_oqo_01plus_scancode_fixup,
},
{
.matches = {
DMI_MATCH(DMI_SYS_VENDOR, "LG Electronics"),
},
.callback = atkbd_deactivate_fixup,
},
{ }
};
static int __init atkbd_init(void)
{
dmi_check_system(atkbd_dmi_quirk_table);
return serio_register_driver(&atkbd_drv);
}
static void __exit atkbd_exit(void)
{
serio_unregister_driver(&atkbd_drv);
}
module_init(atkbd_init);
module_exit(atkbd_exit);
|
linux-master
|
drivers/input/keyboard/atkbd.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* twl4030_keypad.c - driver for 8x8 keypad controller in twl4030 chips
*
* Copyright (C) 2007 Texas Instruments, Inc.
* Copyright (C) 2008 Nokia Corporation
*
* Code re-written for 2430SDP by:
* Syed Mohammed Khasim <[email protected]>
*
* Initial Code:
* Manjunatha G K <[email protected]>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/platform_device.h>
#include <linux/mfd/twl.h>
#include <linux/slab.h>
#include <linux/of.h>
/*
* The TWL4030 family chips include a keypad controller that supports
* up to an 8x8 switch matrix. The controller can issue system wakeup
* events, since it uses only the always-on 32KiHz oscillator, and has
* an internal state machine that decodes pressed keys, including
* multi-key combinations.
*
* This driver lets boards define what keycodes they wish to report for
* which scancodes, as part of the "struct twl4030_keypad_data" used in
* the probe() routine.
*
* See the TPS65950 documentation; that's the general availability
* version of the TWL5030 second generation part.
*/
#define TWL4030_MAX_ROWS 8 /* TWL4030 hard limit */
#define TWL4030_MAX_COLS 8
/*
* Note that we add space for an extra column so that we can handle
* row lines connected to the gnd (see twl4030_col_xlate()).
*/
#define TWL4030_ROW_SHIFT 4
#define TWL4030_KEYMAP_SIZE (TWL4030_MAX_ROWS << TWL4030_ROW_SHIFT)
struct twl4030_keypad {
unsigned short keymap[TWL4030_KEYMAP_SIZE];
u16 kp_state[TWL4030_MAX_ROWS];
bool autorepeat;
unsigned int n_rows;
unsigned int n_cols;
int irq;
struct device *dbg_dev;
struct input_dev *input;
};
/*----------------------------------------------------------------------*/
/* arbitrary prescaler value 0..7 */
#define PTV_PRESCALER 4
/* Register Offsets */
#define KEYP_CTRL 0x00
#define KEYP_DEB 0x01
#define KEYP_LONG_KEY 0x02
#define KEYP_LK_PTV 0x03
#define KEYP_TIMEOUT_L 0x04
#define KEYP_TIMEOUT_H 0x05
#define KEYP_KBC 0x06
#define KEYP_KBR 0x07
#define KEYP_SMS 0x08
#define KEYP_FULL_CODE_7_0 0x09 /* row 0 column status */
#define KEYP_FULL_CODE_15_8 0x0a /* ... row 1 ... */
#define KEYP_FULL_CODE_23_16 0x0b
#define KEYP_FULL_CODE_31_24 0x0c
#define KEYP_FULL_CODE_39_32 0x0d
#define KEYP_FULL_CODE_47_40 0x0e
#define KEYP_FULL_CODE_55_48 0x0f
#define KEYP_FULL_CODE_63_56 0x10
#define KEYP_ISR1 0x11
#define KEYP_IMR1 0x12
#define KEYP_ISR2 0x13
#define KEYP_IMR2 0x14
#define KEYP_SIR 0x15
#define KEYP_EDR 0x16 /* edge triggers */
#define KEYP_SIH_CTRL 0x17
/* KEYP_CTRL_REG Fields */
#define KEYP_CTRL_SOFT_NRST BIT(0)
#define KEYP_CTRL_SOFTMODEN BIT(1)
#define KEYP_CTRL_LK_EN BIT(2)
#define KEYP_CTRL_TOE_EN BIT(3)
#define KEYP_CTRL_TOLE_EN BIT(4)
#define KEYP_CTRL_RP_EN BIT(5)
#define KEYP_CTRL_KBD_ON BIT(6)
/* KEYP_DEB, KEYP_LONG_KEY, KEYP_TIMEOUT_x*/
#define KEYP_PERIOD_US(t, prescale) ((t) / (31 << ((prescale) + 1)) - 1)
/* KEYP_LK_PTV_REG Fields */
#define KEYP_LK_PTV_PTV_SHIFT 5
/* KEYP_{IMR,ISR,SIR} Fields */
#define KEYP_IMR1_MIS BIT(3)
#define KEYP_IMR1_TO BIT(2)
#define KEYP_IMR1_LK BIT(1)
#define KEYP_IMR1_KP BIT(0)
/* KEYP_EDR Fields */
#define KEYP_EDR_KP_FALLING 0x01
#define KEYP_EDR_KP_RISING 0x02
#define KEYP_EDR_KP_BOTH 0x03
#define KEYP_EDR_LK_FALLING 0x04
#define KEYP_EDR_LK_RISING 0x08
#define KEYP_EDR_TO_FALLING 0x10
#define KEYP_EDR_TO_RISING 0x20
#define KEYP_EDR_MIS_FALLING 0x40
#define KEYP_EDR_MIS_RISING 0x80
/*----------------------------------------------------------------------*/
static int twl4030_kpread(struct twl4030_keypad *kp,
u8 *data, u32 reg, u8 num_bytes)
{
int ret = twl_i2c_read(TWL4030_MODULE_KEYPAD, data, reg, num_bytes);
if (ret < 0)
dev_warn(kp->dbg_dev,
"Couldn't read TWL4030: %X - ret %d[%x]\n",
reg, ret, ret);
return ret;
}
static int twl4030_kpwrite_u8(struct twl4030_keypad *kp, u8 data, u32 reg)
{
int ret = twl_i2c_write_u8(TWL4030_MODULE_KEYPAD, data, reg);
if (ret < 0)
dev_warn(kp->dbg_dev,
"Could not write TWL4030: %X - ret %d[%x]\n",
reg, ret, ret);
return ret;
}
static inline u16 twl4030_col_xlate(struct twl4030_keypad *kp, u8 col)
{
/*
* If all bits in a row are active for all columns then
* we have that row line connected to gnd. Mark this
* key on as if it was on matrix position n_cols (i.e.
* one higher than the size of the matrix).
*/
if (col == 0xFF)
return 1 << kp->n_cols;
else
return col & ((1 << kp->n_cols) - 1);
}
static int twl4030_read_kp_matrix_state(struct twl4030_keypad *kp, u16 *state)
{
u8 new_state[TWL4030_MAX_ROWS];
int row;
int ret = twl4030_kpread(kp, new_state,
KEYP_FULL_CODE_7_0, kp->n_rows);
if (ret >= 0)
for (row = 0; row < kp->n_rows; row++)
state[row] = twl4030_col_xlate(kp, new_state[row]);
return ret;
}
static bool twl4030_is_in_ghost_state(struct twl4030_keypad *kp, u16 *key_state)
{
int i;
u16 check = 0;
for (i = 0; i < kp->n_rows; i++) {
u16 col = key_state[i];
if ((col & check) && hweight16(col) > 1)
return true;
check |= col;
}
return false;
}
static void twl4030_kp_scan(struct twl4030_keypad *kp, bool release_all)
{
struct input_dev *input = kp->input;
u16 new_state[TWL4030_MAX_ROWS];
int col, row;
if (release_all) {
memset(new_state, 0, sizeof(new_state));
} else {
/* check for any changes */
int ret = twl4030_read_kp_matrix_state(kp, new_state);
if (ret < 0) /* panic ... */
return;
if (twl4030_is_in_ghost_state(kp, new_state))
return;
}
/* check for changes and print those */
for (row = 0; row < kp->n_rows; row++) {
int changed = new_state[row] ^ kp->kp_state[row];
if (!changed)
continue;
/* Extra column handles "all gnd" rows */
for (col = 0; col < kp->n_cols + 1; col++) {
int code;
if (!(changed & (1 << col)))
continue;
dev_dbg(kp->dbg_dev, "key [%d:%d] %s\n", row, col,
(new_state[row] & (1 << col)) ?
"press" : "release");
code = MATRIX_SCAN_CODE(row, col, TWL4030_ROW_SHIFT);
input_event(input, EV_MSC, MSC_SCAN, code);
input_report_key(input, kp->keymap[code],
new_state[row] & (1 << col));
}
kp->kp_state[row] = new_state[row];
}
input_sync(input);
}
/*
* Keypad interrupt handler
*/
static irqreturn_t do_kp_irq(int irq, void *_kp)
{
struct twl4030_keypad *kp = _kp;
u8 reg;
int ret;
/* Read & Clear TWL4030 pending interrupt */
ret = twl4030_kpread(kp, ®, KEYP_ISR1, 1);
/*
* Release all keys if I2C has gone bad or
* the KEYP has gone to idle state.
*/
if (ret >= 0 && (reg & KEYP_IMR1_KP))
twl4030_kp_scan(kp, false);
else
twl4030_kp_scan(kp, true);
return IRQ_HANDLED;
}
static int twl4030_kp_program(struct twl4030_keypad *kp)
{
u8 reg;
int i;
/* Enable controller, with hardware decoding but not autorepeat */
reg = KEYP_CTRL_SOFT_NRST | KEYP_CTRL_SOFTMODEN
| KEYP_CTRL_TOE_EN | KEYP_CTRL_KBD_ON;
if (twl4030_kpwrite_u8(kp, reg, KEYP_CTRL) < 0)
return -EIO;
/*
* NOTE: we could use sih_setup() here to package keypad
* event sources as four different IRQs ... but we don't.
*/
/* Enable TO rising and KP rising and falling edge detection */
reg = KEYP_EDR_KP_BOTH | KEYP_EDR_TO_RISING;
if (twl4030_kpwrite_u8(kp, reg, KEYP_EDR) < 0)
return -EIO;
/* Set PTV prescaler Field */
reg = (PTV_PRESCALER << KEYP_LK_PTV_PTV_SHIFT);
if (twl4030_kpwrite_u8(kp, reg, KEYP_LK_PTV) < 0)
return -EIO;
/* Set key debounce time to 20 ms */
i = KEYP_PERIOD_US(20000, PTV_PRESCALER);
if (twl4030_kpwrite_u8(kp, i, KEYP_DEB) < 0)
return -EIO;
/* Set timeout period to 200 ms */
i = KEYP_PERIOD_US(200000, PTV_PRESCALER);
if (twl4030_kpwrite_u8(kp, (i & 0xFF), KEYP_TIMEOUT_L) < 0)
return -EIO;
if (twl4030_kpwrite_u8(kp, (i >> 8), KEYP_TIMEOUT_H) < 0)
return -EIO;
/*
* Enable Clear-on-Read; disable remembering events that fire
* after the IRQ but before our handler acks (reads) them.
*/
reg = TWL4030_SIH_CTRL_COR_MASK | TWL4030_SIH_CTRL_PENDDIS_MASK;
if (twl4030_kpwrite_u8(kp, reg, KEYP_SIH_CTRL) < 0)
return -EIO;
/* initialize key state; irqs update it from here on */
if (twl4030_read_kp_matrix_state(kp, kp->kp_state) < 0)
return -EIO;
return 0;
}
/*
* Registers keypad device with input subsystem
* and configures TWL4030 keypad registers
*/
static int twl4030_kp_probe(struct platform_device *pdev)
{
struct twl4030_keypad_data *pdata = dev_get_platdata(&pdev->dev);
const struct matrix_keymap_data *keymap_data = NULL;
struct twl4030_keypad *kp;
struct input_dev *input;
u8 reg;
int error;
kp = devm_kzalloc(&pdev->dev, sizeof(*kp), GFP_KERNEL);
if (!kp)
return -ENOMEM;
input = devm_input_allocate_device(&pdev->dev);
if (!input)
return -ENOMEM;
/* get the debug device */
kp->dbg_dev = &pdev->dev;
kp->input = input;
/* setup input device */
input->name = "TWL4030 Keypad";
input->phys = "twl4030_keypad/input0";
input->id.bustype = BUS_HOST;
input->id.vendor = 0x0001;
input->id.product = 0x0001;
input->id.version = 0x0003;
if (pdata) {
if (!pdata->rows || !pdata->cols || !pdata->keymap_data) {
dev_err(&pdev->dev, "Missing platform_data\n");
return -EINVAL;
}
kp->n_rows = pdata->rows;
kp->n_cols = pdata->cols;
kp->autorepeat = pdata->rep;
keymap_data = pdata->keymap_data;
} else {
error = matrix_keypad_parse_properties(&pdev->dev, &kp->n_rows,
&kp->n_cols);
if (error)
return error;
kp->autorepeat = true;
}
if (kp->n_rows > TWL4030_MAX_ROWS || kp->n_cols > TWL4030_MAX_COLS) {
dev_err(&pdev->dev,
"Invalid rows/cols amount specified in platform/devicetree data\n");
return -EINVAL;
}
kp->irq = platform_get_irq(pdev, 0);
if (kp->irq < 0)
return kp->irq;
error = matrix_keypad_build_keymap(keymap_data, NULL,
TWL4030_MAX_ROWS,
1 << TWL4030_ROW_SHIFT,
kp->keymap, input);
if (error) {
dev_err(kp->dbg_dev, "Failed to build keymap\n");
return error;
}
input_set_capability(input, EV_MSC, MSC_SCAN);
/* Enable auto repeat feature of Linux input subsystem */
if (kp->autorepeat)
__set_bit(EV_REP, input->evbit);
error = input_register_device(input);
if (error) {
dev_err(kp->dbg_dev,
"Unable to register twl4030 keypad device\n");
return error;
}
error = twl4030_kp_program(kp);
if (error)
return error;
/*
* This ISR will always execute in kernel thread context because of
* the need to access the TWL4030 over the I2C bus.
*
* NOTE: we assume this host is wired to TWL4040 INT1, not INT2 ...
*/
error = devm_request_threaded_irq(&pdev->dev, kp->irq, NULL, do_kp_irq,
0, pdev->name, kp);
if (error) {
dev_info(kp->dbg_dev, "request_irq failed for irq no=%d: %d\n",
kp->irq, error);
return error;
}
/* Enable KP and TO interrupts now. */
reg = (u8) ~(KEYP_IMR1_KP | KEYP_IMR1_TO);
if (twl4030_kpwrite_u8(kp, reg, KEYP_IMR1)) {
/* mask all events - we don't care about the result */
(void) twl4030_kpwrite_u8(kp, 0xff, KEYP_IMR1);
return -EIO;
}
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id twl4030_keypad_dt_match_table[] = {
{ .compatible = "ti,twl4030-keypad" },
{},
};
MODULE_DEVICE_TABLE(of, twl4030_keypad_dt_match_table);
#endif
/*
* NOTE: twl4030 are multi-function devices connected via I2C.
* So this device is a child of an I2C parent, thus it needs to
* support unplug/replug (which most platform devices don't).
*/
static struct platform_driver twl4030_kp_driver = {
.probe = twl4030_kp_probe,
.driver = {
.name = "twl4030_keypad",
.of_match_table = of_match_ptr(twl4030_keypad_dt_match_table),
},
};
module_platform_driver(twl4030_kp_driver);
MODULE_AUTHOR("Texas Instruments");
MODULE_DESCRIPTION("TWL4030 Keypad Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:twl4030_keypad");
|
linux-master
|
drivers/input/keyboard/twl4030_keypad.c
|
// SPDX-License-Identifier: GPL-2.0-only
/*
* TM2 touchkey device driver
*
* Copyright 2005 Phil Blundell
* Copyright 2016 Samsung Electronics Co., Ltd.
*
* Author: Beomho Seo <[email protected]>
* Author: Jaechul Lee <[email protected]>
*/
#include <linux/bitops.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/pm.h>
#include <linux/regulator/consumer.h>
#define TM2_TOUCHKEY_DEV_NAME "tm2-touchkey"
#define ARIES_TOUCHKEY_CMD_LED_ON 0x1
#define ARIES_TOUCHKEY_CMD_LED_OFF 0x2
#define TM2_TOUCHKEY_CMD_LED_ON 0x10
#define TM2_TOUCHKEY_CMD_LED_OFF 0x20
#define TM2_TOUCHKEY_BIT_PRESS_EV BIT(3)
#define TM2_TOUCHKEY_BIT_KEYCODE GENMASK(2, 0)
#define TM2_TOUCHKEY_LED_VOLTAGE_MIN 2500000
#define TM2_TOUCHKEY_LED_VOLTAGE_MAX 3300000
struct touchkey_variant {
u8 keycode_reg;
u8 base_reg;
u8 cmd_led_on;
u8 cmd_led_off;
bool no_reg;
bool fixed_regulator;
};
struct tm2_touchkey_data {
struct i2c_client *client;
struct input_dev *input_dev;
struct led_classdev led_dev;
struct regulator *vdd;
struct regulator_bulk_data regulators[3];
const struct touchkey_variant *variant;
u32 keycodes[4];
int num_keycodes;
};
static const struct touchkey_variant tm2_touchkey_variant = {
.keycode_reg = 0x03,
.base_reg = 0x00,
.cmd_led_on = TM2_TOUCHKEY_CMD_LED_ON,
.cmd_led_off = TM2_TOUCHKEY_CMD_LED_OFF,
};
static const struct touchkey_variant midas_touchkey_variant = {
.keycode_reg = 0x00,
.base_reg = 0x00,
.cmd_led_on = TM2_TOUCHKEY_CMD_LED_ON,
.cmd_led_off = TM2_TOUCHKEY_CMD_LED_OFF,
};
static struct touchkey_variant aries_touchkey_variant = {
.no_reg = true,
.fixed_regulator = true,
.cmd_led_on = ARIES_TOUCHKEY_CMD_LED_ON,
.cmd_led_off = ARIES_TOUCHKEY_CMD_LED_OFF,
};
static const struct touchkey_variant tc360_touchkey_variant = {
.keycode_reg = 0x00,
.base_reg = 0x00,
.fixed_regulator = true,
.cmd_led_on = TM2_TOUCHKEY_CMD_LED_ON,
.cmd_led_off = TM2_TOUCHKEY_CMD_LED_OFF,
};
static int tm2_touchkey_led_brightness_set(struct led_classdev *led_dev,
enum led_brightness brightness)
{
struct tm2_touchkey_data *touchkey =
container_of(led_dev, struct tm2_touchkey_data, led_dev);
u32 volt;
u8 data;
if (brightness == LED_OFF) {
volt = TM2_TOUCHKEY_LED_VOLTAGE_MIN;
data = touchkey->variant->cmd_led_off;
} else {
volt = TM2_TOUCHKEY_LED_VOLTAGE_MAX;
data = touchkey->variant->cmd_led_on;
}
if (!touchkey->variant->fixed_regulator)
regulator_set_voltage(touchkey->vdd, volt, volt);
return touchkey->variant->no_reg ?
i2c_smbus_write_byte(touchkey->client, data) :
i2c_smbus_write_byte_data(touchkey->client,
touchkey->variant->base_reg, data);
}
static int tm2_touchkey_power_enable(struct tm2_touchkey_data *touchkey)
{
int error;
error = regulator_bulk_enable(ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
if (error)
return error;
/* waiting for device initialization, at least 150ms */
msleep(150);
return 0;
}
static void tm2_touchkey_power_disable(void *data)
{
struct tm2_touchkey_data *touchkey = data;
regulator_bulk_disable(ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
}
static irqreturn_t tm2_touchkey_irq_handler(int irq, void *devid)
{
struct tm2_touchkey_data *touchkey = devid;
int data;
int index;
int i;
if (touchkey->variant->no_reg)
data = i2c_smbus_read_byte(touchkey->client);
else
data = i2c_smbus_read_byte_data(touchkey->client,
touchkey->variant->keycode_reg);
if (data < 0) {
dev_err(&touchkey->client->dev,
"failed to read i2c data: %d\n", data);
goto out;
}
index = (data & TM2_TOUCHKEY_BIT_KEYCODE) - 1;
if (index < 0 || index >= touchkey->num_keycodes) {
dev_warn(&touchkey->client->dev,
"invalid keycode index %d\n", index);
goto out;
}
input_event(touchkey->input_dev, EV_MSC, MSC_SCAN, index);
if (data & TM2_TOUCHKEY_BIT_PRESS_EV) {
for (i = 0; i < touchkey->num_keycodes; i++)
input_report_key(touchkey->input_dev,
touchkey->keycodes[i], 0);
} else {
input_report_key(touchkey->input_dev,
touchkey->keycodes[index], 1);
}
input_sync(touchkey->input_dev);
out:
if (touchkey->variant->fixed_regulator &&
data & TM2_TOUCHKEY_BIT_PRESS_EV) {
/* touch turns backlight on, so make sure we're in sync */
if (touchkey->led_dev.brightness == LED_OFF)
tm2_touchkey_led_brightness_set(&touchkey->led_dev,
LED_OFF);
}
return IRQ_HANDLED;
}
static int tm2_touchkey_probe(struct i2c_client *client)
{
struct device_node *np = client->dev.of_node;
struct tm2_touchkey_data *touchkey;
int error;
int i;
if (!i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_BYTE | I2C_FUNC_SMBUS_BYTE_DATA)) {
dev_err(&client->dev, "incompatible I2C adapter\n");
return -EIO;
}
touchkey = devm_kzalloc(&client->dev, sizeof(*touchkey), GFP_KERNEL);
if (!touchkey)
return -ENOMEM;
touchkey->client = client;
i2c_set_clientdata(client, touchkey);
touchkey->variant = of_device_get_match_data(&client->dev);
touchkey->regulators[0].supply = "vcc";
touchkey->regulators[1].supply = "vdd";
touchkey->regulators[2].supply = "vddio";
error = devm_regulator_bulk_get(&client->dev,
ARRAY_SIZE(touchkey->regulators),
touchkey->regulators);
if (error) {
dev_err(&client->dev, "failed to get regulators: %d\n", error);
return error;
}
/* Save VDD for easy access */
touchkey->vdd = touchkey->regulators[1].consumer;
touchkey->num_keycodes = of_property_read_variable_u32_array(np,
"linux,keycodes", touchkey->keycodes, 0,
ARRAY_SIZE(touchkey->keycodes));
if (touchkey->num_keycodes <= 0) {
/* default keycodes */
touchkey->keycodes[0] = KEY_PHONE;
touchkey->keycodes[1] = KEY_BACK;
touchkey->num_keycodes = 2;
}
error = tm2_touchkey_power_enable(touchkey);
if (error) {
dev_err(&client->dev, "failed to power up device: %d\n", error);
return error;
}
error = devm_add_action_or_reset(&client->dev,
tm2_touchkey_power_disable, touchkey);
if (error) {
dev_err(&client->dev,
"failed to install poweroff handler: %d\n", error);
return error;
}
/* input device */
touchkey->input_dev = devm_input_allocate_device(&client->dev);
if (!touchkey->input_dev) {
dev_err(&client->dev, "failed to allocate input device\n");
return -ENOMEM;
}
touchkey->input_dev->name = TM2_TOUCHKEY_DEV_NAME;
touchkey->input_dev->id.bustype = BUS_I2C;
touchkey->input_dev->keycode = touchkey->keycodes;
touchkey->input_dev->keycodemax = touchkey->num_keycodes;
touchkey->input_dev->keycodesize = sizeof(touchkey->keycodes[0]);
input_set_capability(touchkey->input_dev, EV_MSC, MSC_SCAN);
for (i = 0; i < touchkey->num_keycodes; i++)
input_set_capability(touchkey->input_dev, EV_KEY,
touchkey->keycodes[i]);
error = input_register_device(touchkey->input_dev);
if (error) {
dev_err(&client->dev,
"failed to register input device: %d\n", error);
return error;
}
error = devm_request_threaded_irq(&client->dev, client->irq,
NULL, tm2_touchkey_irq_handler,
IRQF_ONESHOT,
TM2_TOUCHKEY_DEV_NAME, touchkey);
if (error) {
dev_err(&client->dev,
"failed to request threaded irq: %d\n", error);
return error;
}
/* led device */
touchkey->led_dev.name = TM2_TOUCHKEY_DEV_NAME;
touchkey->led_dev.brightness = LED_ON;
touchkey->led_dev.max_brightness = LED_ON;
touchkey->led_dev.brightness_set_blocking =
tm2_touchkey_led_brightness_set;
error = devm_led_classdev_register(&client->dev, &touchkey->led_dev);
if (error) {
dev_err(&client->dev,
"failed to register touchkey led: %d\n", error);
return error;
}
if (touchkey->variant->fixed_regulator)
tm2_touchkey_led_brightness_set(&touchkey->led_dev, LED_ON);
return 0;
}
static int tm2_touchkey_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct tm2_touchkey_data *touchkey = i2c_get_clientdata(client);
disable_irq(client->irq);
tm2_touchkey_power_disable(touchkey);
return 0;
}
static int tm2_touchkey_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct tm2_touchkey_data *touchkey = i2c_get_clientdata(client);
int ret;
enable_irq(client->irq);
ret = tm2_touchkey_power_enable(touchkey);
if (ret)
dev_err(dev, "failed to enable power: %d\n", ret);
return ret;
}
static DEFINE_SIMPLE_DEV_PM_OPS(tm2_touchkey_pm_ops,
tm2_touchkey_suspend, tm2_touchkey_resume);
static const struct i2c_device_id tm2_touchkey_id_table[] = {
{ TM2_TOUCHKEY_DEV_NAME, 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, tm2_touchkey_id_table);
static const struct of_device_id tm2_touchkey_of_match[] = {
{
.compatible = "cypress,tm2-touchkey",
.data = &tm2_touchkey_variant,
}, {
.compatible = "cypress,midas-touchkey",
.data = &midas_touchkey_variant,
}, {
.compatible = "cypress,aries-touchkey",
.data = &aries_touchkey_variant,
}, {
.compatible = "coreriver,tc360-touchkey",
.data = &tc360_touchkey_variant,
},
{ },
};
MODULE_DEVICE_TABLE(of, tm2_touchkey_of_match);
static struct i2c_driver tm2_touchkey_driver = {
.driver = {
.name = TM2_TOUCHKEY_DEV_NAME,
.pm = pm_sleep_ptr(&tm2_touchkey_pm_ops),
.of_match_table = tm2_touchkey_of_match,
},
.probe = tm2_touchkey_probe,
.id_table = tm2_touchkey_id_table,
};
module_i2c_driver(tm2_touchkey_driver);
MODULE_AUTHOR("Beomho Seo <[email protected]>");
MODULE_AUTHOR("Jaechul Lee <[email protected]>");
MODULE_DESCRIPTION("Samsung touchkey driver");
MODULE_LICENSE("GPL v2");
|
linux-master
|
drivers/input/keyboard/tm2-touchkey.c
|
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* Atmel AT42QT1070 QTouch Sensor Controller
*
* Copyright (C) 2011 Atmel
*
* Authors: Bo Shen <[email protected]>
*
* Base on AT42QT2160 driver by:
* Raphael Derosso Pereira <[email protected]>
* Copyright (C) 2009
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
/* Address for each register */
#define CHIP_ID 0x00
#define QT1070_CHIP_ID 0x2E
#define FW_VERSION 0x01
#define QT1070_FW_VERSION 0x15
#define DET_STATUS 0x02
#define KEY_STATUS 0x03
/* Calibrate */
#define CALIBRATE_CMD 0x38
#define QT1070_CAL_TIME 200
/* Reset */
#define RESET 0x39
#define QT1070_RESET_TIME 255
/* AT42QT1070 support up to 7 keys */
static const unsigned short qt1070_key2code[] = {
KEY_0, KEY_1, KEY_2, KEY_3,
KEY_4, KEY_5, KEY_6,
};
struct qt1070_data {
struct i2c_client *client;
struct input_dev *input;
unsigned int irq;
unsigned short keycodes[ARRAY_SIZE(qt1070_key2code)];
u8 last_keys;
};
static int qt1070_read(struct i2c_client *client, u8 reg)
{
int ret;
ret = i2c_smbus_read_byte_data(client, reg);
if (ret < 0)
dev_err(&client->dev,
"can not read register, returned %d\n", ret);
return ret;
}
static int qt1070_write(struct i2c_client *client, u8 reg, u8 data)
{
int ret;
ret = i2c_smbus_write_byte_data(client, reg, data);
if (ret < 0)
dev_err(&client->dev,
"can not write register, returned %d\n", ret);
return ret;
}
static bool qt1070_identify(struct i2c_client *client)
{
int id, ver;
/* Read Chip ID */
id = qt1070_read(client, CHIP_ID);
if (id != QT1070_CHIP_ID) {
dev_err(&client->dev, "ID %d not supported\n", id);
return false;
}
/* Read firmware version */
ver = qt1070_read(client, FW_VERSION);
if (ver < 0) {
dev_err(&client->dev, "could not read the firmware version\n");
return false;
}
dev_info(&client->dev, "AT42QT1070 firmware version %x\n", ver);
return true;
}
static irqreturn_t qt1070_interrupt(int irq, void *dev_id)
{
struct qt1070_data *data = dev_id;
struct i2c_client *client = data->client;
struct input_dev *input = data->input;
int i;
u8 new_keys, keyval, mask = 0x01;
/* Read the detected status register, thus clearing interrupt */
qt1070_read(client, DET_STATUS);
/* Read which key changed */
new_keys = qt1070_read(client, KEY_STATUS);
for (i = 0; i < ARRAY_SIZE(qt1070_key2code); i++) {
keyval = new_keys & mask;
if ((data->last_keys & mask) != keyval)
input_report_key(input, data->keycodes[i], keyval);
mask <<= 1;
}
input_sync(input);
data->last_keys = new_keys;
return IRQ_HANDLED;
}
static int qt1070_probe(struct i2c_client *client)
{
struct qt1070_data *data;
struct input_dev *input;
int i;
int err;
err = i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE);
if (!err) {
dev_err(&client->dev, "%s adapter not supported\n",
dev_driver_string(&client->adapter->dev));
return -ENODEV;
}
if (!client->irq) {
dev_err(&client->dev, "please assign the irq to this device\n");
return -EINVAL;
}
/* Identify the qt1070 chip */
if (!qt1070_identify(client))
return -ENODEV;
data = devm_kzalloc(&client->dev, sizeof(struct qt1070_data),
GFP_KERNEL);
if (!data)
return -ENOMEM;
input = devm_input_allocate_device(&client->dev);
if (!input)
return -ENOMEM;
data->client = client;
data->input = input;
data->irq = client->irq;
input->name = "AT42QT1070 QTouch Sensor";
input->id.bustype = BUS_I2C;
/* Add the keycode */
input->keycode = data->keycodes;
input->keycodesize = sizeof(data->keycodes[0]);
input->keycodemax = ARRAY_SIZE(qt1070_key2code);
__set_bit(EV_KEY, input->evbit);
for (i = 0; i < ARRAY_SIZE(qt1070_key2code); i++) {
data->keycodes[i] = qt1070_key2code[i];
__set_bit(qt1070_key2code[i], input->keybit);
}
/* Calibrate device */
qt1070_write(client, CALIBRATE_CMD, 1);
msleep(QT1070_CAL_TIME);
/* Soft reset */
qt1070_write(client, RESET, 1);
msleep(QT1070_RESET_TIME);
err = devm_request_threaded_irq(&client->dev, client->irq,
NULL, qt1070_interrupt,
IRQF_TRIGGER_NONE | IRQF_ONESHOT,
client->dev.driver->name, data);
if (err) {
dev_err(&client->dev, "fail to request irq\n");
return err;
}
/* Register the input device */
err = input_register_device(data->input);
if (err) {
dev_err(&client->dev, "Failed to register input device\n");
return err;
}
i2c_set_clientdata(client, data);
/* Read to clear the chang line */
qt1070_read(client, DET_STATUS);
return 0;
}
static int qt1070_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct qt1070_data *data = i2c_get_clientdata(client);
if (device_may_wakeup(dev))
enable_irq_wake(data->irq);
return 0;
}
static int qt1070_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct qt1070_data *data = i2c_get_clientdata(client);
if (device_may_wakeup(dev))
disable_irq_wake(data->irq);
return 0;
}
static DEFINE_SIMPLE_DEV_PM_OPS(qt1070_pm_ops, qt1070_suspend, qt1070_resume);
static const struct i2c_device_id qt1070_id[] = {
{ "qt1070", 0 },
{ },
};
MODULE_DEVICE_TABLE(i2c, qt1070_id);
#ifdef CONFIG_OF
static const struct of_device_id qt1070_of_match[] = {
{ .compatible = "qt1070", },
{ },
};
MODULE_DEVICE_TABLE(of, qt1070_of_match);
#endif
static struct i2c_driver qt1070_driver = {
.driver = {
.name = "qt1070",
.of_match_table = of_match_ptr(qt1070_of_match),
.pm = pm_sleep_ptr(&qt1070_pm_ops),
},
.id_table = qt1070_id,
.probe = qt1070_probe,
};
module_i2c_driver(qt1070_driver);
MODULE_AUTHOR("Bo Shen <[email protected]>");
MODULE_DESCRIPTION("Driver for AT42QT1070 QTouch sensor");
MODULE_LICENSE("GPL");
|
linux-master
|
drivers/input/keyboard/qt1070.c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.