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