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