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