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