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