GNU Linux-libre 6.8.7-gnu
[releases.git] / drivers / usb / typec / ucsi / ucsi.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * USB Type-C Connector System Software Interface driver
4  *
5  * Copyright (C) 2017, Intel Corporation
6  * Author: Heikki Krogerus <heikki.krogerus@linux.intel.com>
7  */
8
9 #include <linux/completion.h>
10 #include <linux/property.h>
11 #include <linux/device.h>
12 #include <linux/module.h>
13 #include <linux/delay.h>
14 #include <linux/slab.h>
15 #include <linux/usb/typec_dp.h>
16
17 #include "ucsi.h"
18 #include "trace.h"
19
20 /*
21  * UCSI_TIMEOUT_MS - PPM communication timeout
22  *
23  * Ideally we could use MIN_TIME_TO_RESPOND_WITH_BUSY (which is defined in UCSI
24  * specification) here as reference, but unfortunately we can't. It is very
25  * difficult to estimate the time it takes for the system to process the command
26  * before it is actually passed to the PPM.
27  */
28 #define UCSI_TIMEOUT_MS         5000
29
30 /*
31  * UCSI_SWAP_TIMEOUT_MS - Timeout for role swap requests
32  *
33  * 5 seconds is close to the time it takes for CapsCounter to reach 0, so even
34  * if the PPM does not generate Connector Change events before that with
35  * partners that do not support USB Power Delivery, this should still work.
36  */
37 #define UCSI_SWAP_TIMEOUT_MS    5000
38
39 static int ucsi_read_message_in(struct ucsi *ucsi, void *buf,
40                                           size_t buf_size)
41 {
42         /*
43          * Below UCSI 2.0, MESSAGE_IN was limited to 16 bytes. Truncate the
44          * reads here.
45          */
46         if (ucsi->version <= UCSI_VERSION_1_2)
47                 buf_size = clamp(buf_size, 0, 16);
48
49         return ucsi->ops->read(ucsi, UCSI_MESSAGE_IN, buf, buf_size);
50 }
51
52 static int ucsi_acknowledge_command(struct ucsi *ucsi)
53 {
54         u64 ctrl;
55
56         ctrl = UCSI_ACK_CC_CI;
57         ctrl |= UCSI_ACK_COMMAND_COMPLETE;
58
59         return ucsi->ops->sync_write(ucsi, UCSI_CONTROL, &ctrl, sizeof(ctrl));
60 }
61
62 static int ucsi_acknowledge_connector_change(struct ucsi *ucsi)
63 {
64         u64 ctrl;
65
66         ctrl = UCSI_ACK_CC_CI;
67         ctrl |= UCSI_ACK_CONNECTOR_CHANGE;
68
69         return ucsi->ops->sync_write(ucsi, UCSI_CONTROL, &ctrl, sizeof(ctrl));
70 }
71
72 static int ucsi_exec_command(struct ucsi *ucsi, u64 command);
73
74 static int ucsi_read_error(struct ucsi *ucsi)
75 {
76         u16 error;
77         int ret;
78
79         /* Acknowledge the command that failed */
80         ret = ucsi_acknowledge_command(ucsi);
81         if (ret)
82                 return ret;
83
84         ret = ucsi_exec_command(ucsi, UCSI_GET_ERROR_STATUS);
85         if (ret < 0)
86                 return ret;
87
88         ret = ucsi_read_message_in(ucsi, &error, sizeof(error));
89         if (ret)
90                 return ret;
91
92         ret = ucsi_acknowledge_command(ucsi);
93         if (ret)
94                 return ret;
95
96         switch (error) {
97         case UCSI_ERROR_INCOMPATIBLE_PARTNER:
98                 return -EOPNOTSUPP;
99         case UCSI_ERROR_CC_COMMUNICATION_ERR:
100                 return -ECOMM;
101         case UCSI_ERROR_CONTRACT_NEGOTIATION_FAIL:
102                 return -EPROTO;
103         case UCSI_ERROR_DEAD_BATTERY:
104                 dev_warn(ucsi->dev, "Dead battery condition!\n");
105                 return -EPERM;
106         case UCSI_ERROR_INVALID_CON_NUM:
107         case UCSI_ERROR_UNREGONIZED_CMD:
108         case UCSI_ERROR_INVALID_CMD_ARGUMENT:
109                 dev_err(ucsi->dev, "possible UCSI driver bug %u\n", error);
110                 return -EINVAL;
111         case UCSI_ERROR_OVERCURRENT:
112                 dev_warn(ucsi->dev, "Overcurrent condition\n");
113                 break;
114         case UCSI_ERROR_PARTNER_REJECTED_SWAP:
115                 dev_warn(ucsi->dev, "Partner rejected swap\n");
116                 break;
117         case UCSI_ERROR_HARD_RESET:
118                 dev_warn(ucsi->dev, "Hard reset occurred\n");
119                 break;
120         case UCSI_ERROR_PPM_POLICY_CONFLICT:
121                 dev_warn(ucsi->dev, "PPM Policy conflict\n");
122                 break;
123         case UCSI_ERROR_SWAP_REJECTED:
124                 dev_warn(ucsi->dev, "Swap rejected\n");
125                 break;
126         case UCSI_ERROR_UNDEFINED:
127         default:
128                 dev_err(ucsi->dev, "unknown error %u\n", error);
129                 break;
130         }
131
132         return -EIO;
133 }
134
135 static int ucsi_exec_command(struct ucsi *ucsi, u64 cmd)
136 {
137         u32 cci;
138         int ret;
139
140         ret = ucsi->ops->sync_write(ucsi, UCSI_CONTROL, &cmd, sizeof(cmd));
141         if (ret)
142                 return ret;
143
144         ret = ucsi->ops->read(ucsi, UCSI_CCI, &cci, sizeof(cci));
145         if (ret)
146                 return ret;
147
148         if (cmd != UCSI_CANCEL && cci & UCSI_CCI_BUSY)
149                 return ucsi_exec_command(ucsi, UCSI_CANCEL);
150
151         if (!(cci & UCSI_CCI_COMMAND_COMPLETE))
152                 return -EIO;
153
154         if (cci & UCSI_CCI_NOT_SUPPORTED) {
155                 if (ucsi_acknowledge_command(ucsi) < 0)
156                         dev_err(ucsi->dev,
157                                 "ACK of unsupported command failed\n");
158                 return -EOPNOTSUPP;
159         }
160
161         if (cci & UCSI_CCI_ERROR) {
162                 if (cmd == UCSI_GET_ERROR_STATUS)
163                         return -EIO;
164                 return ucsi_read_error(ucsi);
165         }
166
167         if (cmd == UCSI_CANCEL && cci & UCSI_CCI_CANCEL_COMPLETE) {
168                 ret = ucsi_acknowledge_command(ucsi);
169                 return ret ? ret : -EBUSY;
170         }
171
172         return UCSI_CCI_LENGTH(cci);
173 }
174
175 int ucsi_send_command(struct ucsi *ucsi, u64 command,
176                       void *data, size_t size)
177 {
178         u8 length;
179         int ret;
180
181         mutex_lock(&ucsi->ppm_lock);
182
183         ret = ucsi_exec_command(ucsi, command);
184         if (ret < 0)
185                 goto out;
186
187         length = ret;
188
189         if (data) {
190                 ret = ucsi_read_message_in(ucsi, data, size);
191                 if (ret)
192                         goto out;
193         }
194
195         ret = ucsi_acknowledge_command(ucsi);
196         if (ret)
197                 goto out;
198
199         ret = length;
200 out:
201         mutex_unlock(&ucsi->ppm_lock);
202         return ret;
203 }
204 EXPORT_SYMBOL_GPL(ucsi_send_command);
205
206 /* -------------------------------------------------------------------------- */
207
208 struct ucsi_work {
209         struct delayed_work work;
210         struct list_head node;
211         unsigned long delay;
212         unsigned int count;
213         struct ucsi_connector *con;
214         int (*cb)(struct ucsi_connector *);
215 };
216
217 static void ucsi_poll_worker(struct work_struct *work)
218 {
219         struct ucsi_work *uwork = container_of(work, struct ucsi_work, work.work);
220         struct ucsi_connector *con = uwork->con;
221         int ret;
222
223         mutex_lock(&con->lock);
224
225         if (!con->partner) {
226                 list_del(&uwork->node);
227                 mutex_unlock(&con->lock);
228                 kfree(uwork);
229                 return;
230         }
231
232         ret = uwork->cb(con);
233
234         if (uwork->count-- && (ret == -EBUSY || ret == -ETIMEDOUT)) {
235                 queue_delayed_work(con->wq, &uwork->work, uwork->delay);
236         } else {
237                 list_del(&uwork->node);
238                 kfree(uwork);
239         }
240
241         mutex_unlock(&con->lock);
242 }
243
244 static int ucsi_partner_task(struct ucsi_connector *con,
245                              int (*cb)(struct ucsi_connector *),
246                              int retries, unsigned long delay)
247 {
248         struct ucsi_work *uwork;
249
250         if (!con->partner)
251                 return 0;
252
253         uwork = kzalloc(sizeof(*uwork), GFP_KERNEL);
254         if (!uwork)
255                 return -ENOMEM;
256
257         INIT_DELAYED_WORK(&uwork->work, ucsi_poll_worker);
258         uwork->count = retries;
259         uwork->delay = delay;
260         uwork->con = con;
261         uwork->cb = cb;
262
263         list_add_tail(&uwork->node, &con->partner_tasks);
264         queue_delayed_work(con->wq, &uwork->work, delay);
265
266         return 0;
267 }
268
269 /* -------------------------------------------------------------------------- */
270
271 void ucsi_altmode_update_active(struct ucsi_connector *con)
272 {
273         const struct typec_altmode *altmode = NULL;
274         u64 command;
275         int ret;
276         u8 cur;
277         int i;
278
279         command = UCSI_GET_CURRENT_CAM | UCSI_CONNECTOR_NUMBER(con->num);
280         ret = ucsi_send_command(con->ucsi, command, &cur, sizeof(cur));
281         if (ret < 0) {
282                 if (con->ucsi->version > 0x0100) {
283                         dev_err(con->ucsi->dev,
284                                 "GET_CURRENT_CAM command failed\n");
285                         return;
286                 }
287                 cur = 0xff;
288         }
289
290         if (cur < UCSI_MAX_ALTMODES)
291                 altmode = typec_altmode_get_partner(con->port_altmode[cur]);
292
293         for (i = 0; con->partner_altmode[i]; i++)
294                 typec_altmode_update_active(con->partner_altmode[i],
295                                             con->partner_altmode[i] == altmode);
296 }
297
298 static int ucsi_altmode_next_mode(struct typec_altmode **alt, u16 svid)
299 {
300         u8 mode = 1;
301         int i;
302
303         for (i = 0; alt[i]; i++) {
304                 if (i > MODE_DISCOVERY_MAX)
305                         return -ERANGE;
306
307                 if (alt[i]->svid == svid)
308                         mode++;
309         }
310
311         return mode;
312 }
313
314 static int ucsi_next_altmode(struct typec_altmode **alt)
315 {
316         int i = 0;
317
318         for (i = 0; i < UCSI_MAX_ALTMODES; i++)
319                 if (!alt[i])
320                         return i;
321
322         return -ENOENT;
323 }
324
325 static int ucsi_get_num_altmode(struct typec_altmode **alt)
326 {
327         int i;
328
329         for (i = 0; i < UCSI_MAX_ALTMODES; i++)
330                 if (!alt[i])
331                         break;
332
333         return i;
334 }
335
336 static int ucsi_register_altmode(struct ucsi_connector *con,
337                                  struct typec_altmode_desc *desc,
338                                  u8 recipient)
339 {
340         struct typec_altmode *alt;
341         bool override;
342         int ret;
343         int i;
344
345         override = !!(con->ucsi->cap.features & UCSI_CAP_ALT_MODE_OVERRIDE);
346
347         switch (recipient) {
348         case UCSI_RECIPIENT_CON:
349                 i = ucsi_next_altmode(con->port_altmode);
350                 if (i < 0) {
351                         ret = i;
352                         goto err;
353                 }
354
355                 ret = ucsi_altmode_next_mode(con->port_altmode, desc->svid);
356                 if (ret < 0)
357                         return ret;
358
359                 desc->mode = ret;
360
361                 switch (desc->svid) {
362                 case USB_TYPEC_DP_SID:
363                         alt = ucsi_register_displayport(con, override, i, desc);
364                         break;
365                 case USB_TYPEC_NVIDIA_VLINK_SID:
366                         if (desc->vdo == USB_TYPEC_NVIDIA_VLINK_DBG_VDO)
367                                 alt = typec_port_register_altmode(con->port,
368                                                                   desc);
369                         else
370                                 alt = ucsi_register_displayport(con, override,
371                                                                 i, desc);
372                         break;
373                 default:
374                         alt = typec_port_register_altmode(con->port, desc);
375                         break;
376                 }
377
378                 if (IS_ERR(alt)) {
379                         ret = PTR_ERR(alt);
380                         goto err;
381                 }
382
383                 con->port_altmode[i] = alt;
384                 break;
385         case UCSI_RECIPIENT_SOP:
386                 i = ucsi_next_altmode(con->partner_altmode);
387                 if (i < 0) {
388                         ret = i;
389                         goto err;
390                 }
391
392                 ret = ucsi_altmode_next_mode(con->partner_altmode, desc->svid);
393                 if (ret < 0)
394                         return ret;
395
396                 desc->mode = ret;
397
398                 alt = typec_partner_register_altmode(con->partner, desc);
399                 if (IS_ERR(alt)) {
400                         ret = PTR_ERR(alt);
401                         goto err;
402                 }
403
404                 con->partner_altmode[i] = alt;
405                 break;
406         default:
407                 return -EINVAL;
408         }
409
410         trace_ucsi_register_altmode(recipient, alt);
411
412         return 0;
413
414 err:
415         dev_err(con->ucsi->dev, "failed to registers svid 0x%04x mode %d\n",
416                 desc->svid, desc->mode);
417
418         return ret;
419 }
420
421 static int
422 ucsi_register_altmodes_nvidia(struct ucsi_connector *con, u8 recipient)
423 {
424         int max_altmodes = UCSI_MAX_ALTMODES;
425         struct typec_altmode_desc desc;
426         struct ucsi_altmode alt;
427         struct ucsi_altmode orig[UCSI_MAX_ALTMODES];
428         struct ucsi_altmode updated[UCSI_MAX_ALTMODES];
429         struct ucsi *ucsi = con->ucsi;
430         bool multi_dp = false;
431         u64 command;
432         int ret;
433         int len;
434         int i;
435         int k = 0;
436
437         if (recipient == UCSI_RECIPIENT_CON)
438                 max_altmodes = con->ucsi->cap.num_alt_modes;
439
440         memset(orig, 0, sizeof(orig));
441         memset(updated, 0, sizeof(updated));
442
443         /* First get all the alternate modes */
444         for (i = 0; i < max_altmodes; i++) {
445                 memset(&alt, 0, sizeof(alt));
446                 command = UCSI_GET_ALTERNATE_MODES;
447                 command |= UCSI_GET_ALTMODE_RECIPIENT(recipient);
448                 command |= UCSI_GET_ALTMODE_CONNECTOR_NUMBER(con->num);
449                 command |= UCSI_GET_ALTMODE_OFFSET(i);
450                 len = ucsi_send_command(con->ucsi, command, &alt, sizeof(alt));
451                 /*
452                  * We are collecting all altmodes first and then registering.
453                  * Some type-C device will return zero length data beyond last
454                  * alternate modes. We should not return if length is zero.
455                  */
456                 if (len < 0)
457                         return len;
458
459                 /* We got all altmodes, now break out and register them */
460                 if (!len || !alt.svid)
461                         break;
462
463                 orig[k].mid = alt.mid;
464                 orig[k].svid = alt.svid;
465                 k++;
466         }
467         /*
468          * Update the original altmode table as some ppms may report
469          * multiple DP altmodes.
470          */
471         if (recipient == UCSI_RECIPIENT_CON)
472                 multi_dp = ucsi->ops->update_altmodes(ucsi, orig, updated);
473
474         /* now register altmodes */
475         for (i = 0; i < max_altmodes; i++) {
476                 memset(&desc, 0, sizeof(desc));
477                 if (multi_dp && recipient == UCSI_RECIPIENT_CON) {
478                         desc.svid = updated[i].svid;
479                         desc.vdo = updated[i].mid;
480                 } else {
481                         desc.svid = orig[i].svid;
482                         desc.vdo = orig[i].mid;
483                 }
484                 desc.roles = TYPEC_PORT_DRD;
485
486                 if (!desc.svid)
487                         return 0;
488
489                 ret = ucsi_register_altmode(con, &desc, recipient);
490                 if (ret)
491                         return ret;
492         }
493
494         return 0;
495 }
496
497 static int ucsi_register_altmodes(struct ucsi_connector *con, u8 recipient)
498 {
499         int max_altmodes = UCSI_MAX_ALTMODES;
500         struct typec_altmode_desc desc;
501         struct ucsi_altmode alt[2];
502         u64 command;
503         int num;
504         int ret;
505         int len;
506         int j;
507         int i;
508
509         if (!(con->ucsi->cap.features & UCSI_CAP_ALT_MODE_DETAILS))
510                 return 0;
511
512         if (recipient == UCSI_RECIPIENT_SOP && con->partner_altmode[0])
513                 return 0;
514
515         if (con->ucsi->ops->update_altmodes)
516                 return ucsi_register_altmodes_nvidia(con, recipient);
517
518         if (recipient == UCSI_RECIPIENT_CON)
519                 max_altmodes = con->ucsi->cap.num_alt_modes;
520
521         for (i = 0; i < max_altmodes;) {
522                 memset(alt, 0, sizeof(alt));
523                 command = UCSI_GET_ALTERNATE_MODES;
524                 command |= UCSI_GET_ALTMODE_RECIPIENT(recipient);
525                 command |= UCSI_GET_ALTMODE_CONNECTOR_NUMBER(con->num);
526                 command |= UCSI_GET_ALTMODE_OFFSET(i);
527                 len = ucsi_send_command(con->ucsi, command, alt, sizeof(alt));
528                 if (len == -EBUSY)
529                         continue;
530                 if (len <= 0)
531                         return len;
532
533                 /*
534                  * This code is requesting one alt mode at a time, but some PPMs
535                  * may still return two. If that happens both alt modes need be
536                  * registered and the offset for the next alt mode has to be
537                  * incremented.
538                  */
539                 num = len / sizeof(alt[0]);
540                 i += num;
541
542                 for (j = 0; j < num; j++) {
543                         if (!alt[j].svid)
544                                 return 0;
545
546                         memset(&desc, 0, sizeof(desc));
547                         desc.vdo = alt[j].mid;
548                         desc.svid = alt[j].svid;
549                         desc.roles = TYPEC_PORT_DRD;
550
551                         ret = ucsi_register_altmode(con, &desc, recipient);
552                         if (ret)
553                                 return ret;
554                 }
555         }
556
557         return 0;
558 }
559
560 static void ucsi_unregister_altmodes(struct ucsi_connector *con, u8 recipient)
561 {
562         const struct typec_altmode *pdev;
563         struct typec_altmode **adev;
564         int i = 0;
565
566         switch (recipient) {
567         case UCSI_RECIPIENT_CON:
568                 adev = con->port_altmode;
569                 break;
570         case UCSI_RECIPIENT_SOP:
571                 adev = con->partner_altmode;
572                 break;
573         default:
574                 return;
575         }
576
577         while (adev[i]) {
578                 if (recipient == UCSI_RECIPIENT_SOP &&
579                     (adev[i]->svid == USB_TYPEC_DP_SID ||
580                         (adev[i]->svid == USB_TYPEC_NVIDIA_VLINK_SID &&
581                         adev[i]->vdo != USB_TYPEC_NVIDIA_VLINK_DBG_VDO))) {
582                         pdev = typec_altmode_get_partner(adev[i]);
583                         ucsi_displayport_remove_partner((void *)pdev);
584                 }
585                 typec_unregister_altmode(adev[i]);
586                 adev[i++] = NULL;
587         }
588 }
589
590 static int ucsi_read_pdos(struct ucsi_connector *con,
591                           enum typec_role role, int is_partner,
592                           u32 *pdos, int offset, int num_pdos)
593 {
594         struct ucsi *ucsi = con->ucsi;
595         u64 command;
596         int ret;
597
598         if (ucsi->quirks & UCSI_NO_PARTNER_PDOS)
599                 return 0;
600
601         command = UCSI_COMMAND(UCSI_GET_PDOS) | UCSI_CONNECTOR_NUMBER(con->num);
602         command |= UCSI_GET_PDOS_PARTNER_PDO(is_partner);
603         command |= UCSI_GET_PDOS_PDO_OFFSET(offset);
604         command |= UCSI_GET_PDOS_NUM_PDOS(num_pdos - 1);
605         command |= is_source(role) ? UCSI_GET_PDOS_SRC_PDOS : 0;
606         ret = ucsi_send_command(ucsi, command, pdos + offset,
607                                 num_pdos * sizeof(u32));
608         if (ret < 0 && ret != -ETIMEDOUT)
609                 dev_err(ucsi->dev, "UCSI_GET_PDOS failed (%d)\n", ret);
610
611         return ret;
612 }
613
614 static int ucsi_get_pdos(struct ucsi_connector *con, enum typec_role role,
615                          int is_partner, u32 *pdos)
616 {
617         u8 num_pdos;
618         int ret;
619
620         /* UCSI max payload means only getting at most 4 PDOs at a time */
621         ret = ucsi_read_pdos(con, role, is_partner, pdos, 0, UCSI_MAX_PDOS);
622         if (ret < 0)
623                 return ret;
624
625         num_pdos = ret / sizeof(u32); /* number of bytes to 32-bit PDOs */
626         if (num_pdos < UCSI_MAX_PDOS)
627                 return num_pdos;
628
629         /* get the remaining PDOs, if any */
630         ret = ucsi_read_pdos(con, role, is_partner, pdos, UCSI_MAX_PDOS,
631                              PDO_MAX_OBJECTS - UCSI_MAX_PDOS);
632         if (ret < 0)
633                 return ret;
634
635         return ret / sizeof(u32) + num_pdos;
636 }
637
638 static int ucsi_get_src_pdos(struct ucsi_connector *con)
639 {
640         int ret;
641
642         ret = ucsi_get_pdos(con, TYPEC_SOURCE, 1, con->src_pdos);
643         if (ret < 0)
644                 return ret;
645
646         con->num_pdos = ret;
647
648         ucsi_port_psy_changed(con);
649
650         return ret;
651 }
652
653 static int ucsi_check_altmodes(struct ucsi_connector *con)
654 {
655         int ret, num_partner_am;
656
657         ret = ucsi_register_altmodes(con, UCSI_RECIPIENT_SOP);
658         if (ret && ret != -ETIMEDOUT)
659                 dev_err(con->ucsi->dev,
660                         "con%d: failed to register partner alt modes (%d)\n",
661                         con->num, ret);
662
663         /* Ignoring the errors in this case. */
664         if (con->partner_altmode[0]) {
665                 num_partner_am = ucsi_get_num_altmode(con->partner_altmode);
666                 if (num_partner_am > 0)
667                         typec_partner_set_num_altmodes(con->partner, num_partner_am);
668                 ucsi_altmode_update_active(con);
669                 return 0;
670         }
671
672         return ret;
673 }
674
675 static int ucsi_register_partner_pdos(struct ucsi_connector *con)
676 {
677         struct usb_power_delivery_desc desc = { con->ucsi->cap.pd_version };
678         struct usb_power_delivery_capabilities_desc caps;
679         struct usb_power_delivery_capabilities *cap;
680         int ret;
681
682         if (con->partner_pd)
683                 return 0;
684
685         con->partner_pd = usb_power_delivery_register(NULL, &desc);
686         if (IS_ERR(con->partner_pd))
687                 return PTR_ERR(con->partner_pd);
688
689         ret = ucsi_get_pdos(con, TYPEC_SOURCE, 1, caps.pdo);
690         if (ret > 0) {
691                 if (ret < PDO_MAX_OBJECTS)
692                         caps.pdo[ret] = 0;
693
694                 caps.role = TYPEC_SOURCE;
695                 cap = usb_power_delivery_register_capabilities(con->partner_pd, &caps);
696                 if (IS_ERR(cap))
697                         return PTR_ERR(cap);
698
699                 con->partner_source_caps = cap;
700
701                 ret = typec_partner_set_usb_power_delivery(con->partner, con->partner_pd);
702                 if (ret) {
703                         usb_power_delivery_unregister_capabilities(con->partner_source_caps);
704                         return ret;
705                 }
706         }
707
708         ret = ucsi_get_pdos(con, TYPEC_SINK, 1, caps.pdo);
709         if (ret > 0) {
710                 if (ret < PDO_MAX_OBJECTS)
711                         caps.pdo[ret] = 0;
712
713                 caps.role = TYPEC_SINK;
714
715                 cap = usb_power_delivery_register_capabilities(con->partner_pd, &caps);
716                 if (IS_ERR(cap))
717                         return PTR_ERR(cap);
718
719                 con->partner_sink_caps = cap;
720
721                 ret = typec_partner_set_usb_power_delivery(con->partner, con->partner_pd);
722                 if (ret) {
723                         usb_power_delivery_unregister_capabilities(con->partner_sink_caps);
724                         return ret;
725                 }
726         }
727
728         return 0;
729 }
730
731 static void ucsi_unregister_partner_pdos(struct ucsi_connector *con)
732 {
733         usb_power_delivery_unregister_capabilities(con->partner_sink_caps);
734         con->partner_sink_caps = NULL;
735         usb_power_delivery_unregister_capabilities(con->partner_source_caps);
736         con->partner_source_caps = NULL;
737         usb_power_delivery_unregister(con->partner_pd);
738         con->partner_pd = NULL;
739 }
740
741 static void ucsi_pwr_opmode_change(struct ucsi_connector *con)
742 {
743         switch (UCSI_CONSTAT_PWR_OPMODE(con->status.flags)) {
744         case UCSI_CONSTAT_PWR_OPMODE_PD:
745                 con->rdo = con->status.request_data_obj;
746                 typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_PD);
747                 ucsi_partner_task(con, ucsi_get_src_pdos, 30, 0);
748                 ucsi_partner_task(con, ucsi_check_altmodes, 30, 0);
749                 ucsi_partner_task(con, ucsi_register_partner_pdos, 1, HZ);
750                 break;
751         case UCSI_CONSTAT_PWR_OPMODE_TYPEC1_5:
752                 con->rdo = 0;
753                 typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_1_5A);
754                 break;
755         case UCSI_CONSTAT_PWR_OPMODE_TYPEC3_0:
756                 con->rdo = 0;
757                 typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_3_0A);
758                 break;
759         default:
760                 con->rdo = 0;
761                 typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_USB);
762                 break;
763         }
764 }
765
766 static int ucsi_register_partner(struct ucsi_connector *con)
767 {
768         u8 pwr_opmode = UCSI_CONSTAT_PWR_OPMODE(con->status.flags);
769         struct typec_partner_desc desc;
770         struct typec_partner *partner;
771
772         if (con->partner)
773                 return 0;
774
775         memset(&desc, 0, sizeof(desc));
776
777         switch (UCSI_CONSTAT_PARTNER_TYPE(con->status.flags)) {
778         case UCSI_CONSTAT_PARTNER_TYPE_DEBUG:
779                 desc.accessory = TYPEC_ACCESSORY_DEBUG;
780                 break;
781         case UCSI_CONSTAT_PARTNER_TYPE_AUDIO:
782                 desc.accessory = TYPEC_ACCESSORY_AUDIO;
783                 break;
784         default:
785                 break;
786         }
787
788         desc.usb_pd = pwr_opmode == UCSI_CONSTAT_PWR_OPMODE_PD;
789
790         partner = typec_register_partner(con->port, &desc);
791         if (IS_ERR(partner)) {
792                 dev_err(con->ucsi->dev,
793                         "con%d: failed to register partner (%ld)\n", con->num,
794                         PTR_ERR(partner));
795                 return PTR_ERR(partner);
796         }
797
798         con->partner = partner;
799
800         return 0;
801 }
802
803 static void ucsi_unregister_partner(struct ucsi_connector *con)
804 {
805         if (!con->partner)
806                 return;
807
808         typec_set_mode(con->port, TYPEC_STATE_SAFE);
809
810         typec_partner_set_usb_power_delivery(con->partner, NULL);
811         ucsi_unregister_partner_pdos(con);
812         ucsi_unregister_altmodes(con, UCSI_RECIPIENT_SOP);
813         typec_unregister_partner(con->partner);
814         con->partner = NULL;
815 }
816
817 static void ucsi_partner_change(struct ucsi_connector *con)
818 {
819         enum usb_role u_role = USB_ROLE_NONE;
820         int ret;
821
822         switch (UCSI_CONSTAT_PARTNER_TYPE(con->status.flags)) {
823         case UCSI_CONSTAT_PARTNER_TYPE_UFP:
824         case UCSI_CONSTAT_PARTNER_TYPE_CABLE_AND_UFP:
825                 u_role = USB_ROLE_HOST;
826                 fallthrough;
827         case UCSI_CONSTAT_PARTNER_TYPE_CABLE:
828                 typec_set_data_role(con->port, TYPEC_HOST);
829                 break;
830         case UCSI_CONSTAT_PARTNER_TYPE_DFP:
831                 u_role = USB_ROLE_DEVICE;
832                 typec_set_data_role(con->port, TYPEC_DEVICE);
833                 break;
834         default:
835                 break;
836         }
837
838         if (con->status.flags & UCSI_CONSTAT_CONNECTED) {
839                 switch (UCSI_CONSTAT_PARTNER_TYPE(con->status.flags)) {
840                 case UCSI_CONSTAT_PARTNER_TYPE_DEBUG:
841                         typec_set_mode(con->port, TYPEC_MODE_DEBUG);
842                         break;
843                 case UCSI_CONSTAT_PARTNER_TYPE_AUDIO:
844                         typec_set_mode(con->port, TYPEC_MODE_AUDIO);
845                         break;
846                 default:
847                         if (UCSI_CONSTAT_PARTNER_FLAGS(con->status.flags) ==
848                                         UCSI_CONSTAT_PARTNER_FLAG_USB)
849                                 typec_set_mode(con->port, TYPEC_STATE_USB);
850                 }
851         }
852
853         /* Only notify USB controller if partner supports USB data */
854         if (!(UCSI_CONSTAT_PARTNER_FLAGS(con->status.flags) & UCSI_CONSTAT_PARTNER_FLAG_USB))
855                 u_role = USB_ROLE_NONE;
856
857         ret = usb_role_switch_set_role(con->usb_role_sw, u_role);
858         if (ret)
859                 dev_err(con->ucsi->dev, "con:%d: failed to set usb role:%d\n",
860                         con->num, u_role);
861 }
862
863 static int ucsi_check_connection(struct ucsi_connector *con)
864 {
865         u8 prev_flags = con->status.flags;
866         u64 command;
867         int ret;
868
869         command = UCSI_GET_CONNECTOR_STATUS | UCSI_CONNECTOR_NUMBER(con->num);
870         ret = ucsi_send_command(con->ucsi, command, &con->status, sizeof(con->status));
871         if (ret < 0) {
872                 dev_err(con->ucsi->dev, "GET_CONNECTOR_STATUS failed (%d)\n", ret);
873                 return ret;
874         }
875
876         if (con->status.flags == prev_flags)
877                 return 0;
878
879         if (con->status.flags & UCSI_CONSTAT_CONNECTED) {
880                 ucsi_register_partner(con);
881                 ucsi_pwr_opmode_change(con);
882                 ucsi_partner_change(con);
883         } else {
884                 ucsi_partner_change(con);
885                 ucsi_port_psy_changed(con);
886                 ucsi_unregister_partner(con);
887         }
888
889         return 0;
890 }
891
892 static void ucsi_handle_connector_change(struct work_struct *work)
893 {
894         struct ucsi_connector *con = container_of(work, struct ucsi_connector,
895                                                   work);
896         struct ucsi *ucsi = con->ucsi;
897         enum typec_role role;
898         u64 command;
899         int ret;
900
901         mutex_lock(&con->lock);
902
903         command = UCSI_GET_CONNECTOR_STATUS | UCSI_CONNECTOR_NUMBER(con->num);
904         ret = ucsi_send_command(ucsi, command, &con->status, sizeof(con->status));
905         if (ret < 0) {
906                 dev_err(ucsi->dev, "%s: GET_CONNECTOR_STATUS failed (%d)\n",
907                         __func__, ret);
908                 clear_bit(EVENT_PENDING, &con->ucsi->flags);
909                 goto out_unlock;
910         }
911
912         trace_ucsi_connector_change(con->num, &con->status);
913
914         role = !!(con->status.flags & UCSI_CONSTAT_PWR_DIR);
915
916         if (con->status.change & UCSI_CONSTAT_POWER_DIR_CHANGE) {
917                 typec_set_pwr_role(con->port, role);
918
919                 /* Complete pending power role swap */
920                 if (!completion_done(&con->complete))
921                         complete(&con->complete);
922         }
923
924         if (con->status.change & UCSI_CONSTAT_CONNECT_CHANGE) {
925                 typec_set_pwr_role(con->port, role);
926                 ucsi_port_psy_changed(con);
927                 ucsi_partner_change(con);
928
929                 if (con->status.flags & UCSI_CONSTAT_CONNECTED) {
930                         ucsi_register_partner(con);
931                         ucsi_partner_task(con, ucsi_check_connection, 1, HZ);
932
933                         if (UCSI_CONSTAT_PWR_OPMODE(con->status.flags) ==
934                             UCSI_CONSTAT_PWR_OPMODE_PD)
935                                 ucsi_partner_task(con, ucsi_register_partner_pdos, 1, HZ);
936                 } else {
937                         ucsi_unregister_partner(con);
938                 }
939         }
940
941         if (con->status.change & UCSI_CONSTAT_POWER_OPMODE_CHANGE ||
942             con->status.change & UCSI_CONSTAT_POWER_LEVEL_CHANGE)
943                 ucsi_pwr_opmode_change(con);
944
945         if (con->partner && con->status.change & UCSI_CONSTAT_PARTNER_CHANGE) {
946                 ucsi_partner_change(con);
947
948                 /* Complete pending data role swap */
949                 if (!completion_done(&con->complete))
950                         complete(&con->complete);
951         }
952
953         if (con->status.change & UCSI_CONSTAT_CAM_CHANGE)
954                 ucsi_partner_task(con, ucsi_check_altmodes, 1, 0);
955
956         mutex_lock(&ucsi->ppm_lock);
957         clear_bit(EVENT_PENDING, &con->ucsi->flags);
958         ret = ucsi_acknowledge_connector_change(ucsi);
959         mutex_unlock(&ucsi->ppm_lock);
960
961         if (ret)
962                 dev_err(ucsi->dev, "%s: ACK failed (%d)", __func__, ret);
963
964 out_unlock:
965         mutex_unlock(&con->lock);
966 }
967
968 /**
969  * ucsi_connector_change - Process Connector Change Event
970  * @ucsi: UCSI Interface
971  * @num: Connector number
972  */
973 void ucsi_connector_change(struct ucsi *ucsi, u8 num)
974 {
975         struct ucsi_connector *con = &ucsi->connector[num - 1];
976
977         if (!(ucsi->ntfy & UCSI_ENABLE_NTFY_CONNECTOR_CHANGE)) {
978                 dev_dbg(ucsi->dev, "Bogus connector change event\n");
979                 return;
980         }
981
982         if (!test_and_set_bit(EVENT_PENDING, &ucsi->flags))
983                 schedule_work(&con->work);
984 }
985 EXPORT_SYMBOL_GPL(ucsi_connector_change);
986
987 /* -------------------------------------------------------------------------- */
988
989 static int ucsi_reset_connector(struct ucsi_connector *con, bool hard)
990 {
991         u64 command;
992
993         command = UCSI_CONNECTOR_RESET | UCSI_CONNECTOR_NUMBER(con->num);
994         command |= hard ? UCSI_CONNECTOR_RESET_HARD : 0;
995
996         return ucsi_send_command(con->ucsi, command, NULL, 0);
997 }
998
999 static int ucsi_reset_ppm(struct ucsi *ucsi)
1000 {
1001         u64 command;
1002         unsigned long tmo;
1003         u32 cci;
1004         int ret;
1005
1006         mutex_lock(&ucsi->ppm_lock);
1007
1008         ret = ucsi->ops->read(ucsi, UCSI_CCI, &cci, sizeof(cci));
1009         if (ret < 0)
1010                 goto out;
1011
1012         /*
1013          * If UCSI_CCI_RESET_COMPLETE is already set we must clear
1014          * the flag before we start another reset. Send a
1015          * UCSI_SET_NOTIFICATION_ENABLE command to achieve this.
1016          * Ignore a timeout and try the reset anyway if this fails.
1017          */
1018         if (cci & UCSI_CCI_RESET_COMPLETE) {
1019                 command = UCSI_SET_NOTIFICATION_ENABLE;
1020                 ret = ucsi->ops->async_write(ucsi, UCSI_CONTROL, &command,
1021                                              sizeof(command));
1022                 if (ret < 0)
1023                         goto out;
1024
1025                 tmo = jiffies + msecs_to_jiffies(UCSI_TIMEOUT_MS);
1026                 do {
1027                         ret = ucsi->ops->read(ucsi, UCSI_CCI,
1028                                               &cci, sizeof(cci));
1029                         if (ret < 0)
1030                                 goto out;
1031                         if (cci & UCSI_CCI_COMMAND_COMPLETE)
1032                                 break;
1033                         if (time_is_before_jiffies(tmo))
1034                                 break;
1035                         msleep(20);
1036                 } while (1);
1037
1038                 WARN_ON(cci & UCSI_CCI_RESET_COMPLETE);
1039         }
1040
1041         command = UCSI_PPM_RESET;
1042         ret = ucsi->ops->async_write(ucsi, UCSI_CONTROL, &command,
1043                                      sizeof(command));
1044         if (ret < 0)
1045                 goto out;
1046
1047         tmo = jiffies + msecs_to_jiffies(UCSI_TIMEOUT_MS);
1048
1049         do {
1050                 if (time_is_before_jiffies(tmo)) {
1051                         ret = -ETIMEDOUT;
1052                         goto out;
1053                 }
1054
1055                 ret = ucsi->ops->read(ucsi, UCSI_CCI, &cci, sizeof(cci));
1056                 if (ret)
1057                         goto out;
1058
1059                 /* If the PPM is still doing something else, reset it again. */
1060                 if (cci & ~UCSI_CCI_RESET_COMPLETE) {
1061                         ret = ucsi->ops->async_write(ucsi, UCSI_CONTROL,
1062                                                      &command,
1063                                                      sizeof(command));
1064                         if (ret < 0)
1065                                 goto out;
1066                 }
1067
1068                 msleep(20);
1069         } while (!(cci & UCSI_CCI_RESET_COMPLETE));
1070
1071 out:
1072         mutex_unlock(&ucsi->ppm_lock);
1073         return ret;
1074 }
1075
1076 static int ucsi_role_cmd(struct ucsi_connector *con, u64 command)
1077 {
1078         int ret;
1079
1080         ret = ucsi_send_command(con->ucsi, command, NULL, 0);
1081         if (ret == -ETIMEDOUT) {
1082                 u64 c;
1083
1084                 /* PPM most likely stopped responding. Resetting everything. */
1085                 ucsi_reset_ppm(con->ucsi);
1086
1087                 c = UCSI_SET_NOTIFICATION_ENABLE | con->ucsi->ntfy;
1088                 ucsi_send_command(con->ucsi, c, NULL, 0);
1089
1090                 ucsi_reset_connector(con, true);
1091         }
1092
1093         return ret;
1094 }
1095
1096 static int ucsi_dr_swap(struct typec_port *port, enum typec_data_role role)
1097 {
1098         struct ucsi_connector *con = typec_get_drvdata(port);
1099         u8 partner_type;
1100         u64 command;
1101         int ret = 0;
1102
1103         mutex_lock(&con->lock);
1104
1105         if (!con->partner) {
1106                 ret = -ENOTCONN;
1107                 goto out_unlock;
1108         }
1109
1110         partner_type = UCSI_CONSTAT_PARTNER_TYPE(con->status.flags);
1111         if ((partner_type == UCSI_CONSTAT_PARTNER_TYPE_DFP &&
1112              role == TYPEC_DEVICE) ||
1113             (partner_type == UCSI_CONSTAT_PARTNER_TYPE_UFP &&
1114              role == TYPEC_HOST))
1115                 goto out_unlock;
1116
1117         reinit_completion(&con->complete);
1118
1119         command = UCSI_SET_UOR | UCSI_CONNECTOR_NUMBER(con->num);
1120         command |= UCSI_SET_UOR_ROLE(role);
1121         command |= UCSI_SET_UOR_ACCEPT_ROLE_SWAPS;
1122         ret = ucsi_role_cmd(con, command);
1123         if (ret < 0)
1124                 goto out_unlock;
1125
1126         mutex_unlock(&con->lock);
1127
1128         if (!wait_for_completion_timeout(&con->complete,
1129                                          msecs_to_jiffies(UCSI_SWAP_TIMEOUT_MS)))
1130                 return -ETIMEDOUT;
1131
1132         return 0;
1133
1134 out_unlock:
1135         mutex_unlock(&con->lock);
1136
1137         return ret;
1138 }
1139
1140 static int ucsi_pr_swap(struct typec_port *port, enum typec_role role)
1141 {
1142         struct ucsi_connector *con = typec_get_drvdata(port);
1143         enum typec_role cur_role;
1144         u64 command;
1145         int ret = 0;
1146
1147         mutex_lock(&con->lock);
1148
1149         if (!con->partner) {
1150                 ret = -ENOTCONN;
1151                 goto out_unlock;
1152         }
1153
1154         cur_role = !!(con->status.flags & UCSI_CONSTAT_PWR_DIR);
1155
1156         if (cur_role == role)
1157                 goto out_unlock;
1158
1159         reinit_completion(&con->complete);
1160
1161         command = UCSI_SET_PDR | UCSI_CONNECTOR_NUMBER(con->num);
1162         command |= UCSI_SET_PDR_ROLE(role);
1163         command |= UCSI_SET_PDR_ACCEPT_ROLE_SWAPS;
1164         ret = ucsi_role_cmd(con, command);
1165         if (ret < 0)
1166                 goto out_unlock;
1167
1168         mutex_unlock(&con->lock);
1169
1170         if (!wait_for_completion_timeout(&con->complete,
1171                                          msecs_to_jiffies(UCSI_SWAP_TIMEOUT_MS)))
1172                 return -ETIMEDOUT;
1173
1174         mutex_lock(&con->lock);
1175
1176         /* Something has gone wrong while swapping the role */
1177         if (UCSI_CONSTAT_PWR_OPMODE(con->status.flags) !=
1178             UCSI_CONSTAT_PWR_OPMODE_PD) {
1179                 ucsi_reset_connector(con, true);
1180                 ret = -EPROTO;
1181         }
1182
1183 out_unlock:
1184         mutex_unlock(&con->lock);
1185
1186         return ret;
1187 }
1188
1189 static const struct typec_operations ucsi_ops = {
1190         .dr_set = ucsi_dr_swap,
1191         .pr_set = ucsi_pr_swap
1192 };
1193
1194 /* Caller must call fwnode_handle_put() after use */
1195 static struct fwnode_handle *ucsi_find_fwnode(struct ucsi_connector *con)
1196 {
1197         struct fwnode_handle *fwnode;
1198         int i = 1;
1199
1200         device_for_each_child_node(con->ucsi->dev, fwnode)
1201                 if (i++ == con->num)
1202                         return fwnode;
1203         return NULL;
1204 }
1205
1206 static int ucsi_register_port(struct ucsi *ucsi, struct ucsi_connector *con)
1207 {
1208         struct usb_power_delivery_desc desc = { ucsi->cap.pd_version};
1209         struct usb_power_delivery_capabilities_desc pd_caps;
1210         struct usb_power_delivery_capabilities *pd_cap;
1211         struct typec_capability *cap = &con->typec_cap;
1212         enum typec_accessory *accessory = cap->accessory;
1213         enum usb_role u_role = USB_ROLE_NONE;
1214         u64 command;
1215         char *name;
1216         int ret;
1217
1218         name = kasprintf(GFP_KERNEL, "%s-con%d", dev_name(ucsi->dev), con->num);
1219         if (!name)
1220                 return -ENOMEM;
1221
1222         con->wq = create_singlethread_workqueue(name);
1223         kfree(name);
1224         if (!con->wq)
1225                 return -ENOMEM;
1226
1227         INIT_WORK(&con->work, ucsi_handle_connector_change);
1228         init_completion(&con->complete);
1229         mutex_init(&con->lock);
1230         INIT_LIST_HEAD(&con->partner_tasks);
1231         con->ucsi = ucsi;
1232
1233         cap->fwnode = ucsi_find_fwnode(con);
1234         con->usb_role_sw = fwnode_usb_role_switch_get(cap->fwnode);
1235         if (IS_ERR(con->usb_role_sw))
1236                 return dev_err_probe(ucsi->dev, PTR_ERR(con->usb_role_sw),
1237                         "con%d: failed to get usb role switch\n", con->num);
1238
1239         /* Delay other interactions with the con until registration is complete */
1240         mutex_lock(&con->lock);
1241
1242         /* Get connector capability */
1243         command = UCSI_GET_CONNECTOR_CAPABILITY;
1244         command |= UCSI_CONNECTOR_NUMBER(con->num);
1245         ret = ucsi_send_command(ucsi, command, &con->cap, sizeof(con->cap));
1246         if (ret < 0)
1247                 goto out_unlock;
1248
1249         if (con->cap.op_mode & UCSI_CONCAP_OPMODE_DRP)
1250                 cap->data = TYPEC_PORT_DRD;
1251         else if (con->cap.op_mode & UCSI_CONCAP_OPMODE_DFP)
1252                 cap->data = TYPEC_PORT_DFP;
1253         else if (con->cap.op_mode & UCSI_CONCAP_OPMODE_UFP)
1254                 cap->data = TYPEC_PORT_UFP;
1255
1256         if ((con->cap.flags & UCSI_CONCAP_FLAG_PROVIDER) &&
1257             (con->cap.flags & UCSI_CONCAP_FLAG_CONSUMER))
1258                 cap->type = TYPEC_PORT_DRP;
1259         else if (con->cap.flags & UCSI_CONCAP_FLAG_PROVIDER)
1260                 cap->type = TYPEC_PORT_SRC;
1261         else if (con->cap.flags & UCSI_CONCAP_FLAG_CONSUMER)
1262                 cap->type = TYPEC_PORT_SNK;
1263
1264         cap->revision = ucsi->cap.typec_version;
1265         cap->pd_revision = ucsi->cap.pd_version;
1266         cap->svdm_version = SVDM_VER_2_0;
1267         cap->prefer_role = TYPEC_NO_PREFERRED_ROLE;
1268
1269         if (con->cap.op_mode & UCSI_CONCAP_OPMODE_AUDIO_ACCESSORY)
1270                 *accessory++ = TYPEC_ACCESSORY_AUDIO;
1271         if (con->cap.op_mode & UCSI_CONCAP_OPMODE_DEBUG_ACCESSORY)
1272                 *accessory = TYPEC_ACCESSORY_DEBUG;
1273
1274         cap->driver_data = con;
1275         cap->ops = &ucsi_ops;
1276
1277         ret = ucsi_register_port_psy(con);
1278         if (ret)
1279                 goto out;
1280
1281         /* Register the connector */
1282         con->port = typec_register_port(ucsi->dev, cap);
1283         if (IS_ERR(con->port)) {
1284                 ret = PTR_ERR(con->port);
1285                 goto out;
1286         }
1287
1288         con->pd = usb_power_delivery_register(ucsi->dev, &desc);
1289
1290         ret = ucsi_get_pdos(con, TYPEC_SOURCE, 0, pd_caps.pdo);
1291         if (ret > 0) {
1292                 if (ret < PDO_MAX_OBJECTS)
1293                         pd_caps.pdo[ret] = 0;
1294
1295                 pd_caps.role = TYPEC_SOURCE;
1296                 pd_cap = usb_power_delivery_register_capabilities(con->pd, &pd_caps);
1297                 if (IS_ERR(pd_cap)) {
1298                         ret = PTR_ERR(pd_cap);
1299                         goto out;
1300                 }
1301
1302                 con->port_source_caps = pd_cap;
1303                 typec_port_set_usb_power_delivery(con->port, con->pd);
1304         }
1305
1306         memset(&pd_caps, 0, sizeof(pd_caps));
1307         ret = ucsi_get_pdos(con, TYPEC_SINK, 0, pd_caps.pdo);
1308         if (ret > 0) {
1309                 if (ret < PDO_MAX_OBJECTS)
1310                         pd_caps.pdo[ret] = 0;
1311
1312                 pd_caps.role = TYPEC_SINK;
1313                 pd_cap = usb_power_delivery_register_capabilities(con->pd, &pd_caps);
1314                 if (IS_ERR(pd_cap)) {
1315                         ret = PTR_ERR(pd_cap);
1316                         goto out;
1317                 }
1318
1319                 con->port_sink_caps = pd_cap;
1320                 typec_port_set_usb_power_delivery(con->port, con->pd);
1321         }
1322
1323         /* Alternate modes */
1324         ret = ucsi_register_altmodes(con, UCSI_RECIPIENT_CON);
1325         if (ret) {
1326                 dev_err(ucsi->dev, "con%d: failed to register alt modes\n",
1327                         con->num);
1328                 goto out;
1329         }
1330
1331         /* Get the status */
1332         command = UCSI_GET_CONNECTOR_STATUS | UCSI_CONNECTOR_NUMBER(con->num);
1333         ret = ucsi_send_command(ucsi, command, &con->status, sizeof(con->status));
1334         if (ret < 0) {
1335                 dev_err(ucsi->dev, "con%d: failed to get status\n", con->num);
1336                 ret = 0;
1337                 goto out;
1338         }
1339         ret = 0; /* ucsi_send_command() returns length on success */
1340
1341         switch (UCSI_CONSTAT_PARTNER_TYPE(con->status.flags)) {
1342         case UCSI_CONSTAT_PARTNER_TYPE_UFP:
1343         case UCSI_CONSTAT_PARTNER_TYPE_CABLE_AND_UFP:
1344                 u_role = USB_ROLE_HOST;
1345                 fallthrough;
1346         case UCSI_CONSTAT_PARTNER_TYPE_CABLE:
1347                 typec_set_data_role(con->port, TYPEC_HOST);
1348                 break;
1349         case UCSI_CONSTAT_PARTNER_TYPE_DFP:
1350                 u_role = USB_ROLE_DEVICE;
1351                 typec_set_data_role(con->port, TYPEC_DEVICE);
1352                 break;
1353         default:
1354                 break;
1355         }
1356
1357         /* Check if there is already something connected */
1358         if (con->status.flags & UCSI_CONSTAT_CONNECTED) {
1359                 typec_set_pwr_role(con->port,
1360                                   !!(con->status.flags & UCSI_CONSTAT_PWR_DIR));
1361                 ucsi_register_partner(con);
1362                 ucsi_pwr_opmode_change(con);
1363                 ucsi_port_psy_changed(con);
1364         }
1365
1366         /* Only notify USB controller if partner supports USB data */
1367         if (!(UCSI_CONSTAT_PARTNER_FLAGS(con->status.flags) & UCSI_CONSTAT_PARTNER_FLAG_USB))
1368                 u_role = USB_ROLE_NONE;
1369
1370         ret = usb_role_switch_set_role(con->usb_role_sw, u_role);
1371         if (ret) {
1372                 dev_err(ucsi->dev, "con:%d: failed to set usb role:%d\n",
1373                         con->num, u_role);
1374                 ret = 0;
1375         }
1376
1377         if (con->partner &&
1378             UCSI_CONSTAT_PWR_OPMODE(con->status.flags) ==
1379             UCSI_CONSTAT_PWR_OPMODE_PD) {
1380                 ucsi_get_src_pdos(con);
1381                 ucsi_check_altmodes(con);
1382         }
1383
1384         trace_ucsi_register_port(con->num, &con->status);
1385
1386 out:
1387         fwnode_handle_put(cap->fwnode);
1388 out_unlock:
1389         mutex_unlock(&con->lock);
1390
1391         if (ret && con->wq) {
1392                 destroy_workqueue(con->wq);
1393                 con->wq = NULL;
1394         }
1395
1396         return ret;
1397 }
1398
1399 /**
1400  * ucsi_init - Initialize UCSI interface
1401  * @ucsi: UCSI to be initialized
1402  *
1403  * Registers all ports @ucsi has and enables all notification events.
1404  */
1405 static int ucsi_init(struct ucsi *ucsi)
1406 {
1407         struct ucsi_connector *con, *connector;
1408         u64 command, ntfy;
1409         int ret;
1410         int i;
1411
1412         /* Reset the PPM */
1413         ret = ucsi_reset_ppm(ucsi);
1414         if (ret) {
1415                 dev_err(ucsi->dev, "failed to reset PPM!\n");
1416                 goto err;
1417         }
1418
1419         /* Enable basic notifications */
1420         ntfy = UCSI_ENABLE_NTFY_CMD_COMPLETE | UCSI_ENABLE_NTFY_ERROR;
1421         command = UCSI_SET_NOTIFICATION_ENABLE | ntfy;
1422         ret = ucsi_send_command(ucsi, command, NULL, 0);
1423         if (ret < 0)
1424                 goto err_reset;
1425
1426         /* Get PPM capabilities */
1427         command = UCSI_GET_CAPABILITY;
1428         ret = ucsi_send_command(ucsi, command, &ucsi->cap, sizeof(ucsi->cap));
1429         if (ret < 0)
1430                 goto err_reset;
1431
1432         if (!ucsi->cap.num_connectors) {
1433                 ret = -ENODEV;
1434                 goto err_reset;
1435         }
1436
1437         /* Allocate the connectors. Released in ucsi_unregister() */
1438         connector = kcalloc(ucsi->cap.num_connectors + 1, sizeof(*connector), GFP_KERNEL);
1439         if (!connector) {
1440                 ret = -ENOMEM;
1441                 goto err_reset;
1442         }
1443
1444         /* Register all connectors */
1445         for (i = 0; i < ucsi->cap.num_connectors; i++) {
1446                 connector[i].num = i + 1;
1447                 ret = ucsi_register_port(ucsi, &connector[i]);
1448                 if (ret)
1449                         goto err_unregister;
1450         }
1451
1452         /* Enable all notifications */
1453         ntfy = UCSI_ENABLE_NTFY_ALL;
1454         command = UCSI_SET_NOTIFICATION_ENABLE | ntfy;
1455         ret = ucsi_send_command(ucsi, command, NULL, 0);
1456         if (ret < 0)
1457                 goto err_unregister;
1458
1459         ucsi->connector = connector;
1460         ucsi->ntfy = ntfy;
1461         return 0;
1462
1463 err_unregister:
1464         for (con = connector; con->port; con++) {
1465                 ucsi_unregister_partner(con);
1466                 ucsi_unregister_altmodes(con, UCSI_RECIPIENT_CON);
1467                 ucsi_unregister_port_psy(con);
1468                 if (con->wq)
1469                         destroy_workqueue(con->wq);
1470
1471                 usb_power_delivery_unregister_capabilities(con->port_sink_caps);
1472                 con->port_sink_caps = NULL;
1473                 usb_power_delivery_unregister_capabilities(con->port_source_caps);
1474                 con->port_source_caps = NULL;
1475                 usb_power_delivery_unregister(con->pd);
1476                 con->pd = NULL;
1477                 typec_unregister_port(con->port);
1478                 con->port = NULL;
1479         }
1480         kfree(connector);
1481 err_reset:
1482         memset(&ucsi->cap, 0, sizeof(ucsi->cap));
1483         ucsi_reset_ppm(ucsi);
1484 err:
1485         return ret;
1486 }
1487
1488 static void ucsi_resume_work(struct work_struct *work)
1489 {
1490         struct ucsi *ucsi = container_of(work, struct ucsi, resume_work);
1491         struct ucsi_connector *con;
1492         u64 command;
1493         int ret;
1494
1495         /* Restore UCSI notification enable mask after system resume */
1496         command = UCSI_SET_NOTIFICATION_ENABLE | ucsi->ntfy;
1497         ret = ucsi_send_command(ucsi, command, NULL, 0);
1498         if (ret < 0) {
1499                 dev_err(ucsi->dev, "failed to re-enable notifications (%d)\n", ret);
1500                 return;
1501         }
1502
1503         for (con = ucsi->connector; con->port; con++) {
1504                 mutex_lock(&con->lock);
1505                 ucsi_partner_task(con, ucsi_check_connection, 1, 0);
1506                 mutex_unlock(&con->lock);
1507         }
1508 }
1509
1510 int ucsi_resume(struct ucsi *ucsi)
1511 {
1512         if (ucsi->connector)
1513                 queue_work(system_long_wq, &ucsi->resume_work);
1514         return 0;
1515 }
1516 EXPORT_SYMBOL_GPL(ucsi_resume);
1517
1518 static void ucsi_init_work(struct work_struct *work)
1519 {
1520         struct ucsi *ucsi = container_of(work, struct ucsi, work.work);
1521         int ret;
1522
1523         ret = ucsi_init(ucsi);
1524         if (ret)
1525                 dev_err_probe(ucsi->dev, ret, "PPM init failed\n");
1526
1527         if (ret == -EPROBE_DEFER) {
1528                 if (ucsi->work_count++ > UCSI_ROLE_SWITCH_WAIT_COUNT) {
1529                         dev_err(ucsi->dev, "PPM init failed, stop trying\n");
1530                         return;
1531                 }
1532
1533                 queue_delayed_work(system_long_wq, &ucsi->work,
1534                                    UCSI_ROLE_SWITCH_INTERVAL);
1535         }
1536 }
1537
1538 /**
1539  * ucsi_get_drvdata - Return private driver data pointer
1540  * @ucsi: UCSI interface
1541  */
1542 void *ucsi_get_drvdata(struct ucsi *ucsi)
1543 {
1544         return ucsi->driver_data;
1545 }
1546 EXPORT_SYMBOL_GPL(ucsi_get_drvdata);
1547
1548 /**
1549  * ucsi_set_drvdata - Assign private driver data pointer
1550  * @ucsi: UCSI interface
1551  * @data: Private data pointer
1552  */
1553 void ucsi_set_drvdata(struct ucsi *ucsi, void *data)
1554 {
1555         ucsi->driver_data = data;
1556 }
1557 EXPORT_SYMBOL_GPL(ucsi_set_drvdata);
1558
1559 /**
1560  * ucsi_create - Allocate UCSI instance
1561  * @dev: Device interface to the PPM (Platform Policy Manager)
1562  * @ops: I/O routines
1563  */
1564 struct ucsi *ucsi_create(struct device *dev, const struct ucsi_operations *ops)
1565 {
1566         struct ucsi *ucsi;
1567
1568         if (!ops || !ops->read || !ops->sync_write || !ops->async_write)
1569                 return ERR_PTR(-EINVAL);
1570
1571         ucsi = kzalloc(sizeof(*ucsi), GFP_KERNEL);
1572         if (!ucsi)
1573                 return ERR_PTR(-ENOMEM);
1574
1575         INIT_WORK(&ucsi->resume_work, ucsi_resume_work);
1576         INIT_DELAYED_WORK(&ucsi->work, ucsi_init_work);
1577         mutex_init(&ucsi->ppm_lock);
1578         ucsi->dev = dev;
1579         ucsi->ops = ops;
1580
1581         return ucsi;
1582 }
1583 EXPORT_SYMBOL_GPL(ucsi_create);
1584
1585 /**
1586  * ucsi_destroy - Free UCSI instance
1587  * @ucsi: UCSI instance to be freed
1588  */
1589 void ucsi_destroy(struct ucsi *ucsi)
1590 {
1591         ucsi_debugfs_unregister(ucsi);
1592         kfree(ucsi);
1593 }
1594 EXPORT_SYMBOL_GPL(ucsi_destroy);
1595
1596 /**
1597  * ucsi_register - Register UCSI interface
1598  * @ucsi: UCSI instance
1599  */
1600 int ucsi_register(struct ucsi *ucsi)
1601 {
1602         int ret;
1603
1604         ret = ucsi->ops->read(ucsi, UCSI_VERSION, &ucsi->version,
1605                               sizeof(ucsi->version));
1606         if (ret)
1607                 return ret;
1608
1609         if (!ucsi->version)
1610                 return -ENODEV;
1611
1612         /*
1613          * Version format is JJ.M.N (JJ = Major version, M = Minor version,
1614          * N = sub-minor version).
1615          */
1616         dev_dbg(ucsi->dev, "Registered UCSI interface with version %x.%x.%x",
1617                 UCSI_BCD_GET_MAJOR(ucsi->version),
1618                 UCSI_BCD_GET_MINOR(ucsi->version),
1619                 UCSI_BCD_GET_SUBMINOR(ucsi->version));
1620
1621         queue_delayed_work(system_long_wq, &ucsi->work, 0);
1622
1623         ucsi_debugfs_register(ucsi);
1624         return 0;
1625 }
1626 EXPORT_SYMBOL_GPL(ucsi_register);
1627
1628 /**
1629  * ucsi_unregister - Unregister UCSI interface
1630  * @ucsi: UCSI interface to be unregistered
1631  *
1632  * Unregister UCSI interface that was created with ucsi_register().
1633  */
1634 void ucsi_unregister(struct ucsi *ucsi)
1635 {
1636         u64 cmd = UCSI_SET_NOTIFICATION_ENABLE;
1637         int i;
1638
1639         /* Make sure that we are not in the middle of driver initialization */
1640         cancel_delayed_work_sync(&ucsi->work);
1641         cancel_work_sync(&ucsi->resume_work);
1642
1643         /* Disable notifications */
1644         ucsi->ops->async_write(ucsi, UCSI_CONTROL, &cmd, sizeof(cmd));
1645
1646         if (!ucsi->connector)
1647                 return;
1648
1649         for (i = 0; i < ucsi->cap.num_connectors; i++) {
1650                 cancel_work_sync(&ucsi->connector[i].work);
1651                 ucsi_unregister_partner(&ucsi->connector[i]);
1652                 ucsi_unregister_altmodes(&ucsi->connector[i],
1653                                          UCSI_RECIPIENT_CON);
1654                 ucsi_unregister_port_psy(&ucsi->connector[i]);
1655
1656                 if (ucsi->connector[i].wq) {
1657                         struct ucsi_work *uwork;
1658
1659                         mutex_lock(&ucsi->connector[i].lock);
1660                         /*
1661                          * queue delayed items immediately so they can execute
1662                          * and free themselves before the wq is destroyed
1663                          */
1664                         list_for_each_entry(uwork, &ucsi->connector[i].partner_tasks, node)
1665                                 mod_delayed_work(ucsi->connector[i].wq, &uwork->work, 0);
1666                         mutex_unlock(&ucsi->connector[i].lock);
1667                         destroy_workqueue(ucsi->connector[i].wq);
1668                 }
1669
1670                 usb_power_delivery_unregister_capabilities(ucsi->connector[i].port_sink_caps);
1671                 ucsi->connector[i].port_sink_caps = NULL;
1672                 usb_power_delivery_unregister_capabilities(ucsi->connector[i].port_source_caps);
1673                 ucsi->connector[i].port_source_caps = NULL;
1674                 usb_power_delivery_unregister(ucsi->connector[i].pd);
1675                 ucsi->connector[i].pd = NULL;
1676                 typec_unregister_port(ucsi->connector[i].port);
1677         }
1678
1679         kfree(ucsi->connector);
1680 }
1681 EXPORT_SYMBOL_GPL(ucsi_unregister);
1682
1683 static int __init ucsi_module_init(void)
1684 {
1685         ucsi_debugfs_init();
1686         return 0;
1687 }
1688 module_init(ucsi_module_init);
1689
1690 static void __exit ucsi_module_exit(void)
1691 {
1692         ucsi_debugfs_exit();
1693 }
1694 module_exit(ucsi_module_exit);
1695
1696 MODULE_AUTHOR("Heikki Krogerus <heikki.krogerus@linux.intel.com>");
1697 MODULE_LICENSE("GPL v2");
1698 MODULE_DESCRIPTION("USB Type-C Connector System Software Interface driver");