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