xref: /linux/drivers/hid/hid-mcp2221.c (revision 2c9b3512402ed192d1f43f4531fb5da947e72bd0)
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_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 */
59 enum {
60 	MCP2221_DIR_OUT = 0x00,
61 	MCP2221_DIR_IN = 0x01,
62 };
63 
64 #define MCP_NGPIO	4
65 
66 /* MCP GPIO set command layout */
67 struct 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 */
79 struct 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  */
93 struct 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 
117 struct 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  */
125 static uint i2c_clk_freq = 400;
126 
127 /* Synchronously send output report to the device */
128 static 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  */
152 static 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 */
173 static 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 */
182 static 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  */
194 static 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 
210 static 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  */
237 static 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  */
295 static 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 
353 static 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 
401 exit:
402 	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
403 	mutex_unlock(&mcp->lock);
404 	return ret;
405 }
406 
407 static 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 
453 static 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 
589 exit:
590 	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
591 	mutex_unlock(&mcp->lock);
592 	return ret;
593 }
594 
595 static 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 
603 static 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)
610 static 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 
627 static 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 
645 static 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 
659 static 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 
672 static 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 
691 static 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 */
716 static 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  */
754 static 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 */
936 static 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 */
945 static void mcp2221_remove(struct hid_device *hdev)
946 {
947 #if IS_REACHABLE(CONFIG_IIO)
948 	struct mcp2221 *mcp = hid_get_drvdata(hdev);
949 
950 	cancel_delayed_work_sync(&mcp->init_work);
951 #endif
952 }
953 
954 #if IS_REACHABLE(CONFIG_IIO)
955 static int mcp2221_read_raw(struct iio_dev *indio_dev,
956 			    struct iio_chan_spec const *channel, int *val,
957 			    int *val2, long mask)
958 {
959 	struct mcp2221_iio *priv = iio_priv(indio_dev);
960 	struct mcp2221 *mcp = priv->mcp;
961 	int ret;
962 
963 	if (mask == IIO_CHAN_INFO_SCALE) {
964 		if (channel->output)
965 			*val = 1 << mcp->dac_scale;
966 		else
967 			*val = 1 << mcp->adc_scale;
968 
969 		return IIO_VAL_INT;
970 	}
971 
972 	mutex_lock(&mcp->lock);
973 
974 	if (channel->output) {
975 		*val = mcp->dac_value;
976 		ret = IIO_VAL_INT;
977 	} else {
978 		/* Read ADC values */
979 		ret = mcp_chk_last_cmd_status(mcp);
980 
981 		if (!ret) {
982 			*val = le16_to_cpu((__force __le16) mcp->adc_values[channel->address]);
983 			if (*val >= BIT(10))
984 				ret =  -EINVAL;
985 			else
986 				ret = IIO_VAL_INT;
987 		}
988 	}
989 
990 	mutex_unlock(&mcp->lock);
991 
992 	return ret;
993 }
994 
995 static int mcp2221_write_raw(struct iio_dev *indio_dev,
996 			     struct iio_chan_spec const *chan,
997 			     int val, int val2, long mask)
998 {
999 	struct mcp2221_iio *priv = iio_priv(indio_dev);
1000 	struct mcp2221 *mcp = priv->mcp;
1001 	int ret;
1002 
1003 	if (val < 0 || val >= BIT(5))
1004 		return -EINVAL;
1005 
1006 	mutex_lock(&mcp->lock);
1007 
1008 	memset(mcp->txbuf, 0, 12);
1009 	mcp->txbuf[0] = MCP2221_SET_SRAM_SETTINGS;
1010 	mcp->txbuf[4] = BIT(7) | val;
1011 
1012 	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 12);
1013 	if (!ret)
1014 		mcp->dac_value = val;
1015 
1016 	mutex_unlock(&mcp->lock);
1017 
1018 	return ret;
1019 }
1020 
1021 static const struct iio_info mcp2221_info = {
1022 	.read_raw = &mcp2221_read_raw,
1023 	.write_raw = &mcp2221_write_raw,
1024 };
1025 
1026 static int mcp_iio_channels(struct mcp2221 *mcp)
1027 {
1028 	int idx, cnt = 0;
1029 	bool dac_created = false;
1030 
1031 	/* GP0 doesn't have ADC/DAC alternative function */
1032 	for (idx = 1; idx < MCP_NGPIO; idx++) {
1033 		struct iio_chan_spec *chan = &mcp->iio_channels[cnt];
1034 
1035 		switch (mcp->mode[idx]) {
1036 		case 2:
1037 			chan->address = idx - 1;
1038 			chan->channel = cnt++;
1039 			break;
1040 		case 3:
1041 			/* GP1 doesn't have DAC alternative function */
1042 			if (idx == 1 || dac_created)
1043 				continue;
1044 			/* DAC1 and DAC2 outputs are connected to the same DAC */
1045 			dac_created = true;
1046 			chan->output = 1;
1047 			cnt++;
1048 			break;
1049 		default:
1050 			continue;
1051 		}
1052 
1053 		chan->type = IIO_VOLTAGE;
1054 		chan->indexed = 1;
1055 		chan->info_mask_separate = BIT(IIO_CHAN_INFO_RAW);
1056 		chan->info_mask_shared_by_type = BIT(IIO_CHAN_INFO_SCALE);
1057 		chan->scan_index = -1;
1058 	}
1059 
1060 	return cnt;
1061 }
1062 
1063 static void mcp_init_work(struct work_struct *work)
1064 {
1065 	struct iio_dev *indio_dev;
1066 	struct mcp2221 *mcp = container_of(work, struct mcp2221, init_work.work);
1067 	struct mcp2221_iio *data;
1068 	static int retries = 5;
1069 	int ret, num_channels;
1070 
1071 	hid_hw_power(mcp->hdev, PM_HINT_FULLON);
1072 	mutex_lock(&mcp->lock);
1073 
1074 	mcp->txbuf[0] = MCP2221_GET_SRAM_SETTINGS;
1075 	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 1);
1076 
1077 	if (ret == -EAGAIN)
1078 		goto reschedule_task;
1079 
1080 	num_channels = mcp_iio_channels(mcp);
1081 	if (!num_channels)
1082 		goto unlock;
1083 
1084 	mcp->txbuf[0] = MCP2221_READ_FLASH_DATA;
1085 	mcp->txbuf[1] = 0;
1086 	ret = mcp_send_data_req_status(mcp, mcp->txbuf, 2);
1087 
1088 	if (ret == -EAGAIN)
1089 		goto reschedule_task;
1090 
1091 	indio_dev = devm_iio_device_alloc(&mcp->hdev->dev, sizeof(*data));
1092 	if (!indio_dev)
1093 		goto unlock;
1094 
1095 	data = iio_priv(indio_dev);
1096 	data->mcp = mcp;
1097 
1098 	indio_dev->name = "mcp2221";
1099 	indio_dev->modes = INDIO_DIRECT_MODE;
1100 	indio_dev->info = &mcp2221_info;
1101 	indio_dev->channels = mcp->iio_channels;
1102 	indio_dev->num_channels = num_channels;
1103 
1104 	devm_iio_device_register(&mcp->hdev->dev, indio_dev);
1105 
1106 unlock:
1107 	mutex_unlock(&mcp->lock);
1108 	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
1109 
1110 	return;
1111 
1112 reschedule_task:
1113 	mutex_unlock(&mcp->lock);
1114 	hid_hw_power(mcp->hdev, PM_HINT_NORMAL);
1115 
1116 	if (!retries--)
1117 		return;
1118 
1119 	/* Device is not ready to read SRAM or FLASH data, try again */
1120 	schedule_delayed_work(&mcp->init_work, msecs_to_jiffies(100));
1121 }
1122 #endif
1123 
1124 static int mcp2221_probe(struct hid_device *hdev,
1125 					const struct hid_device_id *id)
1126 {
1127 	int ret;
1128 	struct mcp2221 *mcp;
1129 
1130 	mcp = devm_kzalloc(&hdev->dev, sizeof(*mcp), GFP_KERNEL);
1131 	if (!mcp)
1132 		return -ENOMEM;
1133 
1134 	ret = hid_parse(hdev);
1135 	if (ret) {
1136 		hid_err(hdev, "can't parse reports\n");
1137 		return ret;
1138 	}
1139 
1140 	/*
1141 	 * This driver uses the .raw_event callback and therefore does not need any
1142 	 * HID_CONNECT_xxx flags.
1143 	 */
1144 	ret = hid_hw_start(hdev, 0);
1145 	if (ret) {
1146 		hid_err(hdev, "can't start hardware\n");
1147 		return ret;
1148 	}
1149 
1150 	hid_info(hdev, "USB HID v%x.%02x Device [%s] on %s\n", hdev->version >> 8,
1151 			hdev->version & 0xff, hdev->name, hdev->phys);
1152 
1153 	ret = hid_hw_open(hdev);
1154 	if (ret) {
1155 		hid_err(hdev, "can't open device\n");
1156 		hid_hw_stop(hdev);
1157 		return ret;
1158 	}
1159 
1160 	mutex_init(&mcp->lock);
1161 	init_completion(&mcp->wait_in_report);
1162 	hid_set_drvdata(hdev, mcp);
1163 	mcp->hdev = hdev;
1164 
1165 	ret = devm_add_action_or_reset(&hdev->dev, mcp2221_hid_unregister, hdev);
1166 	if (ret)
1167 		return ret;
1168 
1169 	hid_device_io_start(hdev);
1170 
1171 	/* Set I2C bus clock diviser */
1172 	if (i2c_clk_freq > 400)
1173 		i2c_clk_freq = 400;
1174 	if (i2c_clk_freq < 50)
1175 		i2c_clk_freq = 50;
1176 	mcp->cur_i2c_clk_div = (12000000 / (i2c_clk_freq * 1000)) - 3;
1177 	ret = mcp_set_i2c_speed(mcp);
1178 	if (ret) {
1179 		hid_err(hdev, "can't set i2c speed: %d\n", ret);
1180 		return ret;
1181 	}
1182 
1183 	mcp->adapter.owner = THIS_MODULE;
1184 	mcp->adapter.class = I2C_CLASS_HWMON;
1185 	mcp->adapter.algo = &mcp_i2c_algo;
1186 	mcp->adapter.retries = 1;
1187 	mcp->adapter.dev.parent = &hdev->dev;
1188 	ACPI_COMPANION_SET(&mcp->adapter.dev, ACPI_COMPANION(hdev->dev.parent));
1189 	snprintf(mcp->adapter.name, sizeof(mcp->adapter.name),
1190 			"MCP2221 usb-i2c bridge");
1191 
1192 	i2c_set_adapdata(&mcp->adapter, mcp);
1193 	ret = devm_i2c_add_adapter(&hdev->dev, &mcp->adapter);
1194 	if (ret) {
1195 		hid_err(hdev, "can't add usb-i2c adapter: %d\n", ret);
1196 		return ret;
1197 	}
1198 
1199 #if IS_REACHABLE(CONFIG_GPIOLIB)
1200 	/* Setup GPIO chip */
1201 	mcp->gc = devm_kzalloc(&hdev->dev, sizeof(*mcp->gc), GFP_KERNEL);
1202 	if (!mcp->gc)
1203 		return -ENOMEM;
1204 
1205 	mcp->gc->label = "mcp2221_gpio";
1206 	mcp->gc->direction_input = mcp_gpio_direction_input;
1207 	mcp->gc->direction_output = mcp_gpio_direction_output;
1208 	mcp->gc->get_direction = mcp_gpio_get_direction;
1209 	mcp->gc->set = mcp_gpio_set;
1210 	mcp->gc->get = mcp_gpio_get;
1211 	mcp->gc->ngpio = MCP_NGPIO;
1212 	mcp->gc->base = -1;
1213 	mcp->gc->can_sleep = 1;
1214 	mcp->gc->parent = &hdev->dev;
1215 
1216 	ret = devm_gpiochip_add_data(&hdev->dev, mcp->gc, mcp);
1217 	if (ret)
1218 		return ret;
1219 #endif
1220 
1221 #if IS_REACHABLE(CONFIG_IIO)
1222 	INIT_DELAYED_WORK(&mcp->init_work, mcp_init_work);
1223 	schedule_delayed_work(&mcp->init_work, msecs_to_jiffies(100));
1224 #endif
1225 
1226 	return 0;
1227 }
1228 
1229 static const struct hid_device_id mcp2221_devices[] = {
1230 	{ HID_USB_DEVICE(USB_VENDOR_ID_MICROCHIP, USB_DEVICE_ID_MCP2221) },
1231 	{ }
1232 };
1233 MODULE_DEVICE_TABLE(hid, mcp2221_devices);
1234 
1235 static struct hid_driver mcp2221_driver = {
1236 	.name		= "mcp2221",
1237 	.id_table	= mcp2221_devices,
1238 	.probe		= mcp2221_probe,
1239 	.remove		= mcp2221_remove,
1240 	.raw_event	= mcp2221_raw_event,
1241 };
1242 
1243 /* Register with HID core */
1244 module_hid_driver(mcp2221_driver);
1245 
1246 MODULE_AUTHOR("Rishi Gupta <gupt21@gmail.com>");
1247 MODULE_DESCRIPTION("MCP2221 Microchip HID USB to I2C master bridge");
1248 MODULE_LICENSE("GPL v2");
1249