Merge tag 'fsnotify_for_v6.5-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git...
[sfrench/cifs-2.6.git] / drivers / usb / typec / ucsi / ucsi_ccg.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * UCSI driver for Cypress CCGx Type-C controller
4  *
5  * Copyright (C) 2017-2018 NVIDIA Corporation. All rights reserved.
6  * Author: Ajay Gupta <ajayg@nvidia.com>
7  *
8  * Some code borrowed from drivers/usb/typec/ucsi/ucsi_acpi.c
9  */
10 #include <linux/acpi.h>
11 #include <linux/delay.h>
12 #include <linux/firmware.h>
13 #include <linux/i2c.h>
14 #include <linux/module.h>
15 #include <linux/pci.h>
16 #include <linux/platform_device.h>
17 #include <linux/pm.h>
18 #include <linux/pm_runtime.h>
19 #include <linux/usb/typec_dp.h>
20
21 #include <asm/unaligned.h>
22 #include "ucsi.h"
23
24 enum enum_fw_mode {
25         BOOT,   /* bootloader */
26         FW1,    /* FW partition-1 (contains secondary fw) */
27         FW2,    /* FW partition-2 (contains primary fw) */
28         FW_INVALID,
29 };
30
31 #define CCGX_RAB_DEVICE_MODE                    0x0000
32 #define CCGX_RAB_INTR_REG                       0x0006
33 #define  DEV_INT                                BIT(0)
34 #define  PORT0_INT                              BIT(1)
35 #define  PORT1_INT                              BIT(2)
36 #define  UCSI_READ_INT                          BIT(7)
37 #define CCGX_RAB_JUMP_TO_BOOT                   0x0007
38 #define  TO_BOOT                                'J'
39 #define  TO_ALT_FW                              'A'
40 #define CCGX_RAB_RESET_REQ                      0x0008
41 #define  RESET_SIG                              'R'
42 #define  CMD_RESET_I2C                          0x0
43 #define  CMD_RESET_DEV                          0x1
44 #define CCGX_RAB_ENTER_FLASHING                 0x000A
45 #define  FLASH_ENTER_SIG                        'P'
46 #define CCGX_RAB_VALIDATE_FW                    0x000B
47 #define CCGX_RAB_FLASH_ROW_RW                   0x000C
48 #define  FLASH_SIG                              'F'
49 #define  FLASH_RD_CMD                           0x0
50 #define  FLASH_WR_CMD                           0x1
51 #define  FLASH_FWCT1_WR_CMD                     0x2
52 #define  FLASH_FWCT2_WR_CMD                     0x3
53 #define  FLASH_FWCT_SIG_WR_CMD                  0x4
54 #define CCGX_RAB_READ_ALL_VER                   0x0010
55 #define CCGX_RAB_READ_FW2_VER                   0x0020
56 #define CCGX_RAB_UCSI_CONTROL                   0x0039
57 #define CCGX_RAB_UCSI_CONTROL_START             BIT(0)
58 #define CCGX_RAB_UCSI_CONTROL_STOP              BIT(1)
59 #define CCGX_RAB_UCSI_DATA_BLOCK(offset)        (0xf000 | ((offset) & 0xff))
60 #define REG_FLASH_RW_MEM        0x0200
61 #define DEV_REG_IDX                             CCGX_RAB_DEVICE_MODE
62 #define CCGX_RAB_PDPORT_ENABLE                  0x002C
63 #define  PDPORT_1               BIT(0)
64 #define  PDPORT_2               BIT(1)
65 #define CCGX_RAB_RESPONSE                       0x007E
66 #define  ASYNC_EVENT                            BIT(7)
67
68 /* CCGx events & async msg codes */
69 #define RESET_COMPLETE          0x80
70 #define EVENT_INDEX             RESET_COMPLETE
71 #define PORT_CONNECT_DET        0x84
72 #define PORT_DISCONNECT_DET     0x85
73 #define ROLE_SWAP_COMPELETE     0x87
74
75 /* ccg firmware */
76 #define CYACD_LINE_SIZE         527
77 #define CCG4_ROW_SIZE           256
78 #define FW1_METADATA_ROW        0x1FF
79 #define FW2_METADATA_ROW        0x1FE
80 #define FW_CFG_TABLE_SIG_SIZE   256
81
82 static int secondary_fw_min_ver = 41;
83
84 enum enum_flash_mode {
85         SECONDARY_BL,   /* update secondary using bootloader */
86         PRIMARY,        /* update primary using secondary */
87         SECONDARY,      /* update secondary using primary */
88         FLASH_NOT_NEEDED,       /* update not required */
89         FLASH_INVALID,
90 };
91
92 static const char * const ccg_fw_names[] = {
93         "ccg_boot.cyacd",
94         "ccg_primary.cyacd",
95         "ccg_secondary.cyacd"
96 };
97
98 struct ccg_dev_info {
99 #define CCG_DEVINFO_FWMODE_SHIFT (0)
100 #define CCG_DEVINFO_FWMODE_MASK (0x3 << CCG_DEVINFO_FWMODE_SHIFT)
101 #define CCG_DEVINFO_PDPORTS_SHIFT (2)
102 #define CCG_DEVINFO_PDPORTS_MASK (0x3 << CCG_DEVINFO_PDPORTS_SHIFT)
103         u8 mode;
104         u8 bl_mode;
105         __le16 silicon_id;
106         __le16 bl_last_row;
107 } __packed;
108
109 struct version_format {
110         __le16 build;
111         u8 patch;
112         u8 ver;
113 #define CCG_VERSION_PATCH(x) ((x) << 16)
114 #define CCG_VERSION(x)  ((x) << 24)
115 #define CCG_VERSION_MIN_SHIFT (0)
116 #define CCG_VERSION_MIN_MASK (0xf << CCG_VERSION_MIN_SHIFT)
117 #define CCG_VERSION_MAJ_SHIFT (4)
118 #define CCG_VERSION_MAJ_MASK (0xf << CCG_VERSION_MAJ_SHIFT)
119 } __packed;
120
121 /*
122  * Firmware version 3.1.10 or earlier, built for NVIDIA has known issue
123  * of missing interrupt when a device is connected for runtime resume
124  */
125 #define CCG_FW_BUILD_NVIDIA     (('n' << 8) | 'v')
126 #define CCG_OLD_FW_VERSION      (CCG_VERSION(0x31) | CCG_VERSION_PATCH(10))
127
128 /* Firmware for Tegra doesn't support UCSI ALT command, built
129  * for NVIDIA has known issue of reporting wrong capability info
130  */
131 #define CCG_FW_BUILD_NVIDIA_TEGRA       (('g' << 8) | 'n')
132
133 /* Altmode offset for NVIDIA Function Test Board (FTB) */
134 #define NVIDIA_FTB_DP_OFFSET    (2)
135 #define NVIDIA_FTB_DBG_OFFSET   (3)
136
137 struct version_info {
138         struct version_format base;
139         struct version_format app;
140 };
141
142 struct fw_config_table {
143         u32 identity;
144         u16 table_size;
145         u8 fwct_version;
146         u8 is_key_change;
147         u8 guid[16];
148         struct version_format base;
149         struct version_format app;
150         u8 primary_fw_digest[32];
151         u32 key_exp_length;
152         u8 key_modulus[256];
153         u8 key_exp[4];
154 };
155
156 /* CCGx response codes */
157 enum ccg_resp_code {
158         CMD_NO_RESP             = 0x00,
159         CMD_SUCCESS             = 0x02,
160         FLASH_DATA_AVAILABLE    = 0x03,
161         CMD_INVALID             = 0x05,
162         FLASH_UPDATE_FAIL       = 0x07,
163         INVALID_FW              = 0x08,
164         INVALID_ARG             = 0x09,
165         CMD_NOT_SUPPORT         = 0x0A,
166         TRANSACTION_FAIL        = 0x0C,
167         PD_CMD_FAIL             = 0x0D,
168         UNDEF_ERROR             = 0x0F,
169         INVALID_RESP            = 0x10,
170 };
171
172 #define CCG_EVENT_MAX   (EVENT_INDEX + 43)
173
174 struct ccg_cmd {
175         u16 reg;
176         u32 data;
177         int len;
178         u32 delay; /* ms delay for cmd timeout  */
179 };
180
181 struct ccg_resp {
182         u8 code;
183         u8 length;
184 };
185
186 struct ucsi_ccg_altmode {
187         u16 svid;
188         u32 mid;
189         u8 linked_idx;
190         u8 active_idx;
191 #define UCSI_MULTI_DP_INDEX     (0xff)
192         bool checked;
193 } __packed;
194
195 struct ucsi_ccg {
196         struct device *dev;
197         struct ucsi *ucsi;
198         struct i2c_client *client;
199
200         struct ccg_dev_info info;
201         /* version info for boot, primary and secondary */
202         struct version_info version[FW2 + 1];
203         u32 fw_version;
204         /* CCG HPI communication flags */
205         unsigned long flags;
206 #define RESET_PENDING   0
207 #define DEV_CMD_PENDING 1
208         struct ccg_resp dev_resp;
209         u8 cmd_resp;
210         int port_num;
211         int irq;
212         struct work_struct work;
213         struct mutex lock; /* to sync between user and driver thread */
214
215         /* fw build with vendor information */
216         u16 fw_build;
217         struct work_struct pm_work;
218
219         struct completion complete;
220
221         u64 last_cmd_sent;
222         bool has_multiple_dp;
223         struct ucsi_ccg_altmode orig[UCSI_MAX_ALTMODES];
224         struct ucsi_ccg_altmode updated[UCSI_MAX_ALTMODES];
225 };
226
227 static int ccg_read(struct ucsi_ccg *uc, u16 rab, u8 *data, u32 len)
228 {
229         struct i2c_client *client = uc->client;
230         const struct i2c_adapter_quirks *quirks = client->adapter->quirks;
231         unsigned char buf[2];
232         struct i2c_msg msgs[] = {
233                 {
234                         .addr   = client->addr,
235                         .flags  = 0x0,
236                         .len    = sizeof(buf),
237                         .buf    = buf,
238                 },
239                 {
240                         .addr   = client->addr,
241                         .flags  = I2C_M_RD,
242                         .buf    = data,
243                 },
244         };
245         u32 rlen, rem_len = len, max_read_len = len;
246         int status;
247
248         /* check any max_read_len limitation on i2c adapter */
249         if (quirks && quirks->max_read_len)
250                 max_read_len = quirks->max_read_len;
251
252         pm_runtime_get_sync(uc->dev);
253         while (rem_len > 0) {
254                 msgs[1].buf = &data[len - rem_len];
255                 rlen = min_t(u16, rem_len, max_read_len);
256                 msgs[1].len = rlen;
257                 put_unaligned_le16(rab, buf);
258                 status = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
259                 if (status < 0) {
260                         dev_err(uc->dev, "i2c_transfer failed %d\n", status);
261                         pm_runtime_put_sync(uc->dev);
262                         return status;
263                 }
264                 rab += rlen;
265                 rem_len -= rlen;
266         }
267
268         pm_runtime_put_sync(uc->dev);
269         return 0;
270 }
271
272 static int ccg_write(struct ucsi_ccg *uc, u16 rab, const u8 *data, u32 len)
273 {
274         struct i2c_client *client = uc->client;
275         unsigned char *buf;
276         struct i2c_msg msgs[] = {
277                 {
278                         .addr   = client->addr,
279                         .flags  = 0x0,
280                 }
281         };
282         int status;
283
284         buf = kzalloc(len + sizeof(rab), GFP_KERNEL);
285         if (!buf)
286                 return -ENOMEM;
287
288         put_unaligned_le16(rab, buf);
289         memcpy(buf + sizeof(rab), data, len);
290
291         msgs[0].len = len + sizeof(rab);
292         msgs[0].buf = buf;
293
294         pm_runtime_get_sync(uc->dev);
295         status = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
296         if (status < 0) {
297                 dev_err(uc->dev, "i2c_transfer failed %d\n", status);
298                 pm_runtime_put_sync(uc->dev);
299                 kfree(buf);
300                 return status;
301         }
302
303         pm_runtime_put_sync(uc->dev);
304         kfree(buf);
305         return 0;
306 }
307
308 static int ucsi_ccg_init(struct ucsi_ccg *uc)
309 {
310         unsigned int count = 10;
311         u8 data;
312         int status;
313
314         data = CCGX_RAB_UCSI_CONTROL_STOP;
315         status = ccg_write(uc, CCGX_RAB_UCSI_CONTROL, &data, sizeof(data));
316         if (status < 0)
317                 return status;
318
319         data = CCGX_RAB_UCSI_CONTROL_START;
320         status = ccg_write(uc, CCGX_RAB_UCSI_CONTROL, &data, sizeof(data));
321         if (status < 0)
322                 return status;
323
324         /*
325          * Flush CCGx RESPONSE queue by acking interrupts. Above ucsi control
326          * register write will push response which must be cleared.
327          */
328         do {
329                 status = ccg_read(uc, CCGX_RAB_INTR_REG, &data, sizeof(data));
330                 if (status < 0)
331                         return status;
332
333                 if (!(data & DEV_INT))
334                         return 0;
335
336                 status = ccg_write(uc, CCGX_RAB_INTR_REG, &data, sizeof(data));
337                 if (status < 0)
338                         return status;
339
340                 usleep_range(10000, 11000);
341         } while (--count);
342
343         return -ETIMEDOUT;
344 }
345
346 static void ucsi_ccg_update_get_current_cam_cmd(struct ucsi_ccg *uc, u8 *data)
347 {
348         u8 cam, new_cam;
349
350         cam = data[0];
351         new_cam = uc->orig[cam].linked_idx;
352         uc->updated[new_cam].active_idx = cam;
353         data[0] = new_cam;
354 }
355
356 static bool ucsi_ccg_update_altmodes(struct ucsi *ucsi,
357                                      struct ucsi_altmode *orig,
358                                      struct ucsi_altmode *updated)
359 {
360         struct ucsi_ccg *uc = ucsi_get_drvdata(ucsi);
361         struct ucsi_ccg_altmode *alt, *new_alt;
362         int i, j, k = 0;
363         bool found = false;
364
365         alt = uc->orig;
366         new_alt = uc->updated;
367         memset(uc->updated, 0, sizeof(uc->updated));
368
369         /*
370          * Copy original connector altmodes to new structure.
371          * We need this before second loop since second loop
372          * checks for duplicate altmodes.
373          */
374         for (i = 0; i < UCSI_MAX_ALTMODES; i++) {
375                 alt[i].svid = orig[i].svid;
376                 alt[i].mid = orig[i].mid;
377                 if (!alt[i].svid)
378                         break;
379         }
380
381         for (i = 0; i < UCSI_MAX_ALTMODES; i++) {
382                 if (!alt[i].svid)
383                         break;
384
385                 /* already checked and considered */
386                 if (alt[i].checked)
387                         continue;
388
389                 if (!DP_CONF_GET_PIN_ASSIGN(alt[i].mid)) {
390                         /* Found Non DP altmode */
391                         new_alt[k].svid = alt[i].svid;
392                         new_alt[k].mid |= alt[i].mid;
393                         new_alt[k].linked_idx = i;
394                         alt[i].linked_idx = k;
395                         updated[k].svid = new_alt[k].svid;
396                         updated[k].mid = new_alt[k].mid;
397                         k++;
398                         continue;
399                 }
400
401                 for (j = i + 1; j < UCSI_MAX_ALTMODES; j++) {
402                         if (alt[i].svid != alt[j].svid ||
403                             !DP_CONF_GET_PIN_ASSIGN(alt[j].mid)) {
404                                 continue;
405                         } else {
406                                 /* Found duplicate DP mode */
407                                 new_alt[k].svid = alt[i].svid;
408                                 new_alt[k].mid |= alt[i].mid | alt[j].mid;
409                                 new_alt[k].linked_idx = UCSI_MULTI_DP_INDEX;
410                                 alt[i].linked_idx = k;
411                                 alt[j].linked_idx = k;
412                                 alt[j].checked = true;
413                                 found = true;
414                         }
415                 }
416                 if (found) {
417                         uc->has_multiple_dp = true;
418                 } else {
419                         /* Didn't find any duplicate DP altmode */
420                         new_alt[k].svid = alt[i].svid;
421                         new_alt[k].mid |= alt[i].mid;
422                         new_alt[k].linked_idx = i;
423                         alt[i].linked_idx = k;
424                 }
425                 updated[k].svid = new_alt[k].svid;
426                 updated[k].mid = new_alt[k].mid;
427                 k++;
428         }
429         return found;
430 }
431
432 static void ucsi_ccg_update_set_new_cam_cmd(struct ucsi_ccg *uc,
433                                             struct ucsi_connector *con,
434                                             u64 *cmd)
435 {
436         struct ucsi_ccg_altmode *new_port, *port;
437         struct typec_altmode *alt = NULL;
438         u8 new_cam, cam, pin;
439         bool enter_new_mode;
440         int i, j, k = 0xff;
441
442         port = uc->orig;
443         new_cam = UCSI_SET_NEW_CAM_GET_AM(*cmd);
444         new_port = &uc->updated[new_cam];
445         cam = new_port->linked_idx;
446         enter_new_mode = UCSI_SET_NEW_CAM_ENTER(*cmd);
447
448         /*
449          * If CAM is UCSI_MULTI_DP_INDEX then this is DP altmode
450          * with multiple DP mode. Find out CAM for best pin assignment
451          * among all DP mode. Priorite pin E->D->C after making sure
452          * the partner supports that pin.
453          */
454         if (cam == UCSI_MULTI_DP_INDEX) {
455                 if (enter_new_mode) {
456                         for (i = 0; con->partner_altmode[i]; i++) {
457                                 alt = con->partner_altmode[i];
458                                 if (alt->svid == new_port->svid)
459                                         break;
460                         }
461                         /*
462                          * alt will always be non NULL since this is
463                          * UCSI_SET_NEW_CAM command and so there will be
464                          * at least one con->partner_altmode[i] with svid
465                          * matching with new_port->svid.
466                          */
467                         for (j = 0; port[j].svid; j++) {
468                                 pin = DP_CONF_GET_PIN_ASSIGN(port[j].mid);
469                                 if (alt && port[j].svid == alt->svid &&
470                                     (pin & DP_CONF_GET_PIN_ASSIGN(alt->vdo))) {
471                                         /* prioritize pin E->D->C */
472                                         if (k == 0xff || (k != 0xff && pin >
473                                             DP_CONF_GET_PIN_ASSIGN(port[k].mid))
474                                             ) {
475                                                 k = j;
476                                         }
477                                 }
478                         }
479                         cam = k;
480                         new_port->active_idx = cam;
481                 } else {
482                         cam = new_port->active_idx;
483                 }
484         }
485         *cmd &= ~UCSI_SET_NEW_CAM_AM_MASK;
486         *cmd |= UCSI_SET_NEW_CAM_SET_AM(cam);
487 }
488
489 /*
490  * Change the order of vdo values of NVIDIA test device FTB
491  * (Function Test Board) which reports altmode list with vdo=0x3
492  * first and then vdo=0x. Current logic to assign mode value is
493  * based on order in altmode list and it causes a mismatch of CON
494  * and SOP altmodes since NVIDIA GPU connector has order of vdo=0x1
495  * first and then vdo=0x3
496  */
497 static void ucsi_ccg_nvidia_altmode(struct ucsi_ccg *uc,
498                                     struct ucsi_altmode *alt)
499 {
500         switch (UCSI_ALTMODE_OFFSET(uc->last_cmd_sent)) {
501         case NVIDIA_FTB_DP_OFFSET:
502                 if (alt[0].mid == USB_TYPEC_NVIDIA_VLINK_DBG_VDO)
503                         alt[0].mid = USB_TYPEC_NVIDIA_VLINK_DP_VDO |
504                                 DP_CAP_DP_SIGNALING | DP_CAP_USB |
505                                 DP_CONF_SET_PIN_ASSIGN(BIT(DP_PIN_ASSIGN_E));
506                 break;
507         case NVIDIA_FTB_DBG_OFFSET:
508                 if (alt[0].mid == USB_TYPEC_NVIDIA_VLINK_DP_VDO)
509                         alt[0].mid = USB_TYPEC_NVIDIA_VLINK_DBG_VDO;
510                 break;
511         default:
512                 break;
513         }
514 }
515
516 static int ucsi_ccg_read(struct ucsi *ucsi, unsigned int offset,
517                          void *val, size_t val_len)
518 {
519         struct ucsi_ccg *uc = ucsi_get_drvdata(ucsi);
520         u16 reg = CCGX_RAB_UCSI_DATA_BLOCK(offset);
521         struct ucsi_capability *cap;
522         struct ucsi_altmode *alt;
523         int ret;
524
525         ret = ccg_read(uc, reg, val, val_len);
526         if (ret)
527                 return ret;
528
529         if (offset != UCSI_MESSAGE_IN)
530                 return ret;
531
532         switch (UCSI_COMMAND(uc->last_cmd_sent)) {
533         case UCSI_GET_CURRENT_CAM:
534                 if (uc->has_multiple_dp)
535                         ucsi_ccg_update_get_current_cam_cmd(uc, (u8 *)val);
536                 break;
537         case UCSI_GET_ALTERNATE_MODES:
538                 if (UCSI_ALTMODE_RECIPIENT(uc->last_cmd_sent) ==
539                     UCSI_RECIPIENT_SOP) {
540                         alt = val;
541                         if (alt[0].svid == USB_TYPEC_NVIDIA_VLINK_SID)
542                                 ucsi_ccg_nvidia_altmode(uc, alt);
543                 }
544                 break;
545         case UCSI_GET_CAPABILITY:
546                 if (uc->fw_build == CCG_FW_BUILD_NVIDIA_TEGRA) {
547                         cap = val;
548                         cap->features &= ~UCSI_CAP_ALT_MODE_DETAILS;
549                 }
550                 break;
551         default:
552                 break;
553         }
554         uc->last_cmd_sent = 0;
555
556         return ret;
557 }
558
559 static int ucsi_ccg_async_write(struct ucsi *ucsi, unsigned int offset,
560                                 const void *val, size_t val_len)
561 {
562         u16 reg = CCGX_RAB_UCSI_DATA_BLOCK(offset);
563
564         return ccg_write(ucsi_get_drvdata(ucsi), reg, val, val_len);
565 }
566
567 static int ucsi_ccg_sync_write(struct ucsi *ucsi, unsigned int offset,
568                                const void *val, size_t val_len)
569 {
570         struct ucsi_ccg *uc = ucsi_get_drvdata(ucsi);
571         struct ucsi_connector *con;
572         int con_index;
573         int ret;
574
575         mutex_lock(&uc->lock);
576         pm_runtime_get_sync(uc->dev);
577         set_bit(DEV_CMD_PENDING, &uc->flags);
578
579         if (offset == UCSI_CONTROL && val_len == sizeof(uc->last_cmd_sent)) {
580                 uc->last_cmd_sent = *(u64 *)val;
581
582                 if (UCSI_COMMAND(uc->last_cmd_sent) == UCSI_SET_NEW_CAM &&
583                     uc->has_multiple_dp) {
584                         con_index = (uc->last_cmd_sent >> 16) &
585                                     UCSI_CMD_CONNECTOR_MASK;
586                         con = &uc->ucsi->connector[con_index - 1];
587                         ucsi_ccg_update_set_new_cam_cmd(uc, con, (u64 *)val);
588                 }
589         }
590
591         ret = ucsi_ccg_async_write(ucsi, offset, val, val_len);
592         if (ret)
593                 goto err_clear_bit;
594
595         if (!wait_for_completion_timeout(&uc->complete, msecs_to_jiffies(5000)))
596                 ret = -ETIMEDOUT;
597
598 err_clear_bit:
599         clear_bit(DEV_CMD_PENDING, &uc->flags);
600         pm_runtime_put_sync(uc->dev);
601         mutex_unlock(&uc->lock);
602
603         return ret;
604 }
605
606 static const struct ucsi_operations ucsi_ccg_ops = {
607         .read = ucsi_ccg_read,
608         .sync_write = ucsi_ccg_sync_write,
609         .async_write = ucsi_ccg_async_write,
610         .update_altmodes = ucsi_ccg_update_altmodes
611 };
612
613 static irqreturn_t ccg_irq_handler(int irq, void *data)
614 {
615         u16 reg = CCGX_RAB_UCSI_DATA_BLOCK(UCSI_CCI);
616         struct ucsi_ccg *uc = data;
617         u8 intr_reg;
618         u32 cci;
619         int ret;
620
621         ret = ccg_read(uc, CCGX_RAB_INTR_REG, &intr_reg, sizeof(intr_reg));
622         if (ret)
623                 return ret;
624
625         ret = ccg_read(uc, reg, (void *)&cci, sizeof(cci));
626         if (ret)
627                 goto err_clear_irq;
628
629         if (UCSI_CCI_CONNECTOR(cci))
630                 ucsi_connector_change(uc->ucsi, UCSI_CCI_CONNECTOR(cci));
631
632         if (test_bit(DEV_CMD_PENDING, &uc->flags) &&
633             cci & (UCSI_CCI_ACK_COMPLETE | UCSI_CCI_COMMAND_COMPLETE))
634                 complete(&uc->complete);
635
636 err_clear_irq:
637         ccg_write(uc, CCGX_RAB_INTR_REG, &intr_reg, sizeof(intr_reg));
638
639         return IRQ_HANDLED;
640 }
641
642 static int ccg_request_irq(struct ucsi_ccg *uc)
643 {
644         unsigned long flags = IRQF_ONESHOT;
645
646         if (!dev_fwnode(uc->dev))
647                 flags |= IRQF_TRIGGER_HIGH;
648
649         return request_threaded_irq(uc->irq, NULL, ccg_irq_handler, flags, dev_name(uc->dev), uc);
650 }
651
652 static void ccg_pm_workaround_work(struct work_struct *pm_work)
653 {
654         ccg_irq_handler(0, container_of(pm_work, struct ucsi_ccg, pm_work));
655 }
656
657 static int get_fw_info(struct ucsi_ccg *uc)
658 {
659         int err;
660
661         err = ccg_read(uc, CCGX_RAB_READ_ALL_VER, (u8 *)(&uc->version),
662                        sizeof(uc->version));
663         if (err < 0)
664                 return err;
665
666         uc->fw_version = CCG_VERSION(uc->version[FW2].app.ver) |
667                         CCG_VERSION_PATCH(uc->version[FW2].app.patch);
668
669         err = ccg_read(uc, CCGX_RAB_DEVICE_MODE, (u8 *)(&uc->info),
670                        sizeof(uc->info));
671         if (err < 0)
672                 return err;
673
674         return 0;
675 }
676
677 static inline bool invalid_async_evt(int code)
678 {
679         return (code >= CCG_EVENT_MAX) || (code < EVENT_INDEX);
680 }
681
682 static void ccg_process_response(struct ucsi_ccg *uc)
683 {
684         struct device *dev = uc->dev;
685
686         if (uc->dev_resp.code & ASYNC_EVENT) {
687                 if (uc->dev_resp.code == RESET_COMPLETE) {
688                         if (test_bit(RESET_PENDING, &uc->flags))
689                                 uc->cmd_resp = uc->dev_resp.code;
690                         get_fw_info(uc);
691                 }
692                 if (invalid_async_evt(uc->dev_resp.code))
693                         dev_err(dev, "invalid async evt %d\n",
694                                 uc->dev_resp.code);
695         } else {
696                 if (test_bit(DEV_CMD_PENDING, &uc->flags)) {
697                         uc->cmd_resp = uc->dev_resp.code;
698                         clear_bit(DEV_CMD_PENDING, &uc->flags);
699                 } else {
700                         dev_err(dev, "dev resp 0x%04x but no cmd pending\n",
701                                 uc->dev_resp.code);
702                 }
703         }
704 }
705
706 static int ccg_read_response(struct ucsi_ccg *uc)
707 {
708         unsigned long target = jiffies + msecs_to_jiffies(1000);
709         struct device *dev = uc->dev;
710         u8 intval;
711         int status;
712
713         /* wait for interrupt status to get updated */
714         do {
715                 status = ccg_read(uc, CCGX_RAB_INTR_REG, &intval,
716                                   sizeof(intval));
717                 if (status < 0)
718                         return status;
719
720                 if (intval & DEV_INT)
721                         break;
722                 usleep_range(500, 600);
723         } while (time_is_after_jiffies(target));
724
725         if (time_is_before_jiffies(target)) {
726                 dev_err(dev, "response timeout error\n");
727                 return -ETIME;
728         }
729
730         status = ccg_read(uc, CCGX_RAB_RESPONSE, (u8 *)&uc->dev_resp,
731                           sizeof(uc->dev_resp));
732         if (status < 0)
733                 return status;
734
735         status = ccg_write(uc, CCGX_RAB_INTR_REG, &intval, sizeof(intval));
736         if (status < 0)
737                 return status;
738
739         return 0;
740 }
741
742 /* Caller must hold uc->lock */
743 static int ccg_send_command(struct ucsi_ccg *uc, struct ccg_cmd *cmd)
744 {
745         struct device *dev = uc->dev;
746         int ret;
747
748         switch (cmd->reg & 0xF000) {
749         case DEV_REG_IDX:
750                 set_bit(DEV_CMD_PENDING, &uc->flags);
751                 break;
752         default:
753                 dev_err(dev, "invalid cmd register\n");
754                 break;
755         }
756
757         ret = ccg_write(uc, cmd->reg, (u8 *)&cmd->data, cmd->len);
758         if (ret < 0)
759                 return ret;
760
761         msleep(cmd->delay);
762
763         ret = ccg_read_response(uc);
764         if (ret < 0) {
765                 dev_err(dev, "response read error\n");
766                 switch (cmd->reg & 0xF000) {
767                 case DEV_REG_IDX:
768                         clear_bit(DEV_CMD_PENDING, &uc->flags);
769                         break;
770                 default:
771                         dev_err(dev, "invalid cmd register\n");
772                         break;
773                 }
774                 return -EIO;
775         }
776         ccg_process_response(uc);
777
778         return uc->cmd_resp;
779 }
780
781 static int ccg_cmd_enter_flashing(struct ucsi_ccg *uc)
782 {
783         struct ccg_cmd cmd;
784         int ret;
785
786         cmd.reg = CCGX_RAB_ENTER_FLASHING;
787         cmd.data = FLASH_ENTER_SIG;
788         cmd.len = 1;
789         cmd.delay = 50;
790
791         mutex_lock(&uc->lock);
792
793         ret = ccg_send_command(uc, &cmd);
794
795         mutex_unlock(&uc->lock);
796
797         if (ret != CMD_SUCCESS) {
798                 dev_err(uc->dev, "enter flashing failed ret=%d\n", ret);
799                 return ret;
800         }
801
802         return 0;
803 }
804
805 static int ccg_cmd_reset(struct ucsi_ccg *uc)
806 {
807         struct ccg_cmd cmd;
808         u8 *p;
809         int ret;
810
811         p = (u8 *)&cmd.data;
812         cmd.reg = CCGX_RAB_RESET_REQ;
813         p[0] = RESET_SIG;
814         p[1] = CMD_RESET_DEV;
815         cmd.len = 2;
816         cmd.delay = 5000;
817
818         mutex_lock(&uc->lock);
819
820         set_bit(RESET_PENDING, &uc->flags);
821
822         ret = ccg_send_command(uc, &cmd);
823         if (ret != RESET_COMPLETE)
824                 goto err_clear_flag;
825
826         ret = 0;
827
828 err_clear_flag:
829         clear_bit(RESET_PENDING, &uc->flags);
830
831         mutex_unlock(&uc->lock);
832
833         return ret;
834 }
835
836 static int ccg_cmd_port_control(struct ucsi_ccg *uc, bool enable)
837 {
838         struct ccg_cmd cmd;
839         int ret;
840
841         cmd.reg = CCGX_RAB_PDPORT_ENABLE;
842         if (enable)
843                 cmd.data = (uc->port_num == 1) ?
844                             PDPORT_1 : (PDPORT_1 | PDPORT_2);
845         else
846                 cmd.data = 0x0;
847         cmd.len = 1;
848         cmd.delay = 10;
849
850         mutex_lock(&uc->lock);
851
852         ret = ccg_send_command(uc, &cmd);
853
854         mutex_unlock(&uc->lock);
855
856         if (ret != CMD_SUCCESS) {
857                 dev_err(uc->dev, "port control failed ret=%d\n", ret);
858                 return ret;
859         }
860         return 0;
861 }
862
863 static int ccg_cmd_jump_boot_mode(struct ucsi_ccg *uc, int bl_mode)
864 {
865         struct ccg_cmd cmd;
866         int ret;
867
868         cmd.reg = CCGX_RAB_JUMP_TO_BOOT;
869
870         if (bl_mode)
871                 cmd.data = TO_BOOT;
872         else
873                 cmd.data = TO_ALT_FW;
874
875         cmd.len = 1;
876         cmd.delay = 100;
877
878         mutex_lock(&uc->lock);
879
880         set_bit(RESET_PENDING, &uc->flags);
881
882         ret = ccg_send_command(uc, &cmd);
883         if (ret != RESET_COMPLETE)
884                 goto err_clear_flag;
885
886         ret = 0;
887
888 err_clear_flag:
889         clear_bit(RESET_PENDING, &uc->flags);
890
891         mutex_unlock(&uc->lock);
892
893         return ret;
894 }
895
896 static int
897 ccg_cmd_write_flash_row(struct ucsi_ccg *uc, u16 row,
898                         const void *data, u8 fcmd)
899 {
900         struct i2c_client *client = uc->client;
901         struct ccg_cmd cmd;
902         u8 buf[CCG4_ROW_SIZE + 2];
903         u8 *p;
904         int ret;
905
906         /* Copy the data into the flash read/write memory. */
907         put_unaligned_le16(REG_FLASH_RW_MEM, buf);
908
909         memcpy(buf + 2, data, CCG4_ROW_SIZE);
910
911         mutex_lock(&uc->lock);
912
913         ret = i2c_master_send(client, buf, CCG4_ROW_SIZE + 2);
914         if (ret != CCG4_ROW_SIZE + 2) {
915                 dev_err(uc->dev, "REG_FLASH_RW_MEM write fail %d\n", ret);
916                 mutex_unlock(&uc->lock);
917                 return ret < 0 ? ret : -EIO;
918         }
919
920         /* Use the FLASH_ROW_READ_WRITE register to trigger */
921         /* writing of data to the desired flash row */
922         p = (u8 *)&cmd.data;
923         cmd.reg = CCGX_RAB_FLASH_ROW_RW;
924         p[0] = FLASH_SIG;
925         p[1] = fcmd;
926         put_unaligned_le16(row, &p[2]);
927         cmd.len = 4;
928         cmd.delay = 50;
929         if (fcmd == FLASH_FWCT_SIG_WR_CMD)
930                 cmd.delay += 400;
931         if (row == 510)
932                 cmd.delay += 220;
933         ret = ccg_send_command(uc, &cmd);
934
935         mutex_unlock(&uc->lock);
936
937         if (ret != CMD_SUCCESS) {
938                 dev_err(uc->dev, "write flash row failed ret=%d\n", ret);
939                 return ret;
940         }
941
942         return 0;
943 }
944
945 static int ccg_cmd_validate_fw(struct ucsi_ccg *uc, unsigned int fwid)
946 {
947         struct ccg_cmd cmd;
948         int ret;
949
950         cmd.reg = CCGX_RAB_VALIDATE_FW;
951         cmd.data = fwid;
952         cmd.len = 1;
953         cmd.delay = 500;
954
955         mutex_lock(&uc->lock);
956
957         ret = ccg_send_command(uc, &cmd);
958
959         mutex_unlock(&uc->lock);
960
961         if (ret != CMD_SUCCESS)
962                 return ret;
963
964         return 0;
965 }
966
967 static bool ccg_check_vendor_version(struct ucsi_ccg *uc,
968                                      struct version_format *app,
969                                      struct fw_config_table *fw_cfg)
970 {
971         struct device *dev = uc->dev;
972
973         /* Check if the fw build is for supported vendors */
974         if (le16_to_cpu(app->build) != uc->fw_build) {
975                 dev_info(dev, "current fw is not from supported vendor\n");
976                 return false;
977         }
978
979         /* Check if the new fw build is for supported vendors */
980         if (le16_to_cpu(fw_cfg->app.build) != uc->fw_build) {
981                 dev_info(dev, "new fw is not from supported vendor\n");
982                 return false;
983         }
984         return true;
985 }
986
987 static bool ccg_check_fw_version(struct ucsi_ccg *uc, const char *fw_name,
988                                  struct version_format *app)
989 {
990         const struct firmware *fw = NULL;
991         struct device *dev = uc->dev;
992         struct fw_config_table fw_cfg;
993         u32 cur_version, new_version;
994         bool is_later = false;
995
996         if (request_firmware(&fw, fw_name, dev) != 0) {
997                 dev_err(dev, "error: Failed to open cyacd file %s\n", fw_name);
998                 return false;
999         }
1000
1001         /*
1002          * check if signed fw
1003          * last part of fw image is fw cfg table and signature
1004          */
1005         if (fw->size < sizeof(fw_cfg) + FW_CFG_TABLE_SIG_SIZE)
1006                 goto out_release_firmware;
1007
1008         memcpy((uint8_t *)&fw_cfg, fw->data + fw->size -
1009                sizeof(fw_cfg) - FW_CFG_TABLE_SIG_SIZE, sizeof(fw_cfg));
1010
1011         if (fw_cfg.identity != ('F' | 'W' << 8 | 'C' << 16 | 'T' << 24)) {
1012                 dev_info(dev, "not a signed image\n");
1013                 goto out_release_firmware;
1014         }
1015
1016         /* compare input version with FWCT version */
1017         cur_version = le16_to_cpu(app->build) | CCG_VERSION_PATCH(app->patch) |
1018                         CCG_VERSION(app->ver);
1019
1020         new_version = le16_to_cpu(fw_cfg.app.build) |
1021                         CCG_VERSION_PATCH(fw_cfg.app.patch) |
1022                         CCG_VERSION(fw_cfg.app.ver);
1023
1024         if (!ccg_check_vendor_version(uc, app, &fw_cfg))
1025                 goto out_release_firmware;
1026
1027         if (new_version > cur_version)
1028                 is_later = true;
1029
1030 out_release_firmware:
1031         release_firmware(fw);
1032         return is_later;
1033 }
1034
1035 static int ccg_fw_update_needed(struct ucsi_ccg *uc,
1036                                 enum enum_flash_mode *mode)
1037 {
1038         struct device *dev = uc->dev;
1039         int err;
1040         struct version_info version[3];
1041
1042         err = ccg_read(uc, CCGX_RAB_DEVICE_MODE, (u8 *)(&uc->info),
1043                        sizeof(uc->info));
1044         if (err) {
1045                 dev_err(dev, "read device mode failed\n");
1046                 return err;
1047         }
1048
1049         err = ccg_read(uc, CCGX_RAB_READ_ALL_VER, (u8 *)version,
1050                        sizeof(version));
1051         if (err) {
1052                 dev_err(dev, "read device mode failed\n");
1053                 return err;
1054         }
1055
1056         if (memcmp(&version[FW1], "\0\0\0\0\0\0\0\0",
1057                    sizeof(struct version_info)) == 0) {
1058                 dev_info(dev, "secondary fw is not flashed\n");
1059                 *mode = SECONDARY_BL;
1060         } else if (le16_to_cpu(version[FW1].base.build) <
1061                 secondary_fw_min_ver) {
1062                 dev_info(dev, "secondary fw version is too low (< %d)\n",
1063                          secondary_fw_min_ver);
1064                 *mode = SECONDARY;
1065         } else if (memcmp(&version[FW2], "\0\0\0\0\0\0\0\0",
1066                    sizeof(struct version_info)) == 0) {
1067                 dev_info(dev, "primary fw is not flashed\n");
1068                 *mode = PRIMARY;
1069         } else if (ccg_check_fw_version(uc, ccg_fw_names[PRIMARY],
1070                    &version[FW2].app)) {
1071                 dev_info(dev, "found primary fw with later version\n");
1072                 *mode = PRIMARY;
1073         } else {
1074                 dev_info(dev, "secondary and primary fw are the latest\n");
1075                 *mode = FLASH_NOT_NEEDED;
1076         }
1077         return 0;
1078 }
1079
1080 static int do_flash(struct ucsi_ccg *uc, enum enum_flash_mode mode)
1081 {
1082         struct device *dev = uc->dev;
1083         const struct firmware *fw = NULL;
1084         const char *p, *s;
1085         const char *eof;
1086         int err, row, len, line_sz, line_cnt = 0;
1087         unsigned long start_time = jiffies;
1088         struct fw_config_table  fw_cfg;
1089         u8 fw_cfg_sig[FW_CFG_TABLE_SIG_SIZE];
1090         u8 *wr_buf;
1091
1092         err = request_firmware(&fw, ccg_fw_names[mode], dev);
1093         if (err) {
1094                 dev_err(dev, "request %s failed err=%d\n",
1095                         ccg_fw_names[mode], err);
1096                 return err;
1097         }
1098
1099         if (((uc->info.mode & CCG_DEVINFO_FWMODE_MASK) >>
1100                         CCG_DEVINFO_FWMODE_SHIFT) == FW2) {
1101                 err = ccg_cmd_port_control(uc, false);
1102                 if (err < 0)
1103                         goto release_fw;
1104                 err = ccg_cmd_jump_boot_mode(uc, 0);
1105                 if (err < 0)
1106                         goto release_fw;
1107         }
1108
1109         eof = fw->data + fw->size;
1110
1111         /*
1112          * check if signed fw
1113          * last part of fw image is fw cfg table and signature
1114          */
1115         if (fw->size < sizeof(fw_cfg) + sizeof(fw_cfg_sig))
1116                 goto not_signed_fw;
1117
1118         memcpy((uint8_t *)&fw_cfg, fw->data + fw->size -
1119                sizeof(fw_cfg) - sizeof(fw_cfg_sig), sizeof(fw_cfg));
1120
1121         if (fw_cfg.identity != ('F' | ('W' << 8) | ('C' << 16) | ('T' << 24))) {
1122                 dev_info(dev, "not a signed image\n");
1123                 goto not_signed_fw;
1124         }
1125         eof = fw->data + fw->size - sizeof(fw_cfg) - sizeof(fw_cfg_sig);
1126
1127         memcpy((uint8_t *)&fw_cfg_sig,
1128                fw->data + fw->size - sizeof(fw_cfg_sig), sizeof(fw_cfg_sig));
1129
1130         /* flash fw config table and signature first */
1131         err = ccg_cmd_write_flash_row(uc, 0, (u8 *)&fw_cfg,
1132                                       FLASH_FWCT1_WR_CMD);
1133         if (err)
1134                 goto release_fw;
1135
1136         err = ccg_cmd_write_flash_row(uc, 0, (u8 *)&fw_cfg + CCG4_ROW_SIZE,
1137                                       FLASH_FWCT2_WR_CMD);
1138         if (err)
1139                 goto release_fw;
1140
1141         err = ccg_cmd_write_flash_row(uc, 0, &fw_cfg_sig,
1142                                       FLASH_FWCT_SIG_WR_CMD);
1143         if (err)
1144                 goto release_fw;
1145
1146 not_signed_fw:
1147         wr_buf = kzalloc(CCG4_ROW_SIZE + 4, GFP_KERNEL);
1148         if (!wr_buf) {
1149                 err = -ENOMEM;
1150                 goto release_fw;
1151         }
1152
1153         err = ccg_cmd_enter_flashing(uc);
1154         if (err)
1155                 goto release_mem;
1156
1157         /*****************************************************************
1158          * CCG firmware image (.cyacd) file line format
1159          *
1160          * :00rrrrllll[dd....]cc/r/n
1161          *
1162          * :00   header
1163          * rrrr is row number to flash                          (4 char)
1164          * llll is data len to flash                            (4 char)
1165          * dd   is a data field represents one byte of data     (512 char)
1166          * cc   is checksum                                     (2 char)
1167          * \r\n newline
1168          *
1169          * Total length: 3 + 4 + 4 + 512 + 2 + 2 = 527
1170          *
1171          *****************************************************************/
1172
1173         p = strnchr(fw->data, fw->size, ':');
1174         while (p < eof) {
1175                 s = strnchr(p + 1, eof - p - 1, ':');
1176
1177                 if (!s)
1178                         s = eof;
1179
1180                 line_sz = s - p;
1181
1182                 if (line_sz != CYACD_LINE_SIZE) {
1183                         dev_err(dev, "Bad FW format line_sz=%d\n", line_sz);
1184                         err =  -EINVAL;
1185                         goto release_mem;
1186                 }
1187
1188                 if (hex2bin(wr_buf, p + 3, CCG4_ROW_SIZE + 4)) {
1189                         err =  -EINVAL;
1190                         goto release_mem;
1191                 }
1192
1193                 row = get_unaligned_be16(wr_buf);
1194                 len = get_unaligned_be16(&wr_buf[2]);
1195
1196                 if (len != CCG4_ROW_SIZE) {
1197                         err =  -EINVAL;
1198                         goto release_mem;
1199                 }
1200
1201                 err = ccg_cmd_write_flash_row(uc, row, wr_buf + 4,
1202                                               FLASH_WR_CMD);
1203                 if (err)
1204                         goto release_mem;
1205
1206                 line_cnt++;
1207                 p = s;
1208         }
1209
1210         dev_info(dev, "total %d row flashed. time: %dms\n",
1211                  line_cnt, jiffies_to_msecs(jiffies - start_time));
1212
1213         err = ccg_cmd_validate_fw(uc, (mode == PRIMARY) ? FW2 :  FW1);
1214         if (err)
1215                 dev_err(dev, "%s validation failed err=%d\n",
1216                         (mode == PRIMARY) ? "FW2" :  "FW1", err);
1217         else
1218                 dev_info(dev, "%s validated\n",
1219                          (mode == PRIMARY) ? "FW2" :  "FW1");
1220
1221         err = ccg_cmd_port_control(uc, false);
1222         if (err < 0)
1223                 goto release_mem;
1224
1225         err = ccg_cmd_reset(uc);
1226         if (err < 0)
1227                 goto release_mem;
1228
1229         err = ccg_cmd_port_control(uc, true);
1230         if (err < 0)
1231                 goto release_mem;
1232
1233 release_mem:
1234         kfree(wr_buf);
1235
1236 release_fw:
1237         release_firmware(fw);
1238         return err;
1239 }
1240
1241 /*******************************************************************************
1242  * CCG4 has two copies of the firmware in addition to the bootloader.
1243  * If the device is running FW1, FW2 can be updated with the new version.
1244  * Dual firmware mode allows the CCG device to stay in a PD contract and support
1245  * USB PD and Type-C functionality while a firmware update is in progress.
1246  ******************************************************************************/
1247 static int ccg_fw_update(struct ucsi_ccg *uc, enum enum_flash_mode flash_mode)
1248 {
1249         int err = 0;
1250
1251         while (flash_mode != FLASH_NOT_NEEDED) {
1252                 err = do_flash(uc, flash_mode);
1253                 if (err < 0)
1254                         return err;
1255                 err = ccg_fw_update_needed(uc, &flash_mode);
1256                 if (err < 0)
1257                         return err;
1258         }
1259         dev_info(uc->dev, "CCG FW update successful\n");
1260
1261         return err;
1262 }
1263
1264 static int ccg_restart(struct ucsi_ccg *uc)
1265 {
1266         struct device *dev = uc->dev;
1267         int status;
1268
1269         status = ucsi_ccg_init(uc);
1270         if (status < 0) {
1271                 dev_err(dev, "ucsi_ccg_start fail, err=%d\n", status);
1272                 return status;
1273         }
1274
1275         status = ccg_request_irq(uc);
1276         if (status < 0) {
1277                 dev_err(dev, "request_threaded_irq failed - %d\n", status);
1278                 return status;
1279         }
1280
1281         status = ucsi_register(uc->ucsi);
1282         if (status) {
1283                 dev_err(uc->dev, "failed to register the interface\n");
1284                 return status;
1285         }
1286
1287         pm_runtime_enable(uc->dev);
1288         return 0;
1289 }
1290
1291 static void ccg_update_firmware(struct work_struct *work)
1292 {
1293         struct ucsi_ccg *uc = container_of(work, struct ucsi_ccg, work);
1294         enum enum_flash_mode flash_mode;
1295         int status;
1296
1297         status = ccg_fw_update_needed(uc, &flash_mode);
1298         if (status < 0)
1299                 return;
1300
1301         if (flash_mode != FLASH_NOT_NEEDED) {
1302                 ucsi_unregister(uc->ucsi);
1303                 pm_runtime_disable(uc->dev);
1304                 free_irq(uc->irq, uc);
1305
1306                 ccg_fw_update(uc, flash_mode);
1307                 ccg_restart(uc);
1308         }
1309 }
1310
1311 static ssize_t do_flash_store(struct device *dev,
1312                               struct device_attribute *attr,
1313                               const char *buf, size_t n)
1314 {
1315         struct ucsi_ccg *uc = i2c_get_clientdata(to_i2c_client(dev));
1316         bool flash;
1317
1318         if (kstrtobool(buf, &flash))
1319                 return -EINVAL;
1320
1321         if (!flash)
1322                 return n;
1323
1324         if (uc->fw_build == 0x0) {
1325                 dev_err(dev, "fail to flash FW due to missing FW build info\n");
1326                 return -EINVAL;
1327         }
1328
1329         schedule_work(&uc->work);
1330         return n;
1331 }
1332
1333 static DEVICE_ATTR_WO(do_flash);
1334
1335 static struct attribute *ucsi_ccg_attrs[] = {
1336         &dev_attr_do_flash.attr,
1337         NULL,
1338 };
1339 ATTRIBUTE_GROUPS(ucsi_ccg);
1340
1341 static int ucsi_ccg_probe(struct i2c_client *client)
1342 {
1343         struct device *dev = &client->dev;
1344         struct ucsi_ccg *uc;
1345         const char *fw_name;
1346         int status;
1347
1348         uc = devm_kzalloc(dev, sizeof(*uc), GFP_KERNEL);
1349         if (!uc)
1350                 return -ENOMEM;
1351
1352         uc->dev = dev;
1353         uc->client = client;
1354         uc->irq = client->irq;
1355         mutex_init(&uc->lock);
1356         init_completion(&uc->complete);
1357         INIT_WORK(&uc->work, ccg_update_firmware);
1358         INIT_WORK(&uc->pm_work, ccg_pm_workaround_work);
1359
1360         /* Only fail FW flashing when FW build information is not provided */
1361         status = device_property_read_string(dev, "firmware-name", &fw_name);
1362         if (!status) {
1363                 if (!strcmp(fw_name, "nvidia,jetson-agx-xavier"))
1364                         uc->fw_build = CCG_FW_BUILD_NVIDIA_TEGRA;
1365                 else if (!strcmp(fw_name, "nvidia,gpu"))
1366                         uc->fw_build = CCG_FW_BUILD_NVIDIA;
1367         }
1368
1369         if (!uc->fw_build)
1370                 dev_err(uc->dev, "failed to get FW build information\n");
1371
1372         /* reset ccg device and initialize ucsi */
1373         status = ucsi_ccg_init(uc);
1374         if (status < 0) {
1375                 dev_err(uc->dev, "ucsi_ccg_init failed - %d\n", status);
1376                 return status;
1377         }
1378
1379         status = get_fw_info(uc);
1380         if (status < 0) {
1381                 dev_err(uc->dev, "get_fw_info failed - %d\n", status);
1382                 return status;
1383         }
1384
1385         uc->port_num = 1;
1386
1387         if (uc->info.mode & CCG_DEVINFO_PDPORTS_MASK)
1388                 uc->port_num++;
1389
1390         uc->ucsi = ucsi_create(dev, &ucsi_ccg_ops);
1391         if (IS_ERR(uc->ucsi))
1392                 return PTR_ERR(uc->ucsi);
1393
1394         ucsi_set_drvdata(uc->ucsi, uc);
1395
1396         status = ccg_request_irq(uc);
1397         if (status < 0) {
1398                 dev_err(uc->dev, "request_threaded_irq failed - %d\n", status);
1399                 goto out_ucsi_destroy;
1400         }
1401
1402         status = ucsi_register(uc->ucsi);
1403         if (status)
1404                 goto out_free_irq;
1405
1406         i2c_set_clientdata(client, uc);
1407
1408         pm_runtime_set_active(uc->dev);
1409         pm_runtime_enable(uc->dev);
1410         pm_runtime_use_autosuspend(uc->dev);
1411         pm_runtime_set_autosuspend_delay(uc->dev, 5000);
1412         pm_runtime_idle(uc->dev);
1413
1414         return 0;
1415
1416 out_free_irq:
1417         free_irq(uc->irq, uc);
1418 out_ucsi_destroy:
1419         ucsi_destroy(uc->ucsi);
1420
1421         return status;
1422 }
1423
1424 static void ucsi_ccg_remove(struct i2c_client *client)
1425 {
1426         struct ucsi_ccg *uc = i2c_get_clientdata(client);
1427
1428         cancel_work_sync(&uc->pm_work);
1429         cancel_work_sync(&uc->work);
1430         pm_runtime_disable(uc->dev);
1431         ucsi_unregister(uc->ucsi);
1432         ucsi_destroy(uc->ucsi);
1433         free_irq(uc->irq, uc);
1434 }
1435
1436 static const struct of_device_id ucsi_ccg_of_match_table[] = {
1437                 { .compatible = "cypress,cypd4226", },
1438                 { /* sentinel */ }
1439 };
1440 MODULE_DEVICE_TABLE(of, ucsi_ccg_of_match_table);
1441
1442 static const struct i2c_device_id ucsi_ccg_device_id[] = {
1443         {"ccgx-ucsi", 0},
1444         {}
1445 };
1446 MODULE_DEVICE_TABLE(i2c, ucsi_ccg_device_id);
1447
1448 static const struct acpi_device_id amd_i2c_ucsi_match[] = {
1449         {"AMDI0042"},
1450         {}
1451 };
1452 MODULE_DEVICE_TABLE(acpi, amd_i2c_ucsi_match);
1453
1454 static int ucsi_ccg_resume(struct device *dev)
1455 {
1456         struct i2c_client *client = to_i2c_client(dev);
1457         struct ucsi_ccg *uc = i2c_get_clientdata(client);
1458
1459         return ucsi_resume(uc->ucsi);
1460 }
1461
1462 static int ucsi_ccg_runtime_suspend(struct device *dev)
1463 {
1464         return 0;
1465 }
1466
1467 static int ucsi_ccg_runtime_resume(struct device *dev)
1468 {
1469         struct i2c_client *client = to_i2c_client(dev);
1470         struct ucsi_ccg *uc = i2c_get_clientdata(client);
1471
1472         /*
1473          * Firmware version 3.1.10 or earlier, built for NVIDIA has known issue
1474          * of missing interrupt when a device is connected for runtime resume.
1475          * Schedule a work to call ISR as a workaround.
1476          */
1477         if (uc->fw_build == CCG_FW_BUILD_NVIDIA &&
1478             uc->fw_version <= CCG_OLD_FW_VERSION)
1479                 schedule_work(&uc->pm_work);
1480
1481         return 0;
1482 }
1483
1484 static const struct dev_pm_ops ucsi_ccg_pm = {
1485         .resume = ucsi_ccg_resume,
1486         .runtime_suspend = ucsi_ccg_runtime_suspend,
1487         .runtime_resume = ucsi_ccg_runtime_resume,
1488 };
1489
1490 static struct i2c_driver ucsi_ccg_driver = {
1491         .driver = {
1492                 .name = "ucsi_ccg",
1493                 .pm = &ucsi_ccg_pm,
1494                 .dev_groups = ucsi_ccg_groups,
1495                 .acpi_match_table = amd_i2c_ucsi_match,
1496                 .of_match_table = ucsi_ccg_of_match_table,
1497         },
1498         .probe = ucsi_ccg_probe,
1499         .remove = ucsi_ccg_remove,
1500         .id_table = ucsi_ccg_device_id,
1501 };
1502
1503 module_i2c_driver(ucsi_ccg_driver);
1504
1505 MODULE_AUTHOR("Ajay Gupta <ajayg@nvidia.com>");
1506 MODULE_DESCRIPTION("UCSI driver for Cypress CCGx Type-C controller");
1507 MODULE_LICENSE("GPL v2");