1 /*
2  * hid-cp2112.c - Silicon Labs HID USB to SMBus master bridge
3  * Copyright (c) 2013,2014 Uplogix, Inc.
4  * David Barksdale <dbarksdale@uplogix.com>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms and conditions of the GNU General Public License,
8  * version 2, as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
13  * more details.
14  */
15 
16 /*
17  * The Silicon Labs CP2112 chip is a USB HID device which provides an
18  * SMBus controller for talking to slave devices and 8 GPIO pins. The
19  * host communicates with the CP2112 via raw HID reports.
20  *
21  * Data Sheet:
22  *   http://www.silabs.com/Support%20Documents/TechnicalDocs/CP2112.pdf
23  * Programming Interface Specification:
24  *   https://www.silabs.com/documents/public/application-notes/an495-cp2112-interface-specification.pdf
25  */
26 
27 #include <linux/gpio.h>
28 #include <linux/gpio/driver.h>
29 #include <linux/hid.h>
30 #include <linux/hidraw.h>
31 #include <linux/i2c.h>
32 #include <linux/module.h>
33 #include <linux/nls.h>
34 #include <linux/usb/ch9.h>
35 #include "hid-ids.h"
36 
37 #define CP2112_REPORT_MAX_LENGTH		64
38 #define CP2112_GPIO_CONFIG_LENGTH		5
39 #define CP2112_GPIO_GET_LENGTH			2
40 #define CP2112_GPIO_SET_LENGTH			3
41 
42 enum {
43 	CP2112_GPIO_CONFIG		= 0x02,
44 	CP2112_GPIO_GET			= 0x03,
45 	CP2112_GPIO_SET			= 0x04,
46 	CP2112_GET_VERSION_INFO		= 0x05,
47 	CP2112_SMBUS_CONFIG		= 0x06,
48 	CP2112_DATA_READ_REQUEST	= 0x10,
49 	CP2112_DATA_WRITE_READ_REQUEST	= 0x11,
50 	CP2112_DATA_READ_FORCE_SEND	= 0x12,
51 	CP2112_DATA_READ_RESPONSE	= 0x13,
52 	CP2112_DATA_WRITE_REQUEST	= 0x14,
53 	CP2112_TRANSFER_STATUS_REQUEST	= 0x15,
54 	CP2112_TRANSFER_STATUS_RESPONSE	= 0x16,
55 	CP2112_CANCEL_TRANSFER		= 0x17,
56 	CP2112_LOCK_BYTE		= 0x20,
57 	CP2112_USB_CONFIG		= 0x21,
58 	CP2112_MANUFACTURER_STRING	= 0x22,
59 	CP2112_PRODUCT_STRING		= 0x23,
60 	CP2112_SERIAL_STRING		= 0x24,
61 };
62 
63 enum {
64 	STATUS0_IDLE		= 0x00,
65 	STATUS0_BUSY		= 0x01,
66 	STATUS0_COMPLETE	= 0x02,
67 	STATUS0_ERROR		= 0x03,
68 };
69 
70 enum {
71 	STATUS1_TIMEOUT_NACK		= 0x00,
72 	STATUS1_TIMEOUT_BUS		= 0x01,
73 	STATUS1_ARBITRATION_LOST	= 0x02,
74 	STATUS1_READ_INCOMPLETE		= 0x03,
75 	STATUS1_WRITE_INCOMPLETE	= 0x04,
76 	STATUS1_SUCCESS			= 0x05,
77 };
78 
79 struct cp2112_smbus_config_report {
80 	u8 report;		/* CP2112_SMBUS_CONFIG */
81 	__be32 clock_speed;	/* Hz */
82 	u8 device_address;	/* Stored in the upper 7 bits */
83 	u8 auto_send_read;	/* 1 = enabled, 0 = disabled */
84 	__be16 write_timeout;	/* ms, 0 = no timeout */
85 	__be16 read_timeout;	/* ms, 0 = no timeout */
86 	u8 scl_low_timeout;	/* 1 = enabled, 0 = disabled */
87 	__be16 retry_time;	/* # of retries, 0 = no limit */
88 } __packed;
89 
90 struct cp2112_usb_config_report {
91 	u8 report;	/* CP2112_USB_CONFIG */
92 	__le16 vid;	/* Vendor ID */
93 	__le16 pid;	/* Product ID */
94 	u8 max_power;	/* Power requested in 2mA units */
95 	u8 power_mode;	/* 0x00 = bus powered
96 			   0x01 = self powered & regulator off
97 			   0x02 = self powered & regulator on */
98 	u8 release_major;
99 	u8 release_minor;
100 	u8 mask;	/* What fields to program */
101 } __packed;
102 
103 struct cp2112_read_req_report {
104 	u8 report;	/* CP2112_DATA_READ_REQUEST */
105 	u8 slave_address;
106 	__be16 length;
107 } __packed;
108 
109 struct cp2112_write_read_req_report {
110 	u8 report;	/* CP2112_DATA_WRITE_READ_REQUEST */
111 	u8 slave_address;
112 	__be16 length;
113 	u8 target_address_length;
114 	u8 target_address[16];
115 } __packed;
116 
117 struct cp2112_write_req_report {
118 	u8 report;	/* CP2112_DATA_WRITE_REQUEST */
119 	u8 slave_address;
120 	u8 length;
121 	u8 data[61];
122 } __packed;
123 
124 struct cp2112_force_read_report {
125 	u8 report;	/* CP2112_DATA_READ_FORCE_SEND */
126 	__be16 length;
127 } __packed;
128 
129 struct cp2112_xfer_status_report {
130 	u8 report;	/* CP2112_TRANSFER_STATUS_RESPONSE */
131 	u8 status0;	/* STATUS0_* */
132 	u8 status1;	/* STATUS1_* */
133 	__be16 retries;
134 	__be16 length;
135 } __packed;
136 
137 struct cp2112_string_report {
138 	u8 dummy;		/* force .string to be aligned */
139 	u8 report;		/* CP2112_*_STRING */
140 	u8 length;		/* length in bytes of everyting after .report */
141 	u8 type;		/* USB_DT_STRING */
142 	wchar_t string[30];	/* UTF16_LITTLE_ENDIAN string */
143 } __packed;
144 
145 /* Number of times to request transfer status before giving up waiting for a
146    transfer to complete. This may need to be changed if SMBUS clock, retries,
147    or read/write/scl_low timeout settings are changed. */
148 static const int XFER_STATUS_RETRIES = 10;
149 
150 /* Time in ms to wait for a CP2112_DATA_READ_RESPONSE or
151    CP2112_TRANSFER_STATUS_RESPONSE. */
152 static const int RESPONSE_TIMEOUT = 50;
153 
154 static const struct hid_device_id cp2112_devices[] = {
155 	{ HID_USB_DEVICE(USB_VENDOR_ID_CYGNAL, USB_DEVICE_ID_CYGNAL_CP2112) },
156 	{ }
157 };
158 MODULE_DEVICE_TABLE(hid, cp2112_devices);
159 
160 struct cp2112_device {
161 	struct i2c_adapter adap;
162 	struct hid_device *hdev;
163 	wait_queue_head_t wait;
164 	u8 read_data[61];
165 	u8 read_length;
166 	u8 hwversion;
167 	int xfer_status;
168 	atomic_t read_avail;
169 	atomic_t xfer_avail;
170 	struct gpio_chip gc;
171 	u8 *in_out_buffer;
172 	struct mutex lock;
173 
174 	struct gpio_desc *desc[8];
175 	bool gpio_poll;
176 	struct delayed_work gpio_poll_worker;
177 	unsigned long irq_mask;
178 	u8 gpio_prev_state;
179 };
180 
181 static int gpio_push_pull = 0xFF;
182 module_param(gpio_push_pull, int, S_IRUGO | S_IWUSR);
183 MODULE_PARM_DESC(gpio_push_pull, "GPIO push-pull configuration bitmask");
184 
cp2112_gpio_direction_input(struct gpio_chip * chip,unsigned offset)185 static int cp2112_gpio_direction_input(struct gpio_chip *chip, unsigned offset)
186 {
187 	struct cp2112_device *dev = gpiochip_get_data(chip);
188 	struct hid_device *hdev = dev->hdev;
189 	u8 *buf = dev->in_out_buffer;
190 	int ret;
191 
192 	mutex_lock(&dev->lock);
193 
194 	ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
195 				 CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
196 				 HID_REQ_GET_REPORT);
197 	if (ret != CP2112_GPIO_CONFIG_LENGTH) {
198 		hid_err(hdev, "error requesting GPIO config: %d\n", ret);
199 		if (ret >= 0)
200 			ret = -EIO;
201 		goto exit;
202 	}
203 
204 	buf[1] &= ~(1 << offset);
205 	buf[2] = gpio_push_pull;
206 
207 	ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
208 				 CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
209 				 HID_REQ_SET_REPORT);
210 	if (ret != CP2112_GPIO_CONFIG_LENGTH) {
211 		hid_err(hdev, "error setting GPIO config: %d\n", ret);
212 		if (ret >= 0)
213 			ret = -EIO;
214 		goto exit;
215 	}
216 
217 	ret = 0;
218 
219 exit:
220 	mutex_unlock(&dev->lock);
221 	return ret;
222 }
223 
cp2112_gpio_set(struct gpio_chip * chip,unsigned offset,int value)224 static void cp2112_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
225 {
226 	struct cp2112_device *dev = gpiochip_get_data(chip);
227 	struct hid_device *hdev = dev->hdev;
228 	u8 *buf = dev->in_out_buffer;
229 	int ret;
230 
231 	mutex_lock(&dev->lock);
232 
233 	buf[0] = CP2112_GPIO_SET;
234 	buf[1] = value ? 0xff : 0;
235 	buf[2] = 1 << offset;
236 
237 	ret = hid_hw_raw_request(hdev, CP2112_GPIO_SET, buf,
238 				 CP2112_GPIO_SET_LENGTH, HID_FEATURE_REPORT,
239 				 HID_REQ_SET_REPORT);
240 	if (ret < 0)
241 		hid_err(hdev, "error setting GPIO values: %d\n", ret);
242 
243 	mutex_unlock(&dev->lock);
244 }
245 
cp2112_gpio_get_all(struct gpio_chip * chip)246 static int cp2112_gpio_get_all(struct gpio_chip *chip)
247 {
248 	struct cp2112_device *dev = gpiochip_get_data(chip);
249 	struct hid_device *hdev = dev->hdev;
250 	u8 *buf = dev->in_out_buffer;
251 	int ret;
252 
253 	mutex_lock(&dev->lock);
254 
255 	ret = hid_hw_raw_request(hdev, CP2112_GPIO_GET, buf,
256 				 CP2112_GPIO_GET_LENGTH, HID_FEATURE_REPORT,
257 				 HID_REQ_GET_REPORT);
258 	if (ret != CP2112_GPIO_GET_LENGTH) {
259 		hid_err(hdev, "error requesting GPIO values: %d\n", ret);
260 		ret = ret < 0 ? ret : -EIO;
261 		goto exit;
262 	}
263 
264 	ret = buf[1];
265 
266 exit:
267 	mutex_unlock(&dev->lock);
268 
269 	return ret;
270 }
271 
cp2112_gpio_get(struct gpio_chip * chip,unsigned int offset)272 static int cp2112_gpio_get(struct gpio_chip *chip, unsigned int offset)
273 {
274 	int ret;
275 
276 	ret = cp2112_gpio_get_all(chip);
277 	if (ret < 0)
278 		return ret;
279 
280 	return (ret >> offset) & 1;
281 }
282 
cp2112_gpio_direction_output(struct gpio_chip * chip,unsigned offset,int value)283 static int cp2112_gpio_direction_output(struct gpio_chip *chip,
284 					unsigned offset, int value)
285 {
286 	struct cp2112_device *dev = gpiochip_get_data(chip);
287 	struct hid_device *hdev = dev->hdev;
288 	u8 *buf = dev->in_out_buffer;
289 	int ret;
290 
291 	mutex_lock(&dev->lock);
292 
293 	ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
294 				 CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
295 				 HID_REQ_GET_REPORT);
296 	if (ret != CP2112_GPIO_CONFIG_LENGTH) {
297 		hid_err(hdev, "error requesting GPIO config: %d\n", ret);
298 		goto fail;
299 	}
300 
301 	buf[1] |= 1 << offset;
302 	buf[2] = gpio_push_pull;
303 
304 	ret = hid_hw_raw_request(hdev, CP2112_GPIO_CONFIG, buf,
305 				 CP2112_GPIO_CONFIG_LENGTH, HID_FEATURE_REPORT,
306 				 HID_REQ_SET_REPORT);
307 	if (ret < 0) {
308 		hid_err(hdev, "error setting GPIO config: %d\n", ret);
309 		goto fail;
310 	}
311 
312 	mutex_unlock(&dev->lock);
313 
314 	/*
315 	 * Set gpio value when output direction is already set,
316 	 * as specified in AN495, Rev. 0.2, cpt. 4.4
317 	 */
318 	cp2112_gpio_set(chip, offset, value);
319 
320 	return 0;
321 
322 fail:
323 	mutex_unlock(&dev->lock);
324 	return ret < 0 ? ret : -EIO;
325 }
326 
cp2112_hid_get(struct hid_device * hdev,unsigned char report_number,u8 * data,size_t count,unsigned char report_type)327 static int cp2112_hid_get(struct hid_device *hdev, unsigned char report_number,
328 			  u8 *data, size_t count, unsigned char report_type)
329 {
330 	u8 *buf;
331 	int ret;
332 
333 	buf = kmalloc(count, GFP_KERNEL);
334 	if (!buf)
335 		return -ENOMEM;
336 
337 	ret = hid_hw_raw_request(hdev, report_number, buf, count,
338 				       report_type, HID_REQ_GET_REPORT);
339 	memcpy(data, buf, count);
340 	kfree(buf);
341 	return ret;
342 }
343 
cp2112_hid_output(struct hid_device * hdev,u8 * data,size_t count,unsigned char report_type)344 static int cp2112_hid_output(struct hid_device *hdev, u8 *data, size_t count,
345 			     unsigned char report_type)
346 {
347 	u8 *buf;
348 	int ret;
349 
350 	buf = kmemdup(data, count, GFP_KERNEL);
351 	if (!buf)
352 		return -ENOMEM;
353 
354 	if (report_type == HID_OUTPUT_REPORT)
355 		ret = hid_hw_output_report(hdev, buf, count);
356 	else
357 		ret = hid_hw_raw_request(hdev, buf[0], buf, count, report_type,
358 				HID_REQ_SET_REPORT);
359 
360 	kfree(buf);
361 	return ret;
362 }
363 
cp2112_wait(struct cp2112_device * dev,atomic_t * avail)364 static int cp2112_wait(struct cp2112_device *dev, atomic_t *avail)
365 {
366 	int ret = 0;
367 
368 	/* We have sent either a CP2112_TRANSFER_STATUS_REQUEST or a
369 	 * CP2112_DATA_READ_FORCE_SEND and we are waiting for the response to
370 	 * come in cp2112_raw_event or timeout. There will only be one of these
371 	 * in flight at any one time. The timeout is extremely large and is a
372 	 * last resort if the CP2112 has died. If we do timeout we don't expect
373 	 * to receive the response which would cause data races, it's not like
374 	 * we can do anything about it anyway.
375 	 */
376 	ret = wait_event_interruptible_timeout(dev->wait,
377 		atomic_read(avail), msecs_to_jiffies(RESPONSE_TIMEOUT));
378 	if (-ERESTARTSYS == ret)
379 		return ret;
380 	if (!ret)
381 		return -ETIMEDOUT;
382 
383 	atomic_set(avail, 0);
384 	return 0;
385 }
386 
cp2112_xfer_status(struct cp2112_device * dev)387 static int cp2112_xfer_status(struct cp2112_device *dev)
388 {
389 	struct hid_device *hdev = dev->hdev;
390 	u8 buf[2];
391 	int ret;
392 
393 	buf[0] = CP2112_TRANSFER_STATUS_REQUEST;
394 	buf[1] = 0x01;
395 	atomic_set(&dev->xfer_avail, 0);
396 
397 	ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
398 	if (ret < 0) {
399 		hid_warn(hdev, "Error requesting status: %d\n", ret);
400 		return ret;
401 	}
402 
403 	ret = cp2112_wait(dev, &dev->xfer_avail);
404 	if (ret)
405 		return ret;
406 
407 	return dev->xfer_status;
408 }
409 
cp2112_read(struct cp2112_device * dev,u8 * data,size_t size)410 static int cp2112_read(struct cp2112_device *dev, u8 *data, size_t size)
411 {
412 	struct hid_device *hdev = dev->hdev;
413 	struct cp2112_force_read_report report;
414 	int ret;
415 
416 	if (size > sizeof(dev->read_data))
417 		size = sizeof(dev->read_data);
418 	report.report = CP2112_DATA_READ_FORCE_SEND;
419 	report.length = cpu_to_be16(size);
420 
421 	atomic_set(&dev->read_avail, 0);
422 
423 	ret = cp2112_hid_output(hdev, &report.report, sizeof(report),
424 				HID_OUTPUT_REPORT);
425 	if (ret < 0) {
426 		hid_warn(hdev, "Error requesting data: %d\n", ret);
427 		return ret;
428 	}
429 
430 	ret = cp2112_wait(dev, &dev->read_avail);
431 	if (ret)
432 		return ret;
433 
434 	hid_dbg(hdev, "read %d of %zd bytes requested\n",
435 		dev->read_length, size);
436 
437 	if (size > dev->read_length)
438 		size = dev->read_length;
439 
440 	memcpy(data, dev->read_data, size);
441 	return dev->read_length;
442 }
443 
cp2112_read_req(void * buf,u8 slave_address,u16 length)444 static int cp2112_read_req(void *buf, u8 slave_address, u16 length)
445 {
446 	struct cp2112_read_req_report *report = buf;
447 
448 	if (length < 1 || length > 512)
449 		return -EINVAL;
450 
451 	report->report = CP2112_DATA_READ_REQUEST;
452 	report->slave_address = slave_address << 1;
453 	report->length = cpu_to_be16(length);
454 	return sizeof(*report);
455 }
456 
cp2112_write_read_req(void * buf,u8 slave_address,u16 length,u8 command,u8 * data,u8 data_length)457 static int cp2112_write_read_req(void *buf, u8 slave_address, u16 length,
458 				 u8 command, u8 *data, u8 data_length)
459 {
460 	struct cp2112_write_read_req_report *report = buf;
461 
462 	if (length < 1 || length > 512
463 	    || data_length > sizeof(report->target_address) - 1)
464 		return -EINVAL;
465 
466 	report->report = CP2112_DATA_WRITE_READ_REQUEST;
467 	report->slave_address = slave_address << 1;
468 	report->length = cpu_to_be16(length);
469 	report->target_address_length = data_length + 1;
470 	report->target_address[0] = command;
471 	memcpy(&report->target_address[1], data, data_length);
472 	return data_length + 6;
473 }
474 
cp2112_write_req(void * buf,u8 slave_address,u8 command,u8 * data,u8 data_length)475 static int cp2112_write_req(void *buf, u8 slave_address, u8 command, u8 *data,
476 			    u8 data_length)
477 {
478 	struct cp2112_write_req_report *report = buf;
479 
480 	if (data_length > sizeof(report->data) - 1)
481 		return -EINVAL;
482 
483 	report->report = CP2112_DATA_WRITE_REQUEST;
484 	report->slave_address = slave_address << 1;
485 	report->length = data_length + 1;
486 	report->data[0] = command;
487 	memcpy(&report->data[1], data, data_length);
488 	return data_length + 4;
489 }
490 
cp2112_i2c_write_req(void * buf,u8 slave_address,u8 * data,u8 data_length)491 static int cp2112_i2c_write_req(void *buf, u8 slave_address, u8 *data,
492 				u8 data_length)
493 {
494 	struct cp2112_write_req_report *report = buf;
495 
496 	if (data_length > sizeof(report->data))
497 		return -EINVAL;
498 
499 	report->report = CP2112_DATA_WRITE_REQUEST;
500 	report->slave_address = slave_address << 1;
501 	report->length = data_length;
502 	memcpy(report->data, data, data_length);
503 	return data_length + 3;
504 }
505 
cp2112_i2c_write_read_req(void * buf,u8 slave_address,u8 * addr,int addr_length,int read_length)506 static int cp2112_i2c_write_read_req(void *buf, u8 slave_address,
507 				     u8 *addr, int addr_length,
508 				     int read_length)
509 {
510 	struct cp2112_write_read_req_report *report = buf;
511 
512 	if (read_length < 1 || read_length > 512 ||
513 	    addr_length > sizeof(report->target_address))
514 		return -EINVAL;
515 
516 	report->report = CP2112_DATA_WRITE_READ_REQUEST;
517 	report->slave_address = slave_address << 1;
518 	report->length = cpu_to_be16(read_length);
519 	report->target_address_length = addr_length;
520 	memcpy(report->target_address, addr, addr_length);
521 	return addr_length + 5;
522 }
523 
cp2112_i2c_xfer(struct i2c_adapter * adap,struct i2c_msg * msgs,int num)524 static int cp2112_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg *msgs,
525 			   int num)
526 {
527 	struct cp2112_device *dev = (struct cp2112_device *)adap->algo_data;
528 	struct hid_device *hdev = dev->hdev;
529 	u8 buf[64];
530 	ssize_t count;
531 	ssize_t read_length = 0;
532 	u8 *read_buf = NULL;
533 	unsigned int retries;
534 	int ret;
535 
536 	hid_dbg(hdev, "I2C %d messages\n", num);
537 
538 	if (num == 1) {
539 		if (msgs->flags & I2C_M_RD) {
540 			hid_dbg(hdev, "I2C read %#04x len %d\n",
541 				msgs->addr, msgs->len);
542 			read_length = msgs->len;
543 			read_buf = msgs->buf;
544 			count = cp2112_read_req(buf, msgs->addr, msgs->len);
545 		} else {
546 			hid_dbg(hdev, "I2C write %#04x len %d\n",
547 				msgs->addr, msgs->len);
548 			count = cp2112_i2c_write_req(buf, msgs->addr,
549 						     msgs->buf, msgs->len);
550 		}
551 		if (count < 0)
552 			return count;
553 	} else if (dev->hwversion > 1 &&  /* no repeated start in rev 1 */
554 		   num == 2 &&
555 		   msgs[0].addr == msgs[1].addr &&
556 		   !(msgs[0].flags & I2C_M_RD) && (msgs[1].flags & I2C_M_RD)) {
557 		hid_dbg(hdev, "I2C write-read %#04x wlen %d rlen %d\n",
558 			msgs[0].addr, msgs[0].len, msgs[1].len);
559 		read_length = msgs[1].len;
560 		read_buf = msgs[1].buf;
561 		count = cp2112_i2c_write_read_req(buf, msgs[0].addr,
562 				msgs[0].buf, msgs[0].len, msgs[1].len);
563 		if (count < 0)
564 			return count;
565 	} else {
566 		hid_err(hdev,
567 			"Multi-message I2C transactions not supported\n");
568 		return -EOPNOTSUPP;
569 	}
570 
571 	ret = hid_hw_power(hdev, PM_HINT_FULLON);
572 	if (ret < 0) {
573 		hid_err(hdev, "power management error: %d\n", ret);
574 		return ret;
575 	}
576 
577 	ret = cp2112_hid_output(hdev, buf, count, HID_OUTPUT_REPORT);
578 	if (ret < 0) {
579 		hid_warn(hdev, "Error starting transaction: %d\n", ret);
580 		goto power_normal;
581 	}
582 
583 	for (retries = 0; retries < XFER_STATUS_RETRIES; ++retries) {
584 		ret = cp2112_xfer_status(dev);
585 		if (-EBUSY == ret)
586 			continue;
587 		if (ret < 0)
588 			goto power_normal;
589 		break;
590 	}
591 
592 	if (XFER_STATUS_RETRIES <= retries) {
593 		hid_warn(hdev, "Transfer timed out, cancelling.\n");
594 		buf[0] = CP2112_CANCEL_TRANSFER;
595 		buf[1] = 0x01;
596 
597 		ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
598 		if (ret < 0)
599 			hid_warn(hdev, "Error cancelling transaction: %d\n",
600 				 ret);
601 
602 		ret = -ETIMEDOUT;
603 		goto power_normal;
604 	}
605 
606 	for (count = 0; count < read_length;) {
607 		ret = cp2112_read(dev, read_buf + count, read_length - count);
608 		if (ret < 0)
609 			goto power_normal;
610 		if (ret == 0) {
611 			hid_err(hdev, "read returned 0\n");
612 			ret = -EIO;
613 			goto power_normal;
614 		}
615 		count += ret;
616 		if (count > read_length) {
617 			/*
618 			 * The hardware returned too much data.
619 			 * This is mostly harmless because cp2112_read()
620 			 * has a limit check so didn't overrun our
621 			 * buffer.  Nevertheless, we return an error
622 			 * because something is seriously wrong and
623 			 * it shouldn't go unnoticed.
624 			 */
625 			hid_err(hdev, "long read: %d > %zd\n",
626 				ret, read_length - count + ret);
627 			ret = -EIO;
628 			goto power_normal;
629 		}
630 	}
631 
632 	/* return the number of transferred messages */
633 	ret = num;
634 
635 power_normal:
636 	hid_hw_power(hdev, PM_HINT_NORMAL);
637 	hid_dbg(hdev, "I2C transfer finished: %d\n", ret);
638 	return ret;
639 }
640 
cp2112_xfer(struct i2c_adapter * adap,u16 addr,unsigned short flags,char read_write,u8 command,int size,union i2c_smbus_data * data)641 static int cp2112_xfer(struct i2c_adapter *adap, u16 addr,
642 		       unsigned short flags, char read_write, u8 command,
643 		       int size, union i2c_smbus_data *data)
644 {
645 	struct cp2112_device *dev = (struct cp2112_device *)adap->algo_data;
646 	struct hid_device *hdev = dev->hdev;
647 	u8 buf[64];
648 	__le16 word;
649 	ssize_t count;
650 	size_t read_length = 0;
651 	unsigned int retries;
652 	int ret;
653 
654 	hid_dbg(hdev, "%s addr 0x%x flags 0x%x cmd 0x%x size %d\n",
655 		read_write == I2C_SMBUS_WRITE ? "write" : "read",
656 		addr, flags, command, size);
657 
658 	switch (size) {
659 	case I2C_SMBUS_BYTE:
660 		read_length = 1;
661 
662 		if (I2C_SMBUS_READ == read_write)
663 			count = cp2112_read_req(buf, addr, read_length);
664 		else
665 			count = cp2112_write_req(buf, addr, command, NULL,
666 						 0);
667 		break;
668 	case I2C_SMBUS_BYTE_DATA:
669 		read_length = 1;
670 
671 		if (I2C_SMBUS_READ == read_write)
672 			count = cp2112_write_read_req(buf, addr, read_length,
673 						      command, NULL, 0);
674 		else
675 			count = cp2112_write_req(buf, addr, command,
676 						 &data->byte, 1);
677 		break;
678 	case I2C_SMBUS_WORD_DATA:
679 		read_length = 2;
680 		word = cpu_to_le16(data->word);
681 
682 		if (I2C_SMBUS_READ == read_write)
683 			count = cp2112_write_read_req(buf, addr, read_length,
684 						      command, NULL, 0);
685 		else
686 			count = cp2112_write_req(buf, addr, command,
687 						 (u8 *)&word, 2);
688 		break;
689 	case I2C_SMBUS_PROC_CALL:
690 		size = I2C_SMBUS_WORD_DATA;
691 		read_write = I2C_SMBUS_READ;
692 		read_length = 2;
693 		word = cpu_to_le16(data->word);
694 
695 		count = cp2112_write_read_req(buf, addr, read_length, command,
696 					      (u8 *)&word, 2);
697 		break;
698 	case I2C_SMBUS_I2C_BLOCK_DATA:
699 		if (read_write == I2C_SMBUS_READ) {
700 			read_length = data->block[0];
701 			count = cp2112_write_read_req(buf, addr, read_length,
702 						      command, NULL, 0);
703 		} else {
704 			count = cp2112_write_req(buf, addr, command,
705 						 data->block + 1,
706 						 data->block[0]);
707 		}
708 		break;
709 	case I2C_SMBUS_BLOCK_DATA:
710 		if (I2C_SMBUS_READ == read_write) {
711 			count = cp2112_write_read_req(buf, addr,
712 						      I2C_SMBUS_BLOCK_MAX,
713 						      command, NULL, 0);
714 		} else {
715 			count = cp2112_write_req(buf, addr, command,
716 						 data->block,
717 						 data->block[0] + 1);
718 		}
719 		break;
720 	case I2C_SMBUS_BLOCK_PROC_CALL:
721 		size = I2C_SMBUS_BLOCK_DATA;
722 		read_write = I2C_SMBUS_READ;
723 
724 		count = cp2112_write_read_req(buf, addr, I2C_SMBUS_BLOCK_MAX,
725 					      command, data->block,
726 					      data->block[0] + 1);
727 		break;
728 	default:
729 		hid_warn(hdev, "Unsupported transaction %d\n", size);
730 		return -EOPNOTSUPP;
731 	}
732 
733 	if (count < 0)
734 		return count;
735 
736 	ret = hid_hw_power(hdev, PM_HINT_FULLON);
737 	if (ret < 0) {
738 		hid_err(hdev, "power management error: %d\n", ret);
739 		return ret;
740 	}
741 
742 	ret = cp2112_hid_output(hdev, buf, count, HID_OUTPUT_REPORT);
743 	if (ret < 0) {
744 		hid_warn(hdev, "Error starting transaction: %d\n", ret);
745 		goto power_normal;
746 	}
747 
748 	for (retries = 0; retries < XFER_STATUS_RETRIES; ++retries) {
749 		ret = cp2112_xfer_status(dev);
750 		if (-EBUSY == ret)
751 			continue;
752 		if (ret < 0)
753 			goto power_normal;
754 		break;
755 	}
756 
757 	if (XFER_STATUS_RETRIES <= retries) {
758 		hid_warn(hdev, "Transfer timed out, cancelling.\n");
759 		buf[0] = CP2112_CANCEL_TRANSFER;
760 		buf[1] = 0x01;
761 
762 		ret = cp2112_hid_output(hdev, buf, 2, HID_OUTPUT_REPORT);
763 		if (ret < 0)
764 			hid_warn(hdev, "Error cancelling transaction: %d\n",
765 				 ret);
766 
767 		ret = -ETIMEDOUT;
768 		goto power_normal;
769 	}
770 
771 	if (I2C_SMBUS_WRITE == read_write) {
772 		ret = 0;
773 		goto power_normal;
774 	}
775 
776 	if (I2C_SMBUS_BLOCK_DATA == size)
777 		read_length = ret;
778 
779 	ret = cp2112_read(dev, buf, read_length);
780 	if (ret < 0)
781 		goto power_normal;
782 	if (ret != read_length) {
783 		hid_warn(hdev, "short read: %d < %zd\n", ret, read_length);
784 		ret = -EIO;
785 		goto power_normal;
786 	}
787 
788 	switch (size) {
789 	case I2C_SMBUS_BYTE:
790 	case I2C_SMBUS_BYTE_DATA:
791 		data->byte = buf[0];
792 		break;
793 	case I2C_SMBUS_WORD_DATA:
794 		data->word = le16_to_cpup((__le16 *)buf);
795 		break;
796 	case I2C_SMBUS_I2C_BLOCK_DATA:
797 		if (read_length > I2C_SMBUS_BLOCK_MAX) {
798 			ret = -EINVAL;
799 			goto power_normal;
800 		}
801 
802 		memcpy(data->block + 1, buf, read_length);
803 		break;
804 	case I2C_SMBUS_BLOCK_DATA:
805 		if (read_length > I2C_SMBUS_BLOCK_MAX) {
806 			ret = -EPROTO;
807 			goto power_normal;
808 		}
809 
810 		memcpy(data->block, buf, read_length);
811 		break;
812 	}
813 
814 	ret = 0;
815 power_normal:
816 	hid_hw_power(hdev, PM_HINT_NORMAL);
817 	hid_dbg(hdev, "transfer finished: %d\n", ret);
818 	return ret;
819 }
820 
cp2112_functionality(struct i2c_adapter * adap)821 static u32 cp2112_functionality(struct i2c_adapter *adap)
822 {
823 	return I2C_FUNC_I2C |
824 		I2C_FUNC_SMBUS_BYTE |
825 		I2C_FUNC_SMBUS_BYTE_DATA |
826 		I2C_FUNC_SMBUS_WORD_DATA |
827 		I2C_FUNC_SMBUS_BLOCK_DATA |
828 		I2C_FUNC_SMBUS_I2C_BLOCK |
829 		I2C_FUNC_SMBUS_PROC_CALL |
830 		I2C_FUNC_SMBUS_BLOCK_PROC_CALL;
831 }
832 
833 static const struct i2c_algorithm smbus_algorithm = {
834 	.master_xfer	= cp2112_i2c_xfer,
835 	.smbus_xfer	= cp2112_xfer,
836 	.functionality	= cp2112_functionality,
837 };
838 
cp2112_get_usb_config(struct hid_device * hdev,struct cp2112_usb_config_report * cfg)839 static int cp2112_get_usb_config(struct hid_device *hdev,
840 				 struct cp2112_usb_config_report *cfg)
841 {
842 	int ret;
843 
844 	ret = cp2112_hid_get(hdev, CP2112_USB_CONFIG, (u8 *)cfg, sizeof(*cfg),
845 			     HID_FEATURE_REPORT);
846 	if (ret != sizeof(*cfg)) {
847 		hid_err(hdev, "error reading usb config: %d\n", ret);
848 		if (ret < 0)
849 			return ret;
850 		return -EIO;
851 	}
852 
853 	return 0;
854 }
855 
cp2112_set_usb_config(struct hid_device * hdev,struct cp2112_usb_config_report * cfg)856 static int cp2112_set_usb_config(struct hid_device *hdev,
857 				 struct cp2112_usb_config_report *cfg)
858 {
859 	int ret;
860 
861 	BUG_ON(cfg->report != CP2112_USB_CONFIG);
862 
863 	ret = cp2112_hid_output(hdev, (u8 *)cfg, sizeof(*cfg),
864 				HID_FEATURE_REPORT);
865 	if (ret != sizeof(*cfg)) {
866 		hid_err(hdev, "error writing usb config: %d\n", ret);
867 		if (ret < 0)
868 			return ret;
869 		return -EIO;
870 	}
871 
872 	return 0;
873 }
874 
875 static void chmod_sysfs_attrs(struct hid_device *hdev);
876 
877 #define CP2112_CONFIG_ATTR(name, store, format, ...) \
878 static ssize_t name##_store(struct device *kdev, \
879 			    struct device_attribute *attr, const char *buf, \
880 			    size_t count) \
881 { \
882 	struct hid_device *hdev = to_hid_device(kdev); \
883 	struct cp2112_usb_config_report cfg; \
884 	int ret = cp2112_get_usb_config(hdev, &cfg); \
885 	if (ret) \
886 		return ret; \
887 	store; \
888 	ret = cp2112_set_usb_config(hdev, &cfg); \
889 	if (ret) \
890 		return ret; \
891 	chmod_sysfs_attrs(hdev); \
892 	return count; \
893 } \
894 static ssize_t name##_show(struct device *kdev, \
895 			   struct device_attribute *attr, char *buf) \
896 { \
897 	struct hid_device *hdev = to_hid_device(kdev); \
898 	struct cp2112_usb_config_report cfg; \
899 	int ret = cp2112_get_usb_config(hdev, &cfg); \
900 	if (ret) \
901 		return ret; \
902 	return scnprintf(buf, PAGE_SIZE, format, ##__VA_ARGS__); \
903 } \
904 static DEVICE_ATTR_RW(name);
905 
906 CP2112_CONFIG_ATTR(vendor_id, ({
907 	u16 vid;
908 
909 	if (sscanf(buf, "%hi", &vid) != 1)
910 		return -EINVAL;
911 
912 	cfg.vid = cpu_to_le16(vid);
913 	cfg.mask = 0x01;
914 }), "0x%04x\n", le16_to_cpu(cfg.vid));
915 
916 CP2112_CONFIG_ATTR(product_id, ({
917 	u16 pid;
918 
919 	if (sscanf(buf, "%hi", &pid) != 1)
920 		return -EINVAL;
921 
922 	cfg.pid = cpu_to_le16(pid);
923 	cfg.mask = 0x02;
924 }), "0x%04x\n", le16_to_cpu(cfg.pid));
925 
926 CP2112_CONFIG_ATTR(max_power, ({
927 	int mA;
928 
929 	if (sscanf(buf, "%i", &mA) != 1)
930 		return -EINVAL;
931 
932 	cfg.max_power = (mA + 1) / 2;
933 	cfg.mask = 0x04;
934 }), "%u mA\n", cfg.max_power * 2);
935 
936 CP2112_CONFIG_ATTR(power_mode, ({
937 	if (sscanf(buf, "%hhi", &cfg.power_mode) != 1)
938 		return -EINVAL;
939 
940 	cfg.mask = 0x08;
941 }), "%u\n", cfg.power_mode);
942 
943 CP2112_CONFIG_ATTR(release_version, ({
944 	if (sscanf(buf, "%hhi.%hhi", &cfg.release_major, &cfg.release_minor)
945 	    != 2)
946 		return -EINVAL;
947 
948 	cfg.mask = 0x10;
949 }), "%u.%u\n", cfg.release_major, cfg.release_minor);
950 
951 #undef CP2112_CONFIG_ATTR
952 
953 struct cp2112_pstring_attribute {
954 	struct device_attribute attr;
955 	unsigned char report;
956 };
957 
pstr_store(struct device * kdev,struct device_attribute * kattr,const char * buf,size_t count)958 static ssize_t pstr_store(struct device *kdev,
959 			  struct device_attribute *kattr, const char *buf,
960 			  size_t count)
961 {
962 	struct hid_device *hdev = to_hid_device(kdev);
963 	struct cp2112_pstring_attribute *attr =
964 		container_of(kattr, struct cp2112_pstring_attribute, attr);
965 	struct cp2112_string_report report;
966 	int ret;
967 
968 	memset(&report, 0, sizeof(report));
969 
970 	ret = utf8s_to_utf16s(buf, count, UTF16_LITTLE_ENDIAN,
971 			      report.string, ARRAY_SIZE(report.string));
972 	report.report = attr->report;
973 	report.length = ret * sizeof(report.string[0]) + 2;
974 	report.type = USB_DT_STRING;
975 
976 	ret = cp2112_hid_output(hdev, &report.report, report.length + 1,
977 				HID_FEATURE_REPORT);
978 	if (ret != report.length + 1) {
979 		hid_err(hdev, "error writing %s string: %d\n", kattr->attr.name,
980 			ret);
981 		if (ret < 0)
982 			return ret;
983 		return -EIO;
984 	}
985 
986 	chmod_sysfs_attrs(hdev);
987 	return count;
988 }
989 
pstr_show(struct device * kdev,struct device_attribute * kattr,char * buf)990 static ssize_t pstr_show(struct device *kdev,
991 			 struct device_attribute *kattr, char *buf)
992 {
993 	struct hid_device *hdev = to_hid_device(kdev);
994 	struct cp2112_pstring_attribute *attr =
995 		container_of(kattr, struct cp2112_pstring_attribute, attr);
996 	struct cp2112_string_report report;
997 	u8 length;
998 	int ret;
999 
1000 	ret = cp2112_hid_get(hdev, attr->report, &report.report,
1001 			     sizeof(report) - 1, HID_FEATURE_REPORT);
1002 	if (ret < 3) {
1003 		hid_err(hdev, "error reading %s string: %d\n", kattr->attr.name,
1004 			ret);
1005 		if (ret < 0)
1006 			return ret;
1007 		return -EIO;
1008 	}
1009 
1010 	if (report.length < 2) {
1011 		hid_err(hdev, "invalid %s string length: %d\n",
1012 			kattr->attr.name, report.length);
1013 		return -EIO;
1014 	}
1015 
1016 	length = report.length > ret - 1 ? ret - 1 : report.length;
1017 	length = (length - 2) / sizeof(report.string[0]);
1018 	ret = utf16s_to_utf8s(report.string, length, UTF16_LITTLE_ENDIAN, buf,
1019 			      PAGE_SIZE - 1);
1020 	buf[ret++] = '\n';
1021 	return ret;
1022 }
1023 
1024 #define CP2112_PSTR_ATTR(name, _report) \
1025 static struct cp2112_pstring_attribute dev_attr_##name = { \
1026 	.attr = __ATTR(name, (S_IWUSR | S_IRUGO), pstr_show, pstr_store), \
1027 	.report = _report, \
1028 };
1029 
1030 CP2112_PSTR_ATTR(manufacturer,	CP2112_MANUFACTURER_STRING);
1031 CP2112_PSTR_ATTR(product,	CP2112_PRODUCT_STRING);
1032 CP2112_PSTR_ATTR(serial,	CP2112_SERIAL_STRING);
1033 
1034 #undef CP2112_PSTR_ATTR
1035 
1036 static const struct attribute_group cp2112_attr_group = {
1037 	.attrs = (struct attribute *[]){
1038 		&dev_attr_vendor_id.attr,
1039 		&dev_attr_product_id.attr,
1040 		&dev_attr_max_power.attr,
1041 		&dev_attr_power_mode.attr,
1042 		&dev_attr_release_version.attr,
1043 		&dev_attr_manufacturer.attr.attr,
1044 		&dev_attr_product.attr.attr,
1045 		&dev_attr_serial.attr.attr,
1046 		NULL
1047 	}
1048 };
1049 
1050 /* Chmoding our sysfs attributes is simply a way to expose which fields in the
1051  * PROM have already been programmed. We do not depend on this preventing
1052  * writing to these attributes since the CP2112 will simply ignore writes to
1053  * already-programmed fields. This is why there is no sense in fixing this
1054  * racy behaviour.
1055  */
chmod_sysfs_attrs(struct hid_device * hdev)1056 static void chmod_sysfs_attrs(struct hid_device *hdev)
1057 {
1058 	struct attribute **attr;
1059 	u8 buf[2];
1060 	int ret;
1061 
1062 	ret = cp2112_hid_get(hdev, CP2112_LOCK_BYTE, buf, sizeof(buf),
1063 			     HID_FEATURE_REPORT);
1064 	if (ret != sizeof(buf)) {
1065 		hid_err(hdev, "error reading lock byte: %d\n", ret);
1066 		return;
1067 	}
1068 
1069 	for (attr = cp2112_attr_group.attrs; *attr; ++attr) {
1070 		umode_t mode = (buf[1] & 1) ? S_IWUSR | S_IRUGO : S_IRUGO;
1071 		ret = sysfs_chmod_file(&hdev->dev.kobj, *attr, mode);
1072 		if (ret < 0)
1073 			hid_err(hdev, "error chmoding sysfs file %s\n",
1074 				(*attr)->name);
1075 		buf[1] >>= 1;
1076 	}
1077 }
1078 
cp2112_gpio_irq_ack(struct irq_data * d)1079 static void cp2112_gpio_irq_ack(struct irq_data *d)
1080 {
1081 }
1082 
cp2112_gpio_irq_mask(struct irq_data * d)1083 static void cp2112_gpio_irq_mask(struct irq_data *d)
1084 {
1085 	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1086 	struct cp2112_device *dev = gpiochip_get_data(gc);
1087 
1088 	__clear_bit(d->hwirq, &dev->irq_mask);
1089 }
1090 
cp2112_gpio_irq_unmask(struct irq_data * d)1091 static void cp2112_gpio_irq_unmask(struct irq_data *d)
1092 {
1093 	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1094 	struct cp2112_device *dev = gpiochip_get_data(gc);
1095 
1096 	__set_bit(d->hwirq, &dev->irq_mask);
1097 }
1098 
cp2112_gpio_poll_callback(struct work_struct * work)1099 static void cp2112_gpio_poll_callback(struct work_struct *work)
1100 {
1101 	struct cp2112_device *dev = container_of(work, struct cp2112_device,
1102 						 gpio_poll_worker.work);
1103 	struct irq_data *d;
1104 	u8 gpio_mask;
1105 	u8 virqs = (u8)dev->irq_mask;
1106 	u32 irq_type;
1107 	int irq, virq, ret;
1108 
1109 	ret = cp2112_gpio_get_all(&dev->gc);
1110 	if (ret == -ENODEV) /* the hardware has been disconnected */
1111 		return;
1112 	if (ret < 0)
1113 		goto exit;
1114 
1115 	gpio_mask = ret;
1116 
1117 	while (virqs) {
1118 		virq = ffs(virqs) - 1;
1119 		virqs &= ~BIT(virq);
1120 
1121 		if (!dev->gc.to_irq)
1122 			break;
1123 
1124 		irq = dev->gc.to_irq(&dev->gc, virq);
1125 
1126 		d = irq_get_irq_data(irq);
1127 		if (!d)
1128 			continue;
1129 
1130 		irq_type = irqd_get_trigger_type(d);
1131 
1132 		if (gpio_mask & BIT(virq)) {
1133 			/* Level High */
1134 
1135 			if (irq_type & IRQ_TYPE_LEVEL_HIGH)
1136 				handle_nested_irq(irq);
1137 
1138 			if ((irq_type & IRQ_TYPE_EDGE_RISING) &&
1139 			    !(dev->gpio_prev_state & BIT(virq)))
1140 				handle_nested_irq(irq);
1141 		} else {
1142 			/* Level Low */
1143 
1144 			if (irq_type & IRQ_TYPE_LEVEL_LOW)
1145 				handle_nested_irq(irq);
1146 
1147 			if ((irq_type & IRQ_TYPE_EDGE_FALLING) &&
1148 			    (dev->gpio_prev_state & BIT(virq)))
1149 				handle_nested_irq(irq);
1150 		}
1151 	}
1152 
1153 	dev->gpio_prev_state = gpio_mask;
1154 
1155 exit:
1156 	if (dev->gpio_poll)
1157 		schedule_delayed_work(&dev->gpio_poll_worker, 10);
1158 }
1159 
1160 
cp2112_gpio_irq_startup(struct irq_data * d)1161 static unsigned int cp2112_gpio_irq_startup(struct irq_data *d)
1162 {
1163 	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1164 	struct cp2112_device *dev = gpiochip_get_data(gc);
1165 
1166 	INIT_DELAYED_WORK(&dev->gpio_poll_worker, cp2112_gpio_poll_callback);
1167 
1168 	if (!dev->gpio_poll) {
1169 		dev->gpio_poll = true;
1170 		schedule_delayed_work(&dev->gpio_poll_worker, 0);
1171 	}
1172 
1173 	cp2112_gpio_irq_unmask(d);
1174 	return 0;
1175 }
1176 
cp2112_gpio_irq_shutdown(struct irq_data * d)1177 static void cp2112_gpio_irq_shutdown(struct irq_data *d)
1178 {
1179 	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
1180 	struct cp2112_device *dev = gpiochip_get_data(gc);
1181 
1182 	cancel_delayed_work_sync(&dev->gpio_poll_worker);
1183 }
1184 
cp2112_gpio_irq_type(struct irq_data * d,unsigned int type)1185 static int cp2112_gpio_irq_type(struct irq_data *d, unsigned int type)
1186 {
1187 	return 0;
1188 }
1189 
1190 static struct irq_chip cp2112_gpio_irqchip = {
1191 	.name = "cp2112-gpio",
1192 	.irq_startup = cp2112_gpio_irq_startup,
1193 	.irq_shutdown = cp2112_gpio_irq_shutdown,
1194 	.irq_ack = cp2112_gpio_irq_ack,
1195 	.irq_mask = cp2112_gpio_irq_mask,
1196 	.irq_unmask = cp2112_gpio_irq_unmask,
1197 	.irq_set_type = cp2112_gpio_irq_type,
1198 };
1199 
cp2112_allocate_irq(struct cp2112_device * dev,int pin)1200 static int __maybe_unused cp2112_allocate_irq(struct cp2112_device *dev,
1201 					      int pin)
1202 {
1203 	int ret;
1204 
1205 	if (dev->desc[pin])
1206 		return -EINVAL;
1207 
1208 	dev->desc[pin] = gpiochip_request_own_desc(&dev->gc, pin,
1209 						   "HID/I2C:Event");
1210 	if (IS_ERR(dev->desc[pin])) {
1211 		dev_err(dev->gc.parent, "Failed to request GPIO\n");
1212 		return PTR_ERR(dev->desc[pin]);
1213 	}
1214 
1215 	ret = cp2112_gpio_direction_input(&dev->gc, pin);
1216 	if (ret < 0) {
1217 		dev_err(dev->gc.parent, "Failed to set GPIO to input dir\n");
1218 		goto err_desc;
1219 	}
1220 
1221 	ret = gpiochip_lock_as_irq(&dev->gc, pin);
1222 	if (ret) {
1223 		dev_err(dev->gc.parent, "Failed to lock GPIO as interrupt\n");
1224 		goto err_desc;
1225 	}
1226 
1227 	ret = gpiod_to_irq(dev->desc[pin]);
1228 	if (ret < 0) {
1229 		dev_err(dev->gc.parent, "Failed to translate GPIO to IRQ\n");
1230 		goto err_lock;
1231 	}
1232 
1233 	return ret;
1234 
1235 err_lock:
1236 	gpiochip_unlock_as_irq(&dev->gc, pin);
1237 err_desc:
1238 	gpiochip_free_own_desc(dev->desc[pin]);
1239 	dev->desc[pin] = NULL;
1240 	return ret;
1241 }
1242 
cp2112_probe(struct hid_device * hdev,const struct hid_device_id * id)1243 static int cp2112_probe(struct hid_device *hdev, const struct hid_device_id *id)
1244 {
1245 	struct cp2112_device *dev;
1246 	u8 buf[3];
1247 	struct cp2112_smbus_config_report config;
1248 	int ret;
1249 
1250 	dev = devm_kzalloc(&hdev->dev, sizeof(*dev), GFP_KERNEL);
1251 	if (!dev)
1252 		return -ENOMEM;
1253 
1254 	dev->in_out_buffer = devm_kzalloc(&hdev->dev, CP2112_REPORT_MAX_LENGTH,
1255 					  GFP_KERNEL);
1256 	if (!dev->in_out_buffer)
1257 		return -ENOMEM;
1258 
1259 	mutex_init(&dev->lock);
1260 
1261 	ret = hid_parse(hdev);
1262 	if (ret) {
1263 		hid_err(hdev, "parse failed\n");
1264 		return ret;
1265 	}
1266 
1267 	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
1268 	if (ret) {
1269 		hid_err(hdev, "hw start failed\n");
1270 		return ret;
1271 	}
1272 
1273 	ret = hid_hw_open(hdev);
1274 	if (ret) {
1275 		hid_err(hdev, "hw open failed\n");
1276 		goto err_hid_stop;
1277 	}
1278 
1279 	ret = hid_hw_power(hdev, PM_HINT_FULLON);
1280 	if (ret < 0) {
1281 		hid_err(hdev, "power management error: %d\n", ret);
1282 		goto err_hid_close;
1283 	}
1284 
1285 	ret = cp2112_hid_get(hdev, CP2112_GET_VERSION_INFO, buf, sizeof(buf),
1286 			     HID_FEATURE_REPORT);
1287 	if (ret != sizeof(buf)) {
1288 		hid_err(hdev, "error requesting version\n");
1289 		if (ret >= 0)
1290 			ret = -EIO;
1291 		goto err_power_normal;
1292 	}
1293 
1294 	hid_info(hdev, "Part Number: 0x%02X Device Version: 0x%02X\n",
1295 		 buf[1], buf[2]);
1296 
1297 	ret = cp2112_hid_get(hdev, CP2112_SMBUS_CONFIG, (u8 *)&config,
1298 			     sizeof(config), HID_FEATURE_REPORT);
1299 	if (ret != sizeof(config)) {
1300 		hid_err(hdev, "error requesting SMBus config\n");
1301 		if (ret >= 0)
1302 			ret = -EIO;
1303 		goto err_power_normal;
1304 	}
1305 
1306 	config.retry_time = cpu_to_be16(1);
1307 
1308 	ret = cp2112_hid_output(hdev, (u8 *)&config, sizeof(config),
1309 				HID_FEATURE_REPORT);
1310 	if (ret != sizeof(config)) {
1311 		hid_err(hdev, "error setting SMBus config\n");
1312 		if (ret >= 0)
1313 			ret = -EIO;
1314 		goto err_power_normal;
1315 	}
1316 
1317 	hid_set_drvdata(hdev, (void *)dev);
1318 	dev->hdev		= hdev;
1319 	dev->adap.owner		= THIS_MODULE;
1320 	dev->adap.class		= I2C_CLASS_HWMON;
1321 	dev->adap.algo		= &smbus_algorithm;
1322 	dev->adap.algo_data	= dev;
1323 	dev->adap.dev.parent	= &hdev->dev;
1324 	snprintf(dev->adap.name, sizeof(dev->adap.name),
1325 		 "CP2112 SMBus Bridge on hidraw%d",
1326 		 ((struct hidraw *)hdev->hidraw)->minor);
1327 	dev->hwversion = buf[2];
1328 	init_waitqueue_head(&dev->wait);
1329 
1330 	hid_device_io_start(hdev);
1331 	ret = i2c_add_adapter(&dev->adap);
1332 	hid_device_io_stop(hdev);
1333 
1334 	if (ret) {
1335 		hid_err(hdev, "error registering i2c adapter\n");
1336 		goto err_power_normal;
1337 	}
1338 
1339 	hid_dbg(hdev, "adapter registered\n");
1340 
1341 	dev->gc.label			= "cp2112_gpio";
1342 	dev->gc.direction_input		= cp2112_gpio_direction_input;
1343 	dev->gc.direction_output	= cp2112_gpio_direction_output;
1344 	dev->gc.set			= cp2112_gpio_set;
1345 	dev->gc.get			= cp2112_gpio_get;
1346 	dev->gc.base			= -1;
1347 	dev->gc.ngpio			= 8;
1348 	dev->gc.can_sleep		= 1;
1349 	dev->gc.parent			= &hdev->dev;
1350 
1351 	ret = gpiochip_add_data(&dev->gc, dev);
1352 	if (ret < 0) {
1353 		hid_err(hdev, "error registering gpio chip\n");
1354 		goto err_free_i2c;
1355 	}
1356 
1357 	ret = sysfs_create_group(&hdev->dev.kobj, &cp2112_attr_group);
1358 	if (ret < 0) {
1359 		hid_err(hdev, "error creating sysfs attrs\n");
1360 		goto err_gpiochip_remove;
1361 	}
1362 
1363 	chmod_sysfs_attrs(hdev);
1364 	hid_hw_power(hdev, PM_HINT_NORMAL);
1365 
1366 	ret = gpiochip_irqchip_add(&dev->gc, &cp2112_gpio_irqchip, 0,
1367 				   handle_simple_irq, IRQ_TYPE_NONE);
1368 	if (ret) {
1369 		dev_err(dev->gc.parent, "failed to add IRQ chip\n");
1370 		goto err_sysfs_remove;
1371 	}
1372 
1373 	return ret;
1374 
1375 err_sysfs_remove:
1376 	sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
1377 err_gpiochip_remove:
1378 	gpiochip_remove(&dev->gc);
1379 err_free_i2c:
1380 	i2c_del_adapter(&dev->adap);
1381 err_power_normal:
1382 	hid_hw_power(hdev, PM_HINT_NORMAL);
1383 err_hid_close:
1384 	hid_hw_close(hdev);
1385 err_hid_stop:
1386 	hid_hw_stop(hdev);
1387 	return ret;
1388 }
1389 
cp2112_remove(struct hid_device * hdev)1390 static void cp2112_remove(struct hid_device *hdev)
1391 {
1392 	struct cp2112_device *dev = hid_get_drvdata(hdev);
1393 	int i;
1394 
1395 	sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
1396 	i2c_del_adapter(&dev->adap);
1397 
1398 	if (dev->gpio_poll) {
1399 		dev->gpio_poll = false;
1400 		cancel_delayed_work_sync(&dev->gpio_poll_worker);
1401 	}
1402 
1403 	for (i = 0; i < ARRAY_SIZE(dev->desc); i++) {
1404 		gpiochip_unlock_as_irq(&dev->gc, i);
1405 		gpiochip_free_own_desc(dev->desc[i]);
1406 	}
1407 
1408 	gpiochip_remove(&dev->gc);
1409 	/* i2c_del_adapter has finished removing all i2c devices from our
1410 	 * adapter. Well behaved devices should no longer call our cp2112_xfer
1411 	 * and should have waited for any pending calls to finish. It has also
1412 	 * waited for device_unregister(&adap->dev) to complete. Therefore we
1413 	 * can safely free our struct cp2112_device.
1414 	 */
1415 	hid_hw_close(hdev);
1416 	hid_hw_stop(hdev);
1417 }
1418 
cp2112_raw_event(struct hid_device * hdev,struct hid_report * report,u8 * data,int size)1419 static int cp2112_raw_event(struct hid_device *hdev, struct hid_report *report,
1420 			    u8 *data, int size)
1421 {
1422 	struct cp2112_device *dev = hid_get_drvdata(hdev);
1423 	struct cp2112_xfer_status_report *xfer = (void *)data;
1424 
1425 	switch (data[0]) {
1426 	case CP2112_TRANSFER_STATUS_RESPONSE:
1427 		hid_dbg(hdev, "xfer status: %02x %02x %04x %04x\n",
1428 			xfer->status0, xfer->status1,
1429 			be16_to_cpu(xfer->retries), be16_to_cpu(xfer->length));
1430 
1431 		switch (xfer->status0) {
1432 		case STATUS0_IDLE:
1433 			dev->xfer_status = -EAGAIN;
1434 			break;
1435 		case STATUS0_BUSY:
1436 			dev->xfer_status = -EBUSY;
1437 			break;
1438 		case STATUS0_COMPLETE:
1439 			dev->xfer_status = be16_to_cpu(xfer->length);
1440 			break;
1441 		case STATUS0_ERROR:
1442 			switch (xfer->status1) {
1443 			case STATUS1_TIMEOUT_NACK:
1444 			case STATUS1_TIMEOUT_BUS:
1445 				dev->xfer_status = -ETIMEDOUT;
1446 				break;
1447 			default:
1448 				dev->xfer_status = -EIO;
1449 				break;
1450 			}
1451 			break;
1452 		default:
1453 			dev->xfer_status = -EINVAL;
1454 			break;
1455 		}
1456 
1457 		atomic_set(&dev->xfer_avail, 1);
1458 		break;
1459 	case CP2112_DATA_READ_RESPONSE:
1460 		hid_dbg(hdev, "read response: %02x %02x\n", data[1], data[2]);
1461 
1462 		dev->read_length = data[2];
1463 		if (dev->read_length > sizeof(dev->read_data))
1464 			dev->read_length = sizeof(dev->read_data);
1465 
1466 		memcpy(dev->read_data, &data[3], dev->read_length);
1467 		atomic_set(&dev->read_avail, 1);
1468 		break;
1469 	default:
1470 		hid_err(hdev, "unknown report\n");
1471 
1472 		return 0;
1473 	}
1474 
1475 	wake_up_interruptible(&dev->wait);
1476 	return 1;
1477 }
1478 
1479 static struct hid_driver cp2112_driver = {
1480 	.name		= "cp2112",
1481 	.id_table	= cp2112_devices,
1482 	.probe		= cp2112_probe,
1483 	.remove		= cp2112_remove,
1484 	.raw_event	= cp2112_raw_event,
1485 };
1486 
1487 module_hid_driver(cp2112_driver);
1488 MODULE_DESCRIPTION("Silicon Labs HID USB to SMBus master bridge");
1489 MODULE_AUTHOR("David Barksdale <dbarksdale@uplogix.com>");
1490 MODULE_LICENSE("GPL");
1491 
1492