Linux Audio

Check our new training course

Loading...
Note: File does not exist in v5.4.
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * MCP2221A - Microchip USB to I2C Host Protocol Bridge
   4 *
   5 * Copyright (c) 2020, Rishi Gupta <gupt21@gmail.com>
   6 *
   7 * Datasheet: https://ww1.microchip.com/downloads/en/DeviceDoc/20005565B.pdf
   8 */
   9
  10#include <linux/module.h>
  11#include <linux/err.h>
  12#include <linux/mutex.h>
  13#include <linux/bitfield.h>
  14#include <linux/completion.h>
  15#include <linux/delay.h>
  16#include <linux/hid.h>
  17#include <linux/hidraw.h>
  18#include <linux/i2c.h>
  19#include <linux/gpio/driver.h>
  20#include <linux/iio/iio.h>
  21#include "hid-ids.h"
  22
  23/* Commands codes in a raw output report */
  24enum {
  25	MCP2221_I2C_WR_DATA = 0x90,
  26	MCP2221_I2C_WR_NO_STOP = 0x94,
  27	MCP2221_I2C_RD_DATA = 0x91,
  28	MCP2221_I2C_RD_RPT_START = 0x93,
  29	MCP2221_I2C_GET_DATA = 0x40,
  30	MCP2221_I2C_PARAM_OR_STATUS	= 0x10,
  31	MCP2221_I2C_SET_SPEED = 0x20,
  32	MCP2221_I2C_CANCEL = 0x10,
  33	MCP2221_GPIO_SET = 0x50,
  34	MCP2221_GPIO_GET = 0x51,
  35	MCP2221_SET_SRAM_SETTINGS = 0x60,
  36	MCP2221_GET_SRAM_SETTINGS = 0x61,
  37	MCP2221_READ_FLASH_DATA = 0xb0,
  38};
  39
  40/* Response codes in a raw input report */
  41enum {
  42	MCP2221_SUCCESS = 0x00,
  43	MCP2221_I2C_ENG_BUSY = 0x01,
  44	MCP2221_I2C_START_TOUT = 0x12,
  45	MCP2221_I2C_STOP_TOUT = 0x62,
  46	MCP2221_I2C_WRADDRL_TOUT = 0x23,
  47	MCP2221_I2C_WRDATA_TOUT = 0x44,
  48	MCP2221_I2C_WRADDRL_NACK = 0x25,
  49	MCP2221_I2C_MASK_ADDR_NACK = 0x40,
  50	MCP2221_I2C_WRADDRL_SEND = 0x21,
  51	MCP2221_I2C_ADDR_NACK = 0x25,
  52	MCP2221_I2C_READ_PARTIAL = 0x54,
  53	MCP2221_I2C_READ_COMPL = 0x55,
  54	MCP2221_ALT_F_NOT_GPIOV = 0xEE,
  55	MCP2221_ALT_F_NOT_GPIOD = 0xEF,
  56};
  57
  58/* MCP GPIO direction encoding */
  59enum {
  60	MCP2221_DIR_OUT = 0x00,
  61	MCP2221_DIR_IN = 0x01,
  62};
  63
  64#define MCP_NGPIO	4
  65
  66/* MCP GPIO set command layout */
  67struct mcp_set_gpio {
  68	u8 cmd;
  69	u8 dummy;
  70	struct {
  71		u8 change_value;
  72		u8 value;
  73		u8 change_direction;
  74		u8 direction;
  75	} gpio[MCP_NGPIO];
  76} __packed;
  77
  78/* MCP GPIO get command layout */
  79struct mcp_get_gpio {
  80	u8 cmd;
  81	u8 dummy;
  82	struct {
  83		u8 value;
  84		u8 direction;
  85	} gpio[MCP_NGPIO];
  86} __packed;
  87
  88/*
  89 * There is no way to distinguish responses. Therefore next command
  90 * is sent only after response to previous has been received. Mutex
  91 * lock is used for this purpose mainly.
  92 */
  93struct mcp2221 {
  94	struct hid_device *hdev;
  95	struct i2c_adapter adapter;
  96	struct mutex lock;
  97	struct completion wait_in_report;
  98	struct delayed_work init_work;
  99	u8 *rxbuf;
 100	u8 txbuf[64];
 101	int rxbuf_idx;
 102	int status;
 103	u8 cur_i2c_clk_div;
 104	struct gpio_chip *gc;
 105	u8 gp_idx;
 106	u8 gpio_dir;
 107	u8 mode[4];
 108#if IS_REACHABLE(CONFIG_IIO)
 109	struct iio_chan_spec iio_channels[3];
 110	u16 adc_values[3];
 111	u8 adc_scale;
 112	u8 dac_value;
 113	u16 dac_scale;
 114#endif
 115};
 116
 117struct mcp2221_iio {
 118	struct mcp2221 *mcp;
 119};
 120
 121/*
 122 * Default i2c bus clock frequency 400 kHz. Modify this if you
 123 * want to set some other frequency (min 50 kHz - max 400 kHz).
 124 */
 125static uint i2c_clk_freq = 400;
 126
 127/* Synchronously send output report to the device */
 128static int mcp_send_report(struct mcp2221 *mcp,
 129					u8 *out_report, size_t len)
 130{
 131	u8 *buf;
 132	int ret;
 133
 134	buf = kmemdup(out_report, len, GFP_KERNEL);
 135	if (!buf)
 136		return -ENOMEM;
 137
 138	/* mcp2221 uses interrupt endpoint for out reports */
 139	ret = hid_hw_output_report(mcp->hdev, buf, len);
 140	kfree(buf);
 141
 142	if (ret < 0)
 143		return ret;
 144	return 0;
 145}
 146
 147/*
 148 * Send o/p report to the device and wait for i/p report to be
 149 * received from the device. If the device does not respond,
 150 * we timeout.
 151 */
 152static int mcp_send_data_req_status(struct mcp2221 *mcp,
 153			u8 *out_report, int len)
 154{
 155	int ret;
 156	unsigned long t;
 157
 158	reinit_completion(&mcp->wait_in_report);
 159
 160	ret = mcp_send_report(mcp, out_report, len);
 161	if (ret)
 162		return ret;
 163
 164	t = wait_for_completion_timeout(&mcp->wait_in_report,
 165							msecs_to_jiffies(4000));
 166	if (!t)
 167		return -ETIMEDOUT;
 168
 169	return mcp->status;
 170}
 171
 172/* Check pass/fail for actual communication with i2c slave */
 173static int mcp_chk_last_cmd_status(struct mcp2221 *mcp)
 174{
 175	memset(mcp->txbuf, 0, 8);
 176	mcp->txbuf[0] = MCP2221_I2C_PARAM_OR_STATUS;
 177
 178	return mcp_send_data_req_status(mcp, mcp->txbuf, 8);
 179}
 180
 181/* Cancels last command releasing i2c bus just in case occupied */
 182static int mcp_cancel_last_cmd(struct mcp2221 *mcp)
 183{
 184	memset(mcp->txbuf, 0, 8);
 185	mcp->txbuf[0] = MCP2221_I2C_PARAM_OR_STATUS;
 186	mcp->txbuf[2] = MCP2221_I2C_CANCEL;
 187
 188	return mcp_send_data_req_status(mcp, mcp->txbuf, 8);
 189}
 190
 191/* Check if the last command succeeded or failed and return the result.
 192 * If the command did fail, cancel that command which will free the i2c bus.
 193 */
 194static int mcp_chk_last_cmd_status_free_bus(struct mcp2221 *mcp)
 195{
 196	int ret;
 197
 198	ret = mcp_chk_last_cmd_status(mcp);
 199	if (ret) {
 200		/* The last command was a failure.
 201		 * Send a cancel which will also free the bus.
 202		 */
 203		usleep_range(980, 1000);
 204		mcp_cancel_last_cmd(mcp);
 205	}
 206
 207	return ret;
 208}
 209
 210static int mcp_set_i2c_speed(struct mcp2221 *mcp)
 211{
 212	int ret;
 213
 214	memset(mcp->txbuf, 0, 8);
 215	mcp->txbuf[0] = MCP2221_I2C_PARAM_OR_STATUS;
 216	mcp->txbuf[3] = MCP2221_I2C_SET_SPEED;
 217	mcp->txbuf[4] = mcp->cur_i2c_clk_div;
 218
 219	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 8);
 220	if (ret) {
 221		/* Small delay is needed here */
 222		usleep_range(980, 1000);
 223		mcp_cancel_last_cmd(mcp);
 224	}
 225
 226	return 0;
 227}
 228
 229/*
 230 * An output report can contain minimum 1 and maximum 60 user data
 231 * bytes. If the number of data bytes is more then 60, we send it
 232 * in chunks of 60 bytes. Last chunk may contain exactly 60 or less
 233 * bytes. Total number of bytes is informed in very first report to
 234 * mcp2221, from that point onwards it first collect all the data
 235 * from host and then send to i2c slave device.
 236 */
 237static int mcp_i2c_write(struct mcp2221 *mcp,
 238				struct i2c_msg *msg, int type, u8 last_status)
 239{
 240	int ret, len, idx, sent;
 241
 242	idx = 0;
 243	sent  = 0;
 244	if (msg->len < 60)
 245		len = msg->len;
 246	else
 247		len = 60;
 248
 249	do {
 250		mcp->txbuf[0] = type;
 251		mcp->txbuf[1] = msg->len & 0xff;
 252		mcp->txbuf[2] = msg->len >> 8;
 253		mcp->txbuf[3] = (u8)(msg->addr << 1);
 254
 255		memcpy(&mcp->txbuf[4], &msg->buf[idx], len);
 256
 257		ret = mcp_send_data_req_status(mcp, mcp->txbuf, len + 4);
 258		if (ret)
 259			return ret;
 260
 261		usleep_range(980, 1000);
 262
 263		if (last_status) {
 264			ret = mcp_chk_last_cmd_status_free_bus(mcp);
 265			if (ret)
 266				return ret;
 267		}
 268
 269		sent = sent + len;
 270		if (sent >= msg->len)
 271			break;
 272
 273		idx = idx + len;
 274		if ((msg->len - sent) < 60)
 275			len = msg->len - sent;
 276		else
 277			len = 60;
 278
 279		/*
 280		 * Testing shows delay is needed between successive writes
 281		 * otherwise next write fails on first-try from i2c core.
 282		 * This value is obtained through automated stress testing.
 283		 */
 284		usleep_range(980, 1000);
 285	} while (len > 0);
 286
 287	return ret;
 288}
 289
 290/*
 291 * Device reads all data (0 - 65535 bytes) from i2c slave device and
 292 * stores it in device itself. This data is read back from device to
 293 * host in multiples of 60 bytes using input reports.
 294 */
 295static int mcp_i2c_smbus_read(struct mcp2221 *mcp,
 296				struct i2c_msg *msg, int type, u16 smbus_addr,
 297				u8 smbus_len, u8 *smbus_buf)
 298{
 299	int ret;
 300	u16 total_len;
 301	int retries = 0;
 302
 303	mcp->txbuf[0] = type;
 304	if (msg) {
 305		mcp->txbuf[1] = msg->len & 0xff;
 306		mcp->txbuf[2] = msg->len >> 8;
 307		mcp->txbuf[3] = (u8)(msg->addr << 1);
 308		total_len = msg->len;
 309		mcp->rxbuf = msg->buf;
 310	} else {
 311		mcp->txbuf[1] = smbus_len;
 312		mcp->txbuf[2] = 0;
 313		mcp->txbuf[3] = (u8)(smbus_addr << 1);
 314		total_len = smbus_len;
 315		mcp->rxbuf = smbus_buf;
 316	}
 317
 318	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 4);
 319	if (ret)
 320		return ret;
 321
 322	mcp->rxbuf_idx = 0;
 323
 324	do {
 325		/* Wait for the data to be read by the device */
 326		usleep_range(980, 1000);
 327
 328		memset(mcp->txbuf, 0, 4);
 329		mcp->txbuf[0] = MCP2221_I2C_GET_DATA;
 330
 331		ret = mcp_send_data_req_status(mcp, mcp->txbuf, 1);
 332		if (ret) {
 333			if (retries < 5) {
 334				/* The data wasn't ready to read.
 335				 * Wait a bit longer and try again.
 336				 */
 337				usleep_range(90, 100);
 338				retries++;
 339			} else {
 340				return ret;
 341			}
 342		} else {
 343			retries = 0;
 344		}
 345	} while (mcp->rxbuf_idx < total_len);
 346
 347	usleep_range(980, 1000);
 348	ret = mcp_chk_last_cmd_status_free_bus(mcp);
 349
 350	return ret;
 351}
 352
 353static int mcp_i2c_xfer(struct i2c_adapter *adapter,
 354				struct i2c_msg msgs[], int num)
 355{
 356	int ret;
 357	struct mcp2221 *mcp = i2c_get_adapdata(adapter);
 358
 359	hid_hw_power(mcp->hdev, PM_HINT_FULLON);
 360
 361	mutex_lock(&mcp->lock);
 362
 363	if (num == 1) {
 364		if (msgs->flags & I2C_M_RD) {
 365			ret = mcp_i2c_smbus_read(mcp, msgs, MCP2221_I2C_RD_DATA,
 366							0, 0, NULL);
 367		} else {
 368			ret = mcp_i2c_write(mcp, msgs, MCP2221_I2C_WR_DATA, 1);
 369		}
 370		if (ret)
 371			goto exit;
 372		ret = num;
 373	} else if (num == 2) {
 374		/* Ex transaction; send reg address and read its contents */
 375		if (msgs[0].addr == msgs[1].addr &&
 376			!(msgs[0].flags & I2C_M_RD) &&
 377			 (msgs[1].flags & I2C_M_RD)) {
 378
 379			ret = mcp_i2c_write(mcp, &msgs[0],
 380						MCP2221_I2C_WR_NO_STOP, 0);
 381			if (ret)
 382				goto exit;
 383
 384			ret = mcp_i2c_smbus_read(mcp, &msgs[1],
 385						MCP2221_I2C_RD_RPT_START,
 386						0, 0, NULL);
 387			if (ret)
 388				goto exit;
 389			ret = num;
 390		} else {
 391			dev_err(&adapter->dev,
 392				"unsupported multi-msg i2c transaction\n");
 393			ret = -EOPNOTSUPP;
 394		}
 395	} else {
 396		dev_err(&adapter->dev,
 397			"unsupported multi-msg i2c transaction\n");
 398		ret = -EOPNOTSUPP;
 399	}
 400
 401exit:
 402	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
 403	mutex_unlock(&mcp->lock);
 404	return ret;
 405}
 406
 407static int mcp_smbus_write(struct mcp2221 *mcp, u16 addr,
 408				u8 command, u8 *buf, u8 len, int type,
 409				u8 last_status)
 410{
 411	int data_len, ret;
 412
 413	mcp->txbuf[0] = type;
 414	mcp->txbuf[1] = len + 1; /* 1 is due to command byte itself */
 415	mcp->txbuf[2] = 0;
 416	mcp->txbuf[3] = (u8)(addr << 1);
 417	mcp->txbuf[4] = command;
 418
 419	switch (len) {
 420	case 0:
 421		data_len = 5;
 422		break;
 423	case 1:
 424		mcp->txbuf[5] = buf[0];
 425		data_len = 6;
 426		break;
 427	case 2:
 428		mcp->txbuf[5] = buf[0];
 429		mcp->txbuf[6] = buf[1];
 430		data_len = 7;
 431		break;
 432	default:
 433		if (len > I2C_SMBUS_BLOCK_MAX)
 434			return -EINVAL;
 435
 436		memcpy(&mcp->txbuf[5], buf, len);
 437		data_len = len + 5;
 438	}
 439
 440	ret = mcp_send_data_req_status(mcp, mcp->txbuf, data_len);
 441	if (ret)
 442		return ret;
 443
 444	if (last_status) {
 445		usleep_range(980, 1000);
 446
 447		ret = mcp_chk_last_cmd_status_free_bus(mcp);
 448	}
 449
 450	return ret;
 451}
 452
 453static int mcp_smbus_xfer(struct i2c_adapter *adapter, u16 addr,
 454				unsigned short flags, char read_write,
 455				u8 command, int size,
 456				union i2c_smbus_data *data)
 457{
 458	int ret;
 459	struct mcp2221 *mcp = i2c_get_adapdata(adapter);
 460
 461	hid_hw_power(mcp->hdev, PM_HINT_FULLON);
 462
 463	mutex_lock(&mcp->lock);
 464
 465	switch (size) {
 466
 467	case I2C_SMBUS_QUICK:
 468		if (read_write == I2C_SMBUS_READ)
 469			ret = mcp_i2c_smbus_read(mcp, NULL, MCP2221_I2C_RD_DATA,
 470						addr, 0, &data->byte);
 471		else
 472			ret = mcp_smbus_write(mcp, addr, command, NULL,
 473						0, MCP2221_I2C_WR_DATA, 1);
 474		break;
 475	case I2C_SMBUS_BYTE:
 476		if (read_write == I2C_SMBUS_READ)
 477			ret = mcp_i2c_smbus_read(mcp, NULL, MCP2221_I2C_RD_DATA,
 478						addr, 1, &data->byte);
 479		else
 480			ret = mcp_smbus_write(mcp, addr, command, NULL,
 481						0, MCP2221_I2C_WR_DATA, 1);
 482		break;
 483	case I2C_SMBUS_BYTE_DATA:
 484		if (read_write == I2C_SMBUS_READ) {
 485			ret = mcp_smbus_write(mcp, addr, command, NULL,
 486						0, MCP2221_I2C_WR_NO_STOP, 0);
 487			if (ret)
 488				goto exit;
 489
 490			ret = mcp_i2c_smbus_read(mcp, NULL,
 491						MCP2221_I2C_RD_RPT_START,
 492						addr, 1, &data->byte);
 493		} else {
 494			ret = mcp_smbus_write(mcp, addr, command, &data->byte,
 495						1, MCP2221_I2C_WR_DATA, 1);
 496		}
 497		break;
 498	case I2C_SMBUS_WORD_DATA:
 499		if (read_write == I2C_SMBUS_READ) {
 500			ret = mcp_smbus_write(mcp, addr, command, NULL,
 501						0, MCP2221_I2C_WR_NO_STOP, 0);
 502			if (ret)
 503				goto exit;
 504
 505			ret = mcp_i2c_smbus_read(mcp, NULL,
 506						MCP2221_I2C_RD_RPT_START,
 507						addr, 2, (u8 *)&data->word);
 508		} else {
 509			ret = mcp_smbus_write(mcp, addr, command,
 510						(u8 *)&data->word, 2,
 511						MCP2221_I2C_WR_DATA, 1);
 512		}
 513		break;
 514	case I2C_SMBUS_BLOCK_DATA:
 515		if (read_write == I2C_SMBUS_READ) {
 516			ret = mcp_smbus_write(mcp, addr, command, NULL,
 517						0, MCP2221_I2C_WR_NO_STOP, 1);
 518			if (ret)
 519				goto exit;
 520
 521			mcp->rxbuf_idx = 0;
 522			mcp->rxbuf = data->block;
 523			mcp->txbuf[0] = MCP2221_I2C_GET_DATA;
 524			ret = mcp_send_data_req_status(mcp, mcp->txbuf, 1);
 525			if (ret)
 526				goto exit;
 527		} else {
 528			if (!data->block[0]) {
 529				ret = -EINVAL;
 530				goto exit;
 531			}
 532			ret = mcp_smbus_write(mcp, addr, command, data->block,
 533						data->block[0] + 1,
 534						MCP2221_I2C_WR_DATA, 1);
 535		}
 536		break;
 537	case I2C_SMBUS_I2C_BLOCK_DATA:
 538		if (read_write == I2C_SMBUS_READ) {
 539			ret = mcp_smbus_write(mcp, addr, command, NULL,
 540						0, MCP2221_I2C_WR_NO_STOP, 1);
 541			if (ret)
 542				goto exit;
 543
 544			mcp->rxbuf_idx = 0;
 545			mcp->rxbuf = data->block;
 546			mcp->txbuf[0] = MCP2221_I2C_GET_DATA;
 547			ret = mcp_send_data_req_status(mcp, mcp->txbuf, 1);
 548			if (ret)
 549				goto exit;
 550		} else {
 551			if (!data->block[0]) {
 552				ret = -EINVAL;
 553				goto exit;
 554			}
 555			ret = mcp_smbus_write(mcp, addr, command,
 556						&data->block[1], data->block[0],
 557						MCP2221_I2C_WR_DATA, 1);
 558		}
 559		break;
 560	case I2C_SMBUS_PROC_CALL:
 561		ret = mcp_smbus_write(mcp, addr, command,
 562						(u8 *)&data->word,
 563						2, MCP2221_I2C_WR_NO_STOP, 0);
 564		if (ret)
 565			goto exit;
 566
 567		ret = mcp_i2c_smbus_read(mcp, NULL,
 568						MCP2221_I2C_RD_RPT_START,
 569						addr, 2, (u8 *)&data->word);
 570		break;
 571	case I2C_SMBUS_BLOCK_PROC_CALL:
 572		ret = mcp_smbus_write(mcp, addr, command, data->block,
 573						data->block[0] + 1,
 574						MCP2221_I2C_WR_NO_STOP, 0);
 575		if (ret)
 576			goto exit;
 577
 578		ret = mcp_i2c_smbus_read(mcp, NULL,
 579						MCP2221_I2C_RD_RPT_START,
 580						addr, I2C_SMBUS_BLOCK_MAX,
 581						data->block);
 582		break;
 583	default:
 584		dev_err(&mcp->adapter.dev,
 585			"unsupported smbus transaction size:%d\n", size);
 586		ret = -EOPNOTSUPP;
 587	}
 588
 589exit:
 590	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
 591	mutex_unlock(&mcp->lock);
 592	return ret;
 593}
 594
 595static u32 mcp_i2c_func(struct i2c_adapter *adapter)
 596{
 597	return I2C_FUNC_I2C |
 598			I2C_FUNC_SMBUS_READ_BLOCK_DATA |
 599			I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
 600			(I2C_FUNC_SMBUS_EMUL & ~I2C_FUNC_SMBUS_PEC);
 601}
 602
 603static const struct i2c_algorithm mcp_i2c_algo = {
 604	.master_xfer = mcp_i2c_xfer,
 605	.smbus_xfer = mcp_smbus_xfer,
 606	.functionality = mcp_i2c_func,
 607};
 608
 609#if IS_REACHABLE(CONFIG_GPIOLIB)
 610static int mcp_gpio_get(struct gpio_chip *gc,
 611				unsigned int offset)
 612{
 613	int ret;
 614	struct mcp2221 *mcp = gpiochip_get_data(gc);
 615
 616	mcp->txbuf[0] = MCP2221_GPIO_GET;
 617
 618	mcp->gp_idx = offsetof(struct mcp_get_gpio, gpio[offset]);
 619
 620	mutex_lock(&mcp->lock);
 621	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 1);
 622	mutex_unlock(&mcp->lock);
 623
 624	return ret;
 625}
 626
 627static void mcp_gpio_set(struct gpio_chip *gc,
 628				unsigned int offset, int value)
 629{
 630	struct mcp2221 *mcp = gpiochip_get_data(gc);
 631
 632	memset(mcp->txbuf, 0, 18);
 633	mcp->txbuf[0] = MCP2221_GPIO_SET;
 634
 635	mcp->gp_idx = offsetof(struct mcp_set_gpio, gpio[offset].value);
 636
 637	mcp->txbuf[mcp->gp_idx - 1] = 1;
 638	mcp->txbuf[mcp->gp_idx] = !!value;
 639
 640	mutex_lock(&mcp->lock);
 641	mcp_send_data_req_status(mcp, mcp->txbuf, 18);
 642	mutex_unlock(&mcp->lock);
 643}
 644
 645static int mcp_gpio_dir_set(struct mcp2221 *mcp,
 646				unsigned int offset, u8 val)
 647{
 648	memset(mcp->txbuf, 0, 18);
 649	mcp->txbuf[0] = MCP2221_GPIO_SET;
 650
 651	mcp->gp_idx = offsetof(struct mcp_set_gpio, gpio[offset].direction);
 652
 653	mcp->txbuf[mcp->gp_idx - 1] = 1;
 654	mcp->txbuf[mcp->gp_idx] = val;
 655
 656	return mcp_send_data_req_status(mcp, mcp->txbuf, 18);
 657}
 658
 659static int mcp_gpio_direction_input(struct gpio_chip *gc,
 660				unsigned int offset)
 661{
 662	int ret;
 663	struct mcp2221 *mcp = gpiochip_get_data(gc);
 664
 665	mutex_lock(&mcp->lock);
 666	ret = mcp_gpio_dir_set(mcp, offset, MCP2221_DIR_IN);
 667	mutex_unlock(&mcp->lock);
 668
 669	return ret;
 670}
 671
 672static int mcp_gpio_direction_output(struct gpio_chip *gc,
 673				unsigned int offset, int value)
 674{
 675	int ret;
 676	struct mcp2221 *mcp = gpiochip_get_data(gc);
 677
 678	mutex_lock(&mcp->lock);
 679	ret = mcp_gpio_dir_set(mcp, offset, MCP2221_DIR_OUT);
 680	mutex_unlock(&mcp->lock);
 681
 682	/* Can't configure as output, bailout early */
 683	if (ret)
 684		return ret;
 685
 686	mcp_gpio_set(gc, offset, value);
 687
 688	return 0;
 689}
 690
 691static int mcp_gpio_get_direction(struct gpio_chip *gc,
 692				unsigned int offset)
 693{
 694	int ret;
 695	struct mcp2221 *mcp = gpiochip_get_data(gc);
 696
 697	mcp->txbuf[0] = MCP2221_GPIO_GET;
 698
 699	mcp->gp_idx = offsetof(struct mcp_get_gpio, gpio[offset]);
 700
 701	mutex_lock(&mcp->lock);
 702	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 1);
 703	mutex_unlock(&mcp->lock);
 704
 705	if (ret)
 706		return ret;
 707
 708	if (mcp->gpio_dir == MCP2221_DIR_IN)
 709		return GPIO_LINE_DIRECTION_IN;
 710
 711	return GPIO_LINE_DIRECTION_OUT;
 712}
 713#endif
 714
 715/* Gives current state of i2c engine inside mcp2221 */
 716static int mcp_get_i2c_eng_state(struct mcp2221 *mcp,
 717				u8 *data, u8 idx)
 718{
 719	int ret;
 720
 721	switch (data[idx]) {
 722	case MCP2221_I2C_WRADDRL_NACK:
 723	case MCP2221_I2C_WRADDRL_SEND:
 724		ret = -ENXIO;
 725		break;
 726	case MCP2221_I2C_START_TOUT:
 727	case MCP2221_I2C_STOP_TOUT:
 728	case MCP2221_I2C_WRADDRL_TOUT:
 729	case MCP2221_I2C_WRDATA_TOUT:
 730		ret = -ETIMEDOUT;
 731		break;
 732	case MCP2221_I2C_ENG_BUSY:
 733		ret = -EAGAIN;
 734		break;
 735	case MCP2221_SUCCESS:
 736		ret = 0x00;
 737		break;
 738	default:
 739		ret = -EIO;
 740	}
 741
 742	return ret;
 743}
 744
 745/*
 746 * MCP2221 uses interrupt endpoint for input reports. This function
 747 * is called by HID layer when it receives i/p report from mcp2221,
 748 * which is actually a response to the previously sent command.
 749 *
 750 * MCP2221A firmware specific return codes are parsed and 0 or
 751 * appropriate negative error code is returned. Delayed response
 752 * results in timeout error and stray reponses results in -EIO.
 753 */
 754static int mcp2221_raw_event(struct hid_device *hdev,
 755				struct hid_report *report, u8 *data, int size)
 756{
 757	u8 *buf;
 758	struct mcp2221 *mcp = hid_get_drvdata(hdev);
 759
 760	switch (data[0]) {
 761
 762	case MCP2221_I2C_WR_DATA:
 763	case MCP2221_I2C_WR_NO_STOP:
 764	case MCP2221_I2C_RD_DATA:
 765	case MCP2221_I2C_RD_RPT_START:
 766		switch (data[1]) {
 767		case MCP2221_SUCCESS:
 768			mcp->status = 0;
 769			break;
 770		default:
 771			mcp->status = mcp_get_i2c_eng_state(mcp, data, 2);
 772		}
 773		complete(&mcp->wait_in_report);
 774		break;
 775
 776	case MCP2221_I2C_PARAM_OR_STATUS:
 777		switch (data[1]) {
 778		case MCP2221_SUCCESS:
 779			if ((mcp->txbuf[3] == MCP2221_I2C_SET_SPEED) &&
 780				(data[3] != MCP2221_I2C_SET_SPEED)) {
 781				mcp->status = -EAGAIN;
 782				break;
 783			}
 784			if (data[20] & MCP2221_I2C_MASK_ADDR_NACK) {
 785				mcp->status = -ENXIO;
 786				break;
 787			}
 788			mcp->status = mcp_get_i2c_eng_state(mcp, data, 8);
 789#if IS_REACHABLE(CONFIG_IIO)
 790			memcpy(&mcp->adc_values, &data[50], sizeof(mcp->adc_values));
 791#endif
 792			break;
 793		default:
 794			mcp->status = -EIO;
 795		}
 796		complete(&mcp->wait_in_report);
 797		break;
 798
 799	case MCP2221_I2C_GET_DATA:
 800		switch (data[1]) {
 801		case MCP2221_SUCCESS:
 802			if (data[2] == MCP2221_I2C_ADDR_NACK) {
 803				mcp->status = -ENXIO;
 804				break;
 805			}
 806			if (!mcp_get_i2c_eng_state(mcp, data, 2)
 807				&& (data[3] == 0)) {
 808				mcp->status = 0;
 809				break;
 810			}
 811			if (data[3] == 127) {
 812				mcp->status = -EIO;
 813				break;
 814			}
 815			if (data[2] == MCP2221_I2C_READ_COMPL ||
 816			    data[2] == MCP2221_I2C_READ_PARTIAL) {
 817				buf = mcp->rxbuf;
 818				memcpy(&buf[mcp->rxbuf_idx], &data[4], data[3]);
 819				mcp->rxbuf_idx = mcp->rxbuf_idx + data[3];
 820				mcp->status = 0;
 821				break;
 822			}
 823			mcp->status = -EIO;
 824			break;
 825		default:
 826			mcp->status = -EIO;
 827		}
 828		complete(&mcp->wait_in_report);
 829		break;
 830
 831	case MCP2221_GPIO_GET:
 832		switch (data[1]) {
 833		case MCP2221_SUCCESS:
 834			if ((data[mcp->gp_idx] == MCP2221_ALT_F_NOT_GPIOV) ||
 835				(data[mcp->gp_idx + 1] == MCP2221_ALT_F_NOT_GPIOD)) {
 836				mcp->status = -ENOENT;
 837			} else {
 838				mcp->status = !!data[mcp->gp_idx];
 839				mcp->gpio_dir = data[mcp->gp_idx + 1];
 840			}
 841			break;
 842		default:
 843			mcp->status = -EAGAIN;
 844		}
 845		complete(&mcp->wait_in_report);
 846		break;
 847
 848	case MCP2221_GPIO_SET:
 849		switch (data[1]) {
 850		case MCP2221_SUCCESS:
 851			if ((data[mcp->gp_idx] == MCP2221_ALT_F_NOT_GPIOV) ||
 852				(data[mcp->gp_idx - 1] == MCP2221_ALT_F_NOT_GPIOV)) {
 853				mcp->status = -ENOENT;
 854			} else {
 855				mcp->status = 0;
 856			}
 857			break;
 858		default:
 859			mcp->status = -EAGAIN;
 860		}
 861		complete(&mcp->wait_in_report);
 862		break;
 863
 864	case MCP2221_SET_SRAM_SETTINGS:
 865		switch (data[1]) {
 866		case MCP2221_SUCCESS:
 867			mcp->status = 0;
 868			break;
 869		default:
 870			mcp->status = -EAGAIN;
 871		}
 872		complete(&mcp->wait_in_report);
 873		break;
 874
 875	case MCP2221_GET_SRAM_SETTINGS:
 876		switch (data[1]) {
 877		case MCP2221_SUCCESS:
 878			memcpy(&mcp->mode, &data[22], 4);
 879#if IS_REACHABLE(CONFIG_IIO)
 880			mcp->dac_value = data[6] & GENMASK(4, 0);
 881#endif
 882			mcp->status = 0;
 883			break;
 884		default:
 885			mcp->status = -EAGAIN;
 886		}
 887		complete(&mcp->wait_in_report);
 888		break;
 889
 890	case MCP2221_READ_FLASH_DATA:
 891		switch (data[1]) {
 892		case MCP2221_SUCCESS:
 893			mcp->status = 0;
 894
 895			/* Only handles CHIP SETTINGS subpage currently */
 896			if (mcp->txbuf[1] != 0) {
 897				mcp->status = -EIO;
 898				break;
 899			}
 900
 901#if IS_REACHABLE(CONFIG_IIO)
 902			{
 903				u8 tmp;
 904				/* DAC scale value */
 905				tmp = FIELD_GET(GENMASK(7, 6), data[6]);
 906				if ((data[6] & BIT(5)) && tmp)
 907					mcp->dac_scale = tmp + 4;
 908				else
 909					mcp->dac_scale = 5;
 910
 911				/* ADC scale value */
 912				tmp = FIELD_GET(GENMASK(4, 3), data[7]);
 913				if ((data[7] & BIT(2)) && tmp)
 914					mcp->adc_scale = tmp - 1;
 915				else
 916					mcp->adc_scale = 0;
 917			}
 918#endif
 919
 920			break;
 921		default:
 922			mcp->status = -EAGAIN;
 923		}
 924		complete(&mcp->wait_in_report);
 925		break;
 926
 927	default:
 928		mcp->status = -EIO;
 929		complete(&mcp->wait_in_report);
 930	}
 931
 932	return 1;
 933}
 934
 935/* Device resource managed function for HID unregistration */
 936static void mcp2221_hid_unregister(void *ptr)
 937{
 938	struct hid_device *hdev = ptr;
 939
 940	hid_hw_close(hdev);
 941	hid_hw_stop(hdev);
 942}
 943
 944/* This is needed to be sure hid_hw_stop() isn't called twice by the subsystem */
 945static void mcp2221_remove(struct hid_device *hdev)
 946{
 947	struct mcp2221 *mcp = hid_get_drvdata(hdev);
 948
 949	cancel_delayed_work_sync(&mcp->init_work);
 950}
 951
 952#if IS_REACHABLE(CONFIG_IIO)
 953static int mcp2221_read_raw(struct iio_dev *indio_dev,
 954			    struct iio_chan_spec const *channel, int *val,
 955			    int *val2, long mask)
 956{
 957	struct mcp2221_iio *priv = iio_priv(indio_dev);
 958	struct mcp2221 *mcp = priv->mcp;
 959	int ret;
 960
 961	if (mask == IIO_CHAN_INFO_SCALE) {
 962		if (channel->output)
 963			*val = 1 << mcp->dac_scale;
 964		else
 965			*val = 1 << mcp->adc_scale;
 966
 967		return IIO_VAL_INT;
 968	}
 969
 970	mutex_lock(&mcp->lock);
 971
 972	if (channel->output) {
 973		*val = mcp->dac_value;
 974		ret = IIO_VAL_INT;
 975	} else {
 976		/* Read ADC values */
 977		ret = mcp_chk_last_cmd_status(mcp);
 978
 979		if (!ret) {
 980			*val = le16_to_cpu((__force __le16) mcp->adc_values[channel->address]);
 981			if (*val >= BIT(10))
 982				ret =  -EINVAL;
 983			else
 984				ret = IIO_VAL_INT;
 985		}
 986	}
 987
 988	mutex_unlock(&mcp->lock);
 989
 990	return ret;
 991}
 992
 993static int mcp2221_write_raw(struct iio_dev *indio_dev,
 994			     struct iio_chan_spec const *chan,
 995			     int val, int val2, long mask)
 996{
 997	struct mcp2221_iio *priv = iio_priv(indio_dev);
 998	struct mcp2221 *mcp = priv->mcp;
 999	int ret;
1000
1001	if (val < 0 || val >= BIT(5))
1002		return -EINVAL;
1003
1004	mutex_lock(&mcp->lock);
1005
1006	memset(mcp->txbuf, 0, 12);
1007	mcp->txbuf[0] = MCP2221_SET_SRAM_SETTINGS;
1008	mcp->txbuf[4] = BIT(7) | val;
1009
1010	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 12);
1011	if (!ret)
1012		mcp->dac_value = val;
1013
1014	mutex_unlock(&mcp->lock);
1015
1016	return ret;
1017}
1018
1019static const struct iio_info mcp2221_info = {
1020	.read_raw = &mcp2221_read_raw,
1021	.write_raw = &mcp2221_write_raw,
1022};
1023
1024static int mcp_iio_channels(struct mcp2221 *mcp)
1025{
1026	int idx, cnt = 0;
1027	bool dac_created = false;
1028
1029	/* GP0 doesn't have ADC/DAC alternative function */
1030	for (idx = 1; idx < MCP_NGPIO; idx++) {
1031		struct iio_chan_spec *chan = &mcp->iio_channels[cnt];
1032
1033		switch (mcp->mode[idx]) {
1034		case 2:
1035			chan->address = idx - 1;
1036			chan->channel = cnt++;
1037			break;
1038		case 3:
1039			/* GP1 doesn't have DAC alternative function */
1040			if (idx == 1 || dac_created)
1041				continue;
1042			/* DAC1 and DAC2 outputs are connected to the same DAC */
1043			dac_created = true;
1044			chan->output = 1;
1045			cnt++;
1046			break;
1047		default:
1048			continue;
1049		};
1050
1051		chan->type = IIO_VOLTAGE;
1052		chan->indexed = 1;
1053		chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
1054		chan->info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE);
1055		chan->scan_index = -1;
1056	}
1057
1058	return cnt;
1059}
1060
1061static void mcp_init_work(struct work_struct *work)
1062{
1063	struct iio_dev *indio_dev;
1064	struct mcp2221 *mcp = container_of(work, struct mcp2221, init_work.work);
1065	struct mcp2221_iio *data;
1066	static int retries = 5;
1067	int ret, num_channels;
1068
1069	hid_hw_power(mcp->hdev, PM_HINT_FULLON);
1070	mutex_lock(&mcp->lock);
1071
1072	mcp->txbuf[0] = MCP2221_GET_SRAM_SETTINGS;
1073	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 1);
1074
1075	if (ret == -EAGAIN)
1076		goto reschedule_task;
1077
1078	num_channels = mcp_iio_channels(mcp);
1079	if (!num_channels)
1080		goto unlock;
1081
1082	mcp->txbuf[0] = MCP2221_READ_FLASH_DATA;
1083	mcp->txbuf[1] = 0;
1084	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 2);
1085
1086	if (ret == -EAGAIN)
1087		goto reschedule_task;
1088
1089	indio_dev = devm_iio_device_alloc(&mcp->hdev->dev, sizeof(*data));
1090	if (!indio_dev)
1091		goto unlock;
1092
1093	data = iio_priv(indio_dev);
1094	data->mcp = mcp;
1095
1096	indio_dev->name = "mcp2221";
1097	indio_dev->modes = INDIO_DIRECT_MODE;
1098	indio_dev->info = &mcp2221_info;
1099	indio_dev->channels = mcp->iio_channels;
1100	indio_dev->num_channels = num_channels;
1101
1102	devm_iio_device_register(&mcp->hdev->dev, indio_dev);
1103
1104unlock:
1105	mutex_unlock(&mcp->lock);
1106	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
1107
1108	return;
1109
1110reschedule_task:
1111	mutex_unlock(&mcp->lock);
1112	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
1113
1114	if (!retries--)
1115		return;
1116
1117	/* Device is not ready to read SRAM or FLASH data, try again */
1118	schedule_delayed_work(&mcp->init_work, msecs_to_jiffies(100));
1119}
1120#endif
1121
1122static int mcp2221_probe(struct hid_device *hdev,
1123					const struct hid_device_id *id)
1124{
1125	int ret;
1126	struct mcp2221 *mcp;
1127
1128	mcp = devm_kzalloc(&hdev->dev, sizeof(*mcp), GFP_KERNEL);
1129	if (!mcp)
1130		return -ENOMEM;
1131
1132	ret = hid_parse(hdev);
1133	if (ret) {
1134		hid_err(hdev, "can't parse reports\n");
1135		return ret;
1136	}
1137
1138	/*
1139	 * This driver uses the .raw_event callback and therefore does not need any
1140	 * HID_CONNECT_xxx flags.
1141	 */
1142	ret = hid_hw_start(hdev, 0);
1143	if (ret) {
1144		hid_err(hdev, "can't start hardware\n");
1145		return ret;
1146	}
1147
1148	hid_info(hdev, "USB HID v%x.%02x Device [%s] on %s\n", hdev->version >> 8,
1149			hdev->version & 0xff, hdev->name, hdev->phys);
1150
1151	ret = hid_hw_open(hdev);
1152	if (ret) {
1153		hid_err(hdev, "can't open device\n");
1154		hid_hw_stop(hdev);
1155		return ret;
1156	}
1157
1158	mutex_init(&mcp->lock);
1159	init_completion(&mcp->wait_in_report);
1160	hid_set_drvdata(hdev, mcp);
1161	mcp->hdev = hdev;
1162
1163	ret = devm_add_action_or_reset(&hdev->dev, mcp2221_hid_unregister, hdev);
1164	if (ret)
1165		return ret;
1166
1167	hid_device_io_start(hdev);
1168
1169	/* Set I2C bus clock diviser */
1170	if (i2c_clk_freq > 400)
1171		i2c_clk_freq = 400;
1172	if (i2c_clk_freq < 50)
1173		i2c_clk_freq = 50;
1174	mcp->cur_i2c_clk_div = (12000000 / (i2c_clk_freq * 1000)) - 3;
1175	ret = mcp_set_i2c_speed(mcp);
1176	if (ret) {
1177		hid_err(hdev, "can't set i2c speed: %d\n", ret);
1178		return ret;
1179	}
1180
1181	mcp->adapter.owner = THIS_MODULE;
1182	mcp->adapter.class = I2C_CLASS_HWMON;
1183	mcp->adapter.algo = &mcp_i2c_algo;
1184	mcp->adapter.retries = 1;
1185	mcp->adapter.dev.parent = &hdev->dev;
1186	ACPI_COMPANION_SET(&mcp->adapter.dev, ACPI_COMPANION(hdev->dev.parent));
1187	snprintf(mcp->adapter.name, sizeof(mcp->adapter.name),
1188			"MCP2221 usb-i2c bridge");
1189
1190	i2c_set_adapdata(&mcp->adapter, mcp);
1191	ret = devm_i2c_add_adapter(&hdev->dev, &mcp->adapter);
1192	if (ret) {
1193		hid_err(hdev, "can't add usb-i2c adapter: %d\n", ret);
1194		return ret;
1195	}
1196
1197#if IS_REACHABLE(CONFIG_GPIOLIB)
1198	/* Setup GPIO chip */
1199	mcp->gc = devm_kzalloc(&hdev->dev, sizeof(*mcp->gc), GFP_KERNEL);
1200	if (!mcp->gc)
1201		return -ENOMEM;
1202
1203	mcp->gc->label = "mcp2221_gpio";
1204	mcp->gc->direction_input = mcp_gpio_direction_input;
1205	mcp->gc->direction_output = mcp_gpio_direction_output;
1206	mcp->gc->get_direction = mcp_gpio_get_direction;
1207	mcp->gc->set = mcp_gpio_set;
1208	mcp->gc->get = mcp_gpio_get;
1209	mcp->gc->ngpio = MCP_NGPIO;
1210	mcp->gc->base = -1;
1211	mcp->gc->can_sleep = 1;
1212	mcp->gc->parent = &hdev->dev;
1213
1214	ret = devm_gpiochip_add_data(&hdev->dev, mcp->gc, mcp);
1215	if (ret)
1216		return ret;
1217#endif
1218
1219#if IS_REACHABLE(CONFIG_IIO)
1220	INIT_DELAYED_WORK(&mcp->init_work, mcp_init_work);
1221	schedule_delayed_work(&mcp->init_work, msecs_to_jiffies(100));
1222#endif
1223
1224	return 0;
1225}
1226
1227static const struct hid_device_id mcp2221_devices[] = {
1228	{ HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_MCP2221) },
1229	{ }
1230};
1231MODULE_DEVICE_TABLE(hid, mcp2221_devices);
1232
1233static struct hid_driver mcp2221_driver = {
1234	.name		= "mcp2221",
1235	.id_table	= mcp2221_devices,
1236	.probe		= mcp2221_probe,
1237	.remove		= mcp2221_remove,
1238	.raw_event	= mcp2221_raw_event,
1239};
1240
1241/* Register with HID core */
1242module_hid_driver(mcp2221_driver);
1243
1244MODULE_AUTHOR("Rishi Gupta <gupt21@gmail.com>");
1245MODULE_DESCRIPTION("MCP2221 Microchip HID USB to I2C master bridge");
1246MODULE_LICENSE("GPL v2");