GNU Linux-libre 5.10.153-gnu1
[releases.git] / drivers / usb / typec / tcpm / tcpm.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2015-2017 Google, Inc
4  *
5  * USB Power Delivery protocol stack.
6  */
7
8 #include <linux/completion.h>
9 #include <linux/debugfs.h>
10 #include <linux/device.h>
11 #include <linux/hrtimer.h>
12 #include <linux/jiffies.h>
13 #include <linux/kernel.h>
14 #include <linux/kthread.h>
15 #include <linux/module.h>
16 #include <linux/mutex.h>
17 #include <linux/power_supply.h>
18 #include <linux/proc_fs.h>
19 #include <linux/property.h>
20 #include <linux/sched/clock.h>
21 #include <linux/seq_file.h>
22 #include <linux/slab.h>
23 #include <linux/spinlock.h>
24 #include <linux/usb.h>
25 #include <linux/usb/pd.h>
26 #include <linux/usb/pd_ado.h>
27 #include <linux/usb/pd_bdo.h>
28 #include <linux/usb/pd_ext_sdb.h>
29 #include <linux/usb/pd_vdo.h>
30 #include <linux/usb/role.h>
31 #include <linux/usb/tcpm.h>
32 #include <linux/usb/typec_altmode.h>
33
34 #include <uapi/linux/sched/types.h>
35
36 #define FOREACH_STATE(S)                        \
37         S(INVALID_STATE),                       \
38         S(TOGGLING),                    \
39         S(SRC_UNATTACHED),                      \
40         S(SRC_ATTACH_WAIT),                     \
41         S(SRC_ATTACHED),                        \
42         S(SRC_STARTUP),                         \
43         S(SRC_SEND_CAPABILITIES),               \
44         S(SRC_SEND_CAPABILITIES_TIMEOUT),       \
45         S(SRC_NEGOTIATE_CAPABILITIES),          \
46         S(SRC_TRANSITION_SUPPLY),               \
47         S(SRC_READY),                           \
48         S(SRC_WAIT_NEW_CAPABILITIES),           \
49                                                 \
50         S(SNK_UNATTACHED),                      \
51         S(SNK_ATTACH_WAIT),                     \
52         S(SNK_DEBOUNCED),                       \
53         S(SNK_ATTACHED),                        \
54         S(SNK_STARTUP),                         \
55         S(SNK_DISCOVERY),                       \
56         S(SNK_DISCOVERY_DEBOUNCE),              \
57         S(SNK_DISCOVERY_DEBOUNCE_DONE),         \
58         S(SNK_WAIT_CAPABILITIES),               \
59         S(SNK_NEGOTIATE_CAPABILITIES),          \
60         S(SNK_NEGOTIATE_PPS_CAPABILITIES),      \
61         S(SNK_TRANSITION_SINK),                 \
62         S(SNK_TRANSITION_SINK_VBUS),            \
63         S(SNK_READY),                           \
64                                                 \
65         S(ACC_UNATTACHED),                      \
66         S(DEBUG_ACC_ATTACHED),                  \
67         S(AUDIO_ACC_ATTACHED),                  \
68         S(AUDIO_ACC_DEBOUNCE),                  \
69                                                 \
70         S(HARD_RESET_SEND),                     \
71         S(HARD_RESET_START),                    \
72         S(SRC_HARD_RESET_VBUS_OFF),             \
73         S(SRC_HARD_RESET_VBUS_ON),              \
74         S(SNK_HARD_RESET_SINK_OFF),             \
75         S(SNK_HARD_RESET_WAIT_VBUS),            \
76         S(SNK_HARD_RESET_SINK_ON),              \
77                                                 \
78         S(SOFT_RESET),                          \
79         S(SOFT_RESET_SEND),                     \
80                                                 \
81         S(DR_SWAP_ACCEPT),                      \
82         S(DR_SWAP_SEND),                        \
83         S(DR_SWAP_SEND_TIMEOUT),                \
84         S(DR_SWAP_CANCEL),                      \
85         S(DR_SWAP_CHANGE_DR),                   \
86                                                 \
87         S(PR_SWAP_ACCEPT),                      \
88         S(PR_SWAP_SEND),                        \
89         S(PR_SWAP_SEND_TIMEOUT),                \
90         S(PR_SWAP_CANCEL),                      \
91         S(PR_SWAP_START),                       \
92         S(PR_SWAP_SRC_SNK_TRANSITION_OFF),      \
93         S(PR_SWAP_SRC_SNK_SOURCE_OFF),          \
94         S(PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED), \
95         S(PR_SWAP_SRC_SNK_SINK_ON),             \
96         S(PR_SWAP_SNK_SRC_SINK_OFF),            \
97         S(PR_SWAP_SNK_SRC_SOURCE_ON),           \
98         S(PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP),    \
99                                                 \
100         S(VCONN_SWAP_ACCEPT),                   \
101         S(VCONN_SWAP_SEND),                     \
102         S(VCONN_SWAP_SEND_TIMEOUT),             \
103         S(VCONN_SWAP_CANCEL),                   \
104         S(VCONN_SWAP_START),                    \
105         S(VCONN_SWAP_WAIT_FOR_VCONN),           \
106         S(VCONN_SWAP_TURN_ON_VCONN),            \
107         S(VCONN_SWAP_TURN_OFF_VCONN),           \
108                                                 \
109         S(FR_SWAP_SEND),                        \
110         S(FR_SWAP_SEND_TIMEOUT),                \
111         S(FR_SWAP_SNK_SRC_TRANSITION_TO_OFF),                   \
112         S(FR_SWAP_SNK_SRC_NEW_SINK_READY),              \
113         S(FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED), \
114         S(FR_SWAP_CANCEL),                      \
115                                                 \
116         S(SNK_TRY),                             \
117         S(SNK_TRY_WAIT),                        \
118         S(SNK_TRY_WAIT_DEBOUNCE),               \
119         S(SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS),    \
120         S(SRC_TRYWAIT),                         \
121         S(SRC_TRYWAIT_DEBOUNCE),                \
122         S(SRC_TRYWAIT_UNATTACHED),              \
123                                                 \
124         S(SRC_TRY),                             \
125         S(SRC_TRY_WAIT),                        \
126         S(SRC_TRY_DEBOUNCE),                    \
127         S(SNK_TRYWAIT),                         \
128         S(SNK_TRYWAIT_DEBOUNCE),                \
129         S(SNK_TRYWAIT_VBUS),                    \
130         S(BIST_RX),                             \
131                                                 \
132         S(GET_STATUS_SEND),                     \
133         S(GET_STATUS_SEND_TIMEOUT),             \
134         S(GET_PPS_STATUS_SEND),                 \
135         S(GET_PPS_STATUS_SEND_TIMEOUT),         \
136                                                 \
137         S(GET_SINK_CAP),                        \
138         S(GET_SINK_CAP_TIMEOUT),                \
139                                                 \
140         S(ERROR_RECOVERY),                      \
141         S(PORT_RESET),                          \
142         S(PORT_RESET_WAIT_OFF)
143
144 #define GENERATE_ENUM(e)        e
145 #define GENERATE_STRING(s)      #s
146
147 enum tcpm_state {
148         FOREACH_STATE(GENERATE_ENUM)
149 };
150
151 static const char * const tcpm_states[] = {
152         FOREACH_STATE(GENERATE_STRING)
153 };
154
155 enum vdm_states {
156         VDM_STATE_ERR_BUSY = -3,
157         VDM_STATE_ERR_SEND = -2,
158         VDM_STATE_ERR_TMOUT = -1,
159         VDM_STATE_DONE = 0,
160         /* Anything >0 represents an active state */
161         VDM_STATE_READY = 1,
162         VDM_STATE_BUSY = 2,
163         VDM_STATE_WAIT_RSP_BUSY = 3,
164 };
165
166 enum pd_msg_request {
167         PD_MSG_NONE = 0,
168         PD_MSG_CTRL_REJECT,
169         PD_MSG_CTRL_WAIT,
170         PD_MSG_CTRL_NOT_SUPP,
171         PD_MSG_DATA_SINK_CAP,
172         PD_MSG_DATA_SOURCE_CAP,
173 };
174
175 enum adev_actions {
176         ADEV_NONE = 0,
177         ADEV_NOTIFY_USB_AND_QUEUE_VDM,
178         ADEV_QUEUE_VDM,
179         ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL,
180         ADEV_ATTENTION,
181 };
182
183 /*
184  * Initial current capability of the new source when vSafe5V is applied during PD3.0 Fast Role Swap.
185  * Based on "Table 6-14 Fixed Supply PDO - Sink" of "USB Power Delivery Specification Revision 3.0,
186  * Version 1.2"
187  */
188 enum frs_typec_current {
189         FRS_NOT_SUPPORTED,
190         FRS_DEFAULT_POWER,
191         FRS_5V_1P5A,
192         FRS_5V_3A,
193 };
194
195 /* Events from low level driver */
196
197 #define TCPM_CC_EVENT           BIT(0)
198 #define TCPM_VBUS_EVENT         BIT(1)
199 #define TCPM_RESET_EVENT        BIT(2)
200 #define TCPM_FRS_EVENT          BIT(3)
201 #define TCPM_SOURCING_VBUS      BIT(4)
202
203 #define LOG_BUFFER_ENTRIES      1024
204 #define LOG_BUFFER_ENTRY_SIZE   128
205
206 /* Alternate mode support */
207
208 #define SVID_DISCOVERY_MAX      16
209 #define ALTMODE_DISCOVERY_MAX   (SVID_DISCOVERY_MAX * MODE_DISCOVERY_MAX)
210
211 #define GET_SINK_CAP_RETRY_MS   100
212
213 struct pd_mode_data {
214         int svid_index;         /* current SVID index           */
215         int nsvids;
216         u16 svids[SVID_DISCOVERY_MAX];
217         int altmodes;           /* number of alternate modes    */
218         struct typec_altmode_desc altmode_desc[ALTMODE_DISCOVERY_MAX];
219 };
220
221 /*
222  * @min_volt: Actual min voltage at the local port
223  * @req_min_volt: Requested min voltage to the port partner
224  * @max_volt: Actual max voltage at the local port
225  * @req_max_volt: Requested max voltage to the port partner
226  * @max_curr: Actual max current at the local port
227  * @req_max_curr: Requested max current of the port partner
228  * @req_out_volt: Requested output voltage to the port partner
229  * @req_op_curr: Requested operating current to the port partner
230  * @supported: Parter has atleast one APDO hence supports PPS
231  * @active: PPS mode is active
232  */
233 struct pd_pps_data {
234         u32 min_volt;
235         u32 req_min_volt;
236         u32 max_volt;
237         u32 req_max_volt;
238         u32 max_curr;
239         u32 req_max_curr;
240         u32 req_out_volt;
241         u32 req_op_curr;
242         bool supported;
243         bool active;
244 };
245
246 struct tcpm_port {
247         struct device *dev;
248
249         struct mutex lock;              /* tcpm state machine lock */
250         struct kthread_worker *wq;
251
252         struct typec_capability typec_caps;
253         struct typec_port *typec_port;
254
255         struct tcpc_dev *tcpc;
256         struct usb_role_switch *role_sw;
257
258         enum typec_role vconn_role;
259         enum typec_role pwr_role;
260         enum typec_data_role data_role;
261         enum typec_pwr_opmode pwr_opmode;
262
263         struct usb_pd_identity partner_ident;
264         struct typec_partner_desc partner_desc;
265         struct typec_partner *partner;
266
267         enum typec_cc_status cc_req;
268
269         enum typec_cc_status cc1;
270         enum typec_cc_status cc2;
271         enum typec_cc_polarity polarity;
272
273         bool attached;
274         bool connected;
275         enum typec_port_type port_type;
276         bool vbus_present;
277         bool vbus_never_low;
278         bool vbus_source;
279         bool vbus_charge;
280
281         bool send_discover;
282         bool op_vsafe5v;
283
284         int try_role;
285         int try_snk_count;
286         int try_src_count;
287
288         enum pd_msg_request queued_message;
289
290         enum tcpm_state enter_state;
291         enum tcpm_state prev_state;
292         enum tcpm_state state;
293         enum tcpm_state delayed_state;
294         ktime_t delayed_runtime;
295         unsigned long delay_ms;
296
297         spinlock_t pd_event_lock;
298         u32 pd_events;
299
300         struct kthread_work event_work;
301         struct hrtimer state_machine_timer;
302         struct kthread_work state_machine;
303         struct hrtimer vdm_state_machine_timer;
304         struct kthread_work vdm_state_machine;
305         struct hrtimer enable_frs_timer;
306         struct kthread_work enable_frs;
307         bool state_machine_running;
308
309         struct completion tx_complete;
310         enum tcpm_transmit_status tx_status;
311
312         struct mutex swap_lock;         /* swap command lock */
313         bool swap_pending;
314         bool non_pd_role_swap;
315         struct completion swap_complete;
316         int swap_status;
317
318         unsigned int negotiated_rev;
319         unsigned int message_id;
320         unsigned int caps_count;
321         unsigned int hard_reset_count;
322         bool pd_capable;
323         bool explicit_contract;
324         unsigned int rx_msgid;
325
326         /* Partner capabilities/requests */
327         u32 sink_request;
328         u32 source_caps[PDO_MAX_OBJECTS];
329         unsigned int nr_source_caps;
330         u32 sink_caps[PDO_MAX_OBJECTS];
331         unsigned int nr_sink_caps;
332
333         /* Local capabilities */
334         u32 src_pdo[PDO_MAX_OBJECTS];
335         unsigned int nr_src_pdo;
336         u32 snk_pdo[PDO_MAX_OBJECTS];
337         unsigned int nr_snk_pdo;
338         u32 snk_vdo[VDO_MAX_OBJECTS];
339         unsigned int nr_snk_vdo;
340
341         unsigned int operating_snk_mw;
342         bool update_sink_caps;
343
344         /* Requested current / voltage to the port partner */
345         u32 req_current_limit;
346         u32 req_supply_voltage;
347         /* Actual current / voltage limit of the local port */
348         u32 current_limit;
349         u32 supply_voltage;
350
351         /* Used to export TA voltage and current */
352         struct power_supply *psy;
353         struct power_supply_desc psy_desc;
354         enum power_supply_usb_type usb_type;
355
356         u32 bist_request;
357
358         /* PD state for Vendor Defined Messages */
359         enum vdm_states vdm_state;
360         u32 vdm_retries;
361         /* next Vendor Defined Message to send */
362         u32 vdo_data[VDO_MAX_SIZE];
363         u8 vdo_count;
364         /* VDO to retry if UFP responder replied busy */
365         u32 vdo_retry;
366
367         /* PPS */
368         struct pd_pps_data pps_data;
369         struct completion pps_complete;
370         bool pps_pending;
371         int pps_status;
372
373         /* Alternate mode data */
374         struct pd_mode_data mode_data;
375         struct typec_altmode *partner_altmode[ALTMODE_DISCOVERY_MAX];
376         struct typec_altmode *port_altmode[ALTMODE_DISCOVERY_MAX];
377
378         /* Deadline in jiffies to exit src_try_wait state */
379         unsigned long max_wait;
380
381         /* port belongs to a self powered device */
382         bool self_powered;
383
384         /* FRS */
385         enum frs_typec_current frs_current;
386
387         /* Sink caps have been queried */
388         bool sink_cap_done;
389
390 #ifdef CONFIG_DEBUG_FS
391         struct dentry *dentry;
392         struct mutex logbuffer_lock;    /* log buffer access lock */
393         int logbuffer_head;
394         int logbuffer_tail;
395         u8 *logbuffer[LOG_BUFFER_ENTRIES];
396 #endif
397 };
398
399 struct pd_rx_event {
400         struct kthread_work work;
401         struct tcpm_port *port;
402         struct pd_message msg;
403 };
404
405 #define tcpm_cc_is_sink(cc) \
406         ((cc) == TYPEC_CC_RP_DEF || (cc) == TYPEC_CC_RP_1_5 || \
407          (cc) == TYPEC_CC_RP_3_0)
408
409 #define tcpm_port_is_sink(port) \
410         ((tcpm_cc_is_sink((port)->cc1) && !tcpm_cc_is_sink((port)->cc2)) || \
411          (tcpm_cc_is_sink((port)->cc2) && !tcpm_cc_is_sink((port)->cc1)))
412
413 #define tcpm_cc_is_source(cc) ((cc) == TYPEC_CC_RD)
414 #define tcpm_cc_is_audio(cc) ((cc) == TYPEC_CC_RA)
415 #define tcpm_cc_is_open(cc) ((cc) == TYPEC_CC_OPEN)
416
417 #define tcpm_port_is_source(port) \
418         ((tcpm_cc_is_source((port)->cc1) && \
419          !tcpm_cc_is_source((port)->cc2)) || \
420          (tcpm_cc_is_source((port)->cc2) && \
421           !tcpm_cc_is_source((port)->cc1)))
422
423 #define tcpm_port_is_debug(port) \
424         (tcpm_cc_is_source((port)->cc1) && tcpm_cc_is_source((port)->cc2))
425
426 #define tcpm_port_is_audio(port) \
427         (tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_audio((port)->cc2))
428
429 #define tcpm_port_is_audio_detached(port) \
430         ((tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_open((port)->cc2)) || \
431          (tcpm_cc_is_audio((port)->cc2) && tcpm_cc_is_open((port)->cc1)))
432
433 #define tcpm_try_snk(port) \
434         ((port)->try_snk_count == 0 && (port)->try_role == TYPEC_SINK && \
435         (port)->port_type == TYPEC_PORT_DRP)
436
437 #define tcpm_try_src(port) \
438         ((port)->try_src_count == 0 && (port)->try_role == TYPEC_SOURCE && \
439         (port)->port_type == TYPEC_PORT_DRP)
440
441 #define tcpm_data_role_for_source(port) \
442         ((port)->typec_caps.data == TYPEC_PORT_UFP ? \
443         TYPEC_DEVICE : TYPEC_HOST)
444
445 #define tcpm_data_role_for_sink(port) \
446         ((port)->typec_caps.data == TYPEC_PORT_DFP ? \
447         TYPEC_HOST : TYPEC_DEVICE)
448
449 static enum tcpm_state tcpm_default_state(struct tcpm_port *port)
450 {
451         if (port->port_type == TYPEC_PORT_DRP) {
452                 if (port->try_role == TYPEC_SINK)
453                         return SNK_UNATTACHED;
454                 else if (port->try_role == TYPEC_SOURCE)
455                         return SRC_UNATTACHED;
456                 /* Fall through to return SRC_UNATTACHED */
457         } else if (port->port_type == TYPEC_PORT_SNK) {
458                 return SNK_UNATTACHED;
459         }
460         return SRC_UNATTACHED;
461 }
462
463 static bool tcpm_port_is_disconnected(struct tcpm_port *port)
464 {
465         return (!port->attached && port->cc1 == TYPEC_CC_OPEN &&
466                 port->cc2 == TYPEC_CC_OPEN) ||
467                (port->attached && ((port->polarity == TYPEC_POLARITY_CC1 &&
468                                     port->cc1 == TYPEC_CC_OPEN) ||
469                                    (port->polarity == TYPEC_POLARITY_CC2 &&
470                                     port->cc2 == TYPEC_CC_OPEN)));
471 }
472
473 /*
474  * Logging
475  */
476
477 #ifdef CONFIG_DEBUG_FS
478
479 static bool tcpm_log_full(struct tcpm_port *port)
480 {
481         return port->logbuffer_tail ==
482                 (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
483 }
484
485 __printf(2, 0)
486 static void _tcpm_log(struct tcpm_port *port, const char *fmt, va_list args)
487 {
488         char tmpbuffer[LOG_BUFFER_ENTRY_SIZE];
489         u64 ts_nsec = local_clock();
490         unsigned long rem_nsec;
491
492         mutex_lock(&port->logbuffer_lock);
493         if (!port->logbuffer[port->logbuffer_head]) {
494                 port->logbuffer[port->logbuffer_head] =
495                                 kzalloc(LOG_BUFFER_ENTRY_SIZE, GFP_KERNEL);
496                 if (!port->logbuffer[port->logbuffer_head]) {
497                         mutex_unlock(&port->logbuffer_lock);
498                         return;
499                 }
500         }
501
502         vsnprintf(tmpbuffer, sizeof(tmpbuffer), fmt, args);
503
504         if (tcpm_log_full(port)) {
505                 port->logbuffer_head = max(port->logbuffer_head - 1, 0);
506                 strcpy(tmpbuffer, "overflow");
507         }
508
509         if (port->logbuffer_head < 0 ||
510             port->logbuffer_head >= LOG_BUFFER_ENTRIES) {
511                 dev_warn(port->dev,
512                          "Bad log buffer index %d\n", port->logbuffer_head);
513                 goto abort;
514         }
515
516         if (!port->logbuffer[port->logbuffer_head]) {
517                 dev_warn(port->dev,
518                          "Log buffer index %d is NULL\n", port->logbuffer_head);
519                 goto abort;
520         }
521
522         rem_nsec = do_div(ts_nsec, 1000000000);
523         scnprintf(port->logbuffer[port->logbuffer_head],
524                   LOG_BUFFER_ENTRY_SIZE, "[%5lu.%06lu] %s",
525                   (unsigned long)ts_nsec, rem_nsec / 1000,
526                   tmpbuffer);
527         port->logbuffer_head = (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
528
529 abort:
530         mutex_unlock(&port->logbuffer_lock);
531 }
532
533 __printf(2, 3)
534 static void tcpm_log(struct tcpm_port *port, const char *fmt, ...)
535 {
536         va_list args;
537
538         /* Do not log while disconnected and unattached */
539         if (tcpm_port_is_disconnected(port) &&
540             (port->state == SRC_UNATTACHED || port->state == SNK_UNATTACHED ||
541              port->state == TOGGLING))
542                 return;
543
544         va_start(args, fmt);
545         _tcpm_log(port, fmt, args);
546         va_end(args);
547 }
548
549 __printf(2, 3)
550 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...)
551 {
552         va_list args;
553
554         va_start(args, fmt);
555         _tcpm_log(port, fmt, args);
556         va_end(args);
557 }
558
559 static void tcpm_log_source_caps(struct tcpm_port *port)
560 {
561         int i;
562
563         for (i = 0; i < port->nr_source_caps; i++) {
564                 u32 pdo = port->source_caps[i];
565                 enum pd_pdo_type type = pdo_type(pdo);
566                 char msg[64];
567
568                 switch (type) {
569                 case PDO_TYPE_FIXED:
570                         scnprintf(msg, sizeof(msg),
571                                   "%u mV, %u mA [%s%s%s%s%s%s]",
572                                   pdo_fixed_voltage(pdo),
573                                   pdo_max_current(pdo),
574                                   (pdo & PDO_FIXED_DUAL_ROLE) ?
575                                                         "R" : "",
576                                   (pdo & PDO_FIXED_SUSPEND) ?
577                                                         "S" : "",
578                                   (pdo & PDO_FIXED_HIGHER_CAP) ?
579                                                         "H" : "",
580                                   (pdo & PDO_FIXED_USB_COMM) ?
581                                                         "U" : "",
582                                   (pdo & PDO_FIXED_DATA_SWAP) ?
583                                                         "D" : "",
584                                   (pdo & PDO_FIXED_EXTPOWER) ?
585                                                         "E" : "");
586                         break;
587                 case PDO_TYPE_VAR:
588                         scnprintf(msg, sizeof(msg),
589                                   "%u-%u mV, %u mA",
590                                   pdo_min_voltage(pdo),
591                                   pdo_max_voltage(pdo),
592                                   pdo_max_current(pdo));
593                         break;
594                 case PDO_TYPE_BATT:
595                         scnprintf(msg, sizeof(msg),
596                                   "%u-%u mV, %u mW",
597                                   pdo_min_voltage(pdo),
598                                   pdo_max_voltage(pdo),
599                                   pdo_max_power(pdo));
600                         break;
601                 case PDO_TYPE_APDO:
602                         if (pdo_apdo_type(pdo) == APDO_TYPE_PPS)
603                                 scnprintf(msg, sizeof(msg),
604                                           "%u-%u mV, %u mA",
605                                           pdo_pps_apdo_min_voltage(pdo),
606                                           pdo_pps_apdo_max_voltage(pdo),
607                                           pdo_pps_apdo_max_current(pdo));
608                         else
609                                 strcpy(msg, "undefined APDO");
610                         break;
611                 default:
612                         strcpy(msg, "undefined");
613                         break;
614                 }
615                 tcpm_log(port, " PDO %d: type %d, %s",
616                          i, type, msg);
617         }
618 }
619
620 static int tcpm_debug_show(struct seq_file *s, void *v)
621 {
622         struct tcpm_port *port = (struct tcpm_port *)s->private;
623         int tail;
624
625         mutex_lock(&port->logbuffer_lock);
626         tail = port->logbuffer_tail;
627         while (tail != port->logbuffer_head) {
628                 seq_printf(s, "%s\n", port->logbuffer[tail]);
629                 tail = (tail + 1) % LOG_BUFFER_ENTRIES;
630         }
631         if (!seq_has_overflowed(s))
632                 port->logbuffer_tail = tail;
633         mutex_unlock(&port->logbuffer_lock);
634
635         return 0;
636 }
637 DEFINE_SHOW_ATTRIBUTE(tcpm_debug);
638
639 static void tcpm_debugfs_init(struct tcpm_port *port)
640 {
641         char name[NAME_MAX];
642
643         mutex_init(&port->logbuffer_lock);
644         snprintf(name, NAME_MAX, "tcpm-%s", dev_name(port->dev));
645         port->dentry = debugfs_create_file(name, S_IFREG | 0444, usb_debug_root,
646                                            port, &tcpm_debug_fops);
647 }
648
649 static void tcpm_debugfs_exit(struct tcpm_port *port)
650 {
651         int i;
652
653         mutex_lock(&port->logbuffer_lock);
654         for (i = 0; i < LOG_BUFFER_ENTRIES; i++) {
655                 kfree(port->logbuffer[i]);
656                 port->logbuffer[i] = NULL;
657         }
658         mutex_unlock(&port->logbuffer_lock);
659
660         debugfs_remove(port->dentry);
661 }
662
663 #else
664
665 __printf(2, 3)
666 static void tcpm_log(const struct tcpm_port *port, const char *fmt, ...) { }
667 __printf(2, 3)
668 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...) { }
669 static void tcpm_log_source_caps(struct tcpm_port *port) { }
670 static void tcpm_debugfs_init(const struct tcpm_port *port) { }
671 static void tcpm_debugfs_exit(const struct tcpm_port *port) { }
672
673 #endif
674
675 static int tcpm_pd_transmit(struct tcpm_port *port,
676                             enum tcpm_transmit_type type,
677                             const struct pd_message *msg)
678 {
679         unsigned long timeout;
680         int ret;
681
682         if (msg)
683                 tcpm_log(port, "PD TX, header: %#x", le16_to_cpu(msg->header));
684         else
685                 tcpm_log(port, "PD TX, type: %#x", type);
686
687         reinit_completion(&port->tx_complete);
688         ret = port->tcpc->pd_transmit(port->tcpc, type, msg);
689         if (ret < 0)
690                 return ret;
691
692         mutex_unlock(&port->lock);
693         timeout = wait_for_completion_timeout(&port->tx_complete,
694                                 msecs_to_jiffies(PD_T_TCPC_TX_TIMEOUT));
695         mutex_lock(&port->lock);
696         if (!timeout)
697                 return -ETIMEDOUT;
698
699         switch (port->tx_status) {
700         case TCPC_TX_SUCCESS:
701                 port->message_id = (port->message_id + 1) & PD_HEADER_ID_MASK;
702                 return 0;
703         case TCPC_TX_DISCARDED:
704                 return -EAGAIN;
705         case TCPC_TX_FAILED:
706         default:
707                 return -EIO;
708         }
709 }
710
711 void tcpm_pd_transmit_complete(struct tcpm_port *port,
712                                enum tcpm_transmit_status status)
713 {
714         tcpm_log(port, "PD TX complete, status: %u", status);
715         port->tx_status = status;
716         complete(&port->tx_complete);
717 }
718 EXPORT_SYMBOL_GPL(tcpm_pd_transmit_complete);
719
720 static int tcpm_mux_set(struct tcpm_port *port, int state,
721                         enum usb_role usb_role,
722                         enum typec_orientation orientation)
723 {
724         int ret;
725
726         tcpm_log(port, "Requesting mux state %d, usb-role %d, orientation %d",
727                  state, usb_role, orientation);
728
729         ret = typec_set_orientation(port->typec_port, orientation);
730         if (ret)
731                 return ret;
732
733         if (port->role_sw) {
734                 ret = usb_role_switch_set_role(port->role_sw, usb_role);
735                 if (ret)
736                         return ret;
737         }
738
739         return typec_set_mode(port->typec_port, state);
740 }
741
742 static int tcpm_set_polarity(struct tcpm_port *port,
743                              enum typec_cc_polarity polarity)
744 {
745         int ret;
746
747         tcpm_log(port, "polarity %d", polarity);
748
749         ret = port->tcpc->set_polarity(port->tcpc, polarity);
750         if (ret < 0)
751                 return ret;
752
753         port->polarity = polarity;
754
755         return 0;
756 }
757
758 static int tcpm_set_vconn(struct tcpm_port *port, bool enable)
759 {
760         int ret;
761
762         tcpm_log(port, "vconn:=%d", enable);
763
764         ret = port->tcpc->set_vconn(port->tcpc, enable);
765         if (!ret) {
766                 port->vconn_role = enable ? TYPEC_SOURCE : TYPEC_SINK;
767                 typec_set_vconn_role(port->typec_port, port->vconn_role);
768         }
769
770         return ret;
771 }
772
773 static u32 tcpm_get_current_limit(struct tcpm_port *port)
774 {
775         enum typec_cc_status cc;
776         u32 limit;
777
778         cc = port->polarity ? port->cc2 : port->cc1;
779         switch (cc) {
780         case TYPEC_CC_RP_1_5:
781                 limit = 1500;
782                 break;
783         case TYPEC_CC_RP_3_0:
784                 limit = 3000;
785                 break;
786         case TYPEC_CC_RP_DEF:
787         default:
788                 if (port->tcpc->get_current_limit)
789                         limit = port->tcpc->get_current_limit(port->tcpc);
790                 else
791                         limit = 0;
792                 break;
793         }
794
795         return limit;
796 }
797
798 static int tcpm_set_current_limit(struct tcpm_port *port, u32 max_ma, u32 mv)
799 {
800         int ret = -EOPNOTSUPP;
801
802         tcpm_log(port, "Setting voltage/current limit %u mV %u mA", mv, max_ma);
803
804         port->supply_voltage = mv;
805         port->current_limit = max_ma;
806         power_supply_changed(port->psy);
807
808         if (port->tcpc->set_current_limit)
809                 ret = port->tcpc->set_current_limit(port->tcpc, max_ma, mv);
810
811         return ret;
812 }
813
814 /*
815  * Determine RP value to set based on maximum current supported
816  * by a port if configured as source.
817  * Returns CC value to report to link partner.
818  */
819 static enum typec_cc_status tcpm_rp_cc(struct tcpm_port *port)
820 {
821         const u32 *src_pdo = port->src_pdo;
822         int nr_pdo = port->nr_src_pdo;
823         int i;
824
825         /*
826          * Search for first entry with matching voltage.
827          * It should report the maximum supported current.
828          */
829         for (i = 0; i < nr_pdo; i++) {
830                 const u32 pdo = src_pdo[i];
831
832                 if (pdo_type(pdo) == PDO_TYPE_FIXED &&
833                     pdo_fixed_voltage(pdo) == 5000) {
834                         unsigned int curr = pdo_max_current(pdo);
835
836                         if (curr >= 3000)
837                                 return TYPEC_CC_RP_3_0;
838                         else if (curr >= 1500)
839                                 return TYPEC_CC_RP_1_5;
840                         return TYPEC_CC_RP_DEF;
841                 }
842         }
843
844         return TYPEC_CC_RP_DEF;
845 }
846
847 static int tcpm_set_attached_state(struct tcpm_port *port, bool attached)
848 {
849         return port->tcpc->set_roles(port->tcpc, attached, port->pwr_role,
850                                      port->data_role);
851 }
852
853 static int tcpm_set_roles(struct tcpm_port *port, bool attached,
854                           enum typec_role role, enum typec_data_role data)
855 {
856         enum typec_orientation orientation;
857         enum usb_role usb_role;
858         int ret;
859
860         if (port->polarity == TYPEC_POLARITY_CC1)
861                 orientation = TYPEC_ORIENTATION_NORMAL;
862         else
863                 orientation = TYPEC_ORIENTATION_REVERSE;
864
865         if (port->typec_caps.data == TYPEC_PORT_DRD) {
866                 if (data == TYPEC_HOST)
867                         usb_role = USB_ROLE_HOST;
868                 else
869                         usb_role = USB_ROLE_DEVICE;
870         } else if (port->typec_caps.data == TYPEC_PORT_DFP) {
871                 if (data == TYPEC_HOST) {
872                         if (role == TYPEC_SOURCE)
873                                 usb_role = USB_ROLE_HOST;
874                         else
875                                 usb_role = USB_ROLE_NONE;
876                 } else {
877                         return -ENOTSUPP;
878                 }
879         } else {
880                 if (data == TYPEC_DEVICE) {
881                         if (role == TYPEC_SINK)
882                                 usb_role = USB_ROLE_DEVICE;
883                         else
884                                 usb_role = USB_ROLE_NONE;
885                 } else {
886                         return -ENOTSUPP;
887                 }
888         }
889
890         ret = tcpm_mux_set(port, TYPEC_STATE_USB, usb_role, orientation);
891         if (ret < 0)
892                 return ret;
893
894         ret = port->tcpc->set_roles(port->tcpc, attached, role, data);
895         if (ret < 0)
896                 return ret;
897
898         port->pwr_role = role;
899         port->data_role = data;
900         typec_set_data_role(port->typec_port, data);
901         typec_set_pwr_role(port->typec_port, role);
902
903         return 0;
904 }
905
906 static int tcpm_set_pwr_role(struct tcpm_port *port, enum typec_role role)
907 {
908         int ret;
909
910         ret = port->tcpc->set_roles(port->tcpc, true, role,
911                                     port->data_role);
912         if (ret < 0)
913                 return ret;
914
915         port->pwr_role = role;
916         typec_set_pwr_role(port->typec_port, role);
917
918         return 0;
919 }
920
921 static int tcpm_pd_send_source_caps(struct tcpm_port *port)
922 {
923         struct pd_message msg;
924         int i;
925
926         memset(&msg, 0, sizeof(msg));
927         if (!port->nr_src_pdo) {
928                 /* No source capabilities defined, sink only */
929                 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
930                                           port->pwr_role,
931                                           port->data_role,
932                                           port->negotiated_rev,
933                                           port->message_id, 0);
934         } else {
935                 msg.header = PD_HEADER_LE(PD_DATA_SOURCE_CAP,
936                                           port->pwr_role,
937                                           port->data_role,
938                                           port->negotiated_rev,
939                                           port->message_id,
940                                           port->nr_src_pdo);
941         }
942         for (i = 0; i < port->nr_src_pdo; i++)
943                 msg.payload[i] = cpu_to_le32(port->src_pdo[i]);
944
945         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
946 }
947
948 static int tcpm_pd_send_sink_caps(struct tcpm_port *port)
949 {
950         struct pd_message msg;
951         int i;
952
953         memset(&msg, 0, sizeof(msg));
954         if (!port->nr_snk_pdo) {
955                 /* No sink capabilities defined, source only */
956                 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
957                                           port->pwr_role,
958                                           port->data_role,
959                                           port->negotiated_rev,
960                                           port->message_id, 0);
961         } else {
962                 msg.header = PD_HEADER_LE(PD_DATA_SINK_CAP,
963                                           port->pwr_role,
964                                           port->data_role,
965                                           port->negotiated_rev,
966                                           port->message_id,
967                                           port->nr_snk_pdo);
968         }
969         for (i = 0; i < port->nr_snk_pdo; i++)
970                 msg.payload[i] = cpu_to_le32(port->snk_pdo[i]);
971
972         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
973 }
974
975 static void mod_tcpm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
976 {
977         if (delay_ms) {
978                 hrtimer_start(&port->state_machine_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
979         } else {
980                 hrtimer_cancel(&port->state_machine_timer);
981                 kthread_queue_work(port->wq, &port->state_machine);
982         }
983 }
984
985 static void mod_vdm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
986 {
987         if (delay_ms) {
988                 hrtimer_start(&port->vdm_state_machine_timer, ms_to_ktime(delay_ms),
989                               HRTIMER_MODE_REL);
990         } else {
991                 hrtimer_cancel(&port->vdm_state_machine_timer);
992                 kthread_queue_work(port->wq, &port->vdm_state_machine);
993         }
994 }
995
996 static void mod_enable_frs_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
997 {
998         if (delay_ms) {
999                 hrtimer_start(&port->enable_frs_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1000         } else {
1001                 hrtimer_cancel(&port->enable_frs_timer);
1002                 kthread_queue_work(port->wq, &port->enable_frs);
1003         }
1004 }
1005
1006 static void tcpm_set_state(struct tcpm_port *port, enum tcpm_state state,
1007                            unsigned int delay_ms)
1008 {
1009         if (delay_ms) {
1010                 tcpm_log(port, "pending state change %s -> %s @ %u ms",
1011                          tcpm_states[port->state], tcpm_states[state],
1012                          delay_ms);
1013                 port->delayed_state = state;
1014                 mod_tcpm_delayed_work(port, delay_ms);
1015                 port->delayed_runtime = ktime_add(ktime_get(), ms_to_ktime(delay_ms));
1016                 port->delay_ms = delay_ms;
1017         } else {
1018                 tcpm_log(port, "state change %s -> %s",
1019                          tcpm_states[port->state], tcpm_states[state]);
1020                 port->delayed_state = INVALID_STATE;
1021                 port->prev_state = port->state;
1022                 port->state = state;
1023                 /*
1024                  * Don't re-queue the state machine work item if we're currently
1025                  * in the state machine and we're immediately changing states.
1026                  * tcpm_state_machine_work() will continue running the state
1027                  * machine.
1028                  */
1029                 if (!port->state_machine_running)
1030                         mod_tcpm_delayed_work(port, 0);
1031         }
1032 }
1033
1034 static void tcpm_set_state_cond(struct tcpm_port *port, enum tcpm_state state,
1035                                 unsigned int delay_ms)
1036 {
1037         if (port->enter_state == port->state)
1038                 tcpm_set_state(port, state, delay_ms);
1039         else
1040                 tcpm_log(port,
1041                          "skipped %sstate change %s -> %s [%u ms], context state %s",
1042                          delay_ms ? "delayed " : "",
1043                          tcpm_states[port->state], tcpm_states[state],
1044                          delay_ms, tcpm_states[port->enter_state]);
1045 }
1046
1047 static void tcpm_queue_message(struct tcpm_port *port,
1048                                enum pd_msg_request message)
1049 {
1050         port->queued_message = message;
1051         mod_tcpm_delayed_work(port, 0);
1052 }
1053
1054 /*
1055  * VDM/VDO handling functions
1056  */
1057 static void tcpm_queue_vdm(struct tcpm_port *port, const u32 header,
1058                            const u32 *data, int cnt)
1059 {
1060         WARN_ON(!mutex_is_locked(&port->lock));
1061
1062         /* Make sure we are not still processing a previous VDM packet */
1063         WARN_ON(port->vdm_state > VDM_STATE_DONE);
1064
1065         port->vdo_count = cnt + 1;
1066         port->vdo_data[0] = header;
1067         memcpy(&port->vdo_data[1], data, sizeof(u32) * cnt);
1068         /* Set ready, vdm state machine will actually send */
1069         port->vdm_retries = 0;
1070         port->vdm_state = VDM_STATE_READY;
1071
1072         mod_vdm_delayed_work(port, 0);
1073 }
1074
1075 static void tcpm_queue_vdm_unlocked(struct tcpm_port *port, const u32 header,
1076                                     const u32 *data, int cnt)
1077 {
1078         mutex_lock(&port->lock);
1079         tcpm_queue_vdm(port, header, data, cnt);
1080         mutex_unlock(&port->lock);
1081 }
1082
1083 static void svdm_consume_identity(struct tcpm_port *port, const u32 *p, int cnt)
1084 {
1085         u32 vdo = p[VDO_INDEX_IDH];
1086         u32 product = p[VDO_INDEX_PRODUCT];
1087
1088         memset(&port->mode_data, 0, sizeof(port->mode_data));
1089
1090         port->partner_ident.id_header = vdo;
1091         port->partner_ident.cert_stat = p[VDO_INDEX_CSTAT];
1092         port->partner_ident.product = product;
1093
1094         typec_partner_set_identity(port->partner);
1095
1096         tcpm_log(port, "Identity: %04x:%04x.%04x",
1097                  PD_IDH_VID(vdo),
1098                  PD_PRODUCT_PID(product), product & 0xffff);
1099 }
1100
1101 static bool svdm_consume_svids(struct tcpm_port *port, const u32 *p, int cnt)
1102 {
1103         struct pd_mode_data *pmdata = &port->mode_data;
1104         int i;
1105
1106         for (i = 1; i < cnt; i++) {
1107                 u16 svid;
1108
1109                 svid = (p[i] >> 16) & 0xffff;
1110                 if (!svid)
1111                         return false;
1112
1113                 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1114                         goto abort;
1115
1116                 pmdata->svids[pmdata->nsvids++] = svid;
1117                 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1118
1119                 svid = p[i] & 0xffff;
1120                 if (!svid)
1121                         return false;
1122
1123                 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1124                         goto abort;
1125
1126                 pmdata->svids[pmdata->nsvids++] = svid;
1127                 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1128         }
1129         return true;
1130 abort:
1131         tcpm_log(port, "SVID_DISCOVERY_MAX(%d) too low!", SVID_DISCOVERY_MAX);
1132         return false;
1133 }
1134
1135 static void svdm_consume_modes(struct tcpm_port *port, const u32 *p, int cnt)
1136 {
1137         struct pd_mode_data *pmdata = &port->mode_data;
1138         struct typec_altmode_desc *paltmode;
1139         int i;
1140
1141         if (pmdata->altmodes >= ARRAY_SIZE(port->partner_altmode)) {
1142                 /* Already logged in svdm_consume_svids() */
1143                 return;
1144         }
1145
1146         for (i = 1; i < cnt; i++) {
1147                 paltmode = &pmdata->altmode_desc[pmdata->altmodes];
1148                 memset(paltmode, 0, sizeof(*paltmode));
1149
1150                 paltmode->svid = pmdata->svids[pmdata->svid_index];
1151                 paltmode->mode = i;
1152                 paltmode->vdo = p[i];
1153
1154                 tcpm_log(port, " Alternate mode %d: SVID 0x%04x, VDO %d: 0x%08x",
1155                          pmdata->altmodes, paltmode->svid,
1156                          paltmode->mode, paltmode->vdo);
1157
1158                 pmdata->altmodes++;
1159         }
1160 }
1161
1162 static void tcpm_register_partner_altmodes(struct tcpm_port *port)
1163 {
1164         struct pd_mode_data *modep = &port->mode_data;
1165         struct typec_altmode *altmode;
1166         int i;
1167
1168         for (i = 0; i < modep->altmodes; i++) {
1169                 altmode = typec_partner_register_altmode(port->partner,
1170                                                 &modep->altmode_desc[i]);
1171                 if (IS_ERR(altmode)) {
1172                         tcpm_log(port, "Failed to register partner SVID 0x%04x",
1173                                  modep->altmode_desc[i].svid);
1174                         altmode = NULL;
1175                 }
1176                 port->partner_altmode[i] = altmode;
1177         }
1178 }
1179
1180 #define supports_modal(port)    PD_IDH_MODAL_SUPP((port)->partner_ident.id_header)
1181
1182 static int tcpm_pd_svdm(struct tcpm_port *port, struct typec_altmode *adev,
1183                         const u32 *p, int cnt, u32 *response,
1184                         enum adev_actions *adev_action)
1185 {
1186         struct typec_altmode *pdev;
1187         struct pd_mode_data *modep;
1188         int rlen = 0;
1189         int cmd_type;
1190         int cmd;
1191         int i;
1192
1193         cmd_type = PD_VDO_CMDT(p[0]);
1194         cmd = PD_VDO_CMD(p[0]);
1195
1196         tcpm_log(port, "Rx VDM cmd 0x%x type %d cmd %d len %d",
1197                  p[0], cmd_type, cmd, cnt);
1198
1199         modep = &port->mode_data;
1200
1201         pdev = typec_match_altmode(port->partner_altmode, ALTMODE_DISCOVERY_MAX,
1202                                    PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1203
1204         switch (cmd_type) {
1205         case CMDT_INIT:
1206                 switch (cmd) {
1207                 case CMD_DISCOVER_IDENT:
1208                         /* 6.4.4.3.1: Only respond as UFP (device) */
1209                         if (port->data_role == TYPEC_DEVICE &&
1210                             port->nr_snk_vdo) {
1211                                 for (i = 0; i <  port->nr_snk_vdo; i++)
1212                                         response[i + 1] = port->snk_vdo[i];
1213                                 rlen = port->nr_snk_vdo + 1;
1214                         }
1215                         break;
1216                 case CMD_DISCOVER_SVID:
1217                         break;
1218                 case CMD_DISCOVER_MODES:
1219                         break;
1220                 case CMD_ENTER_MODE:
1221                         break;
1222                 case CMD_EXIT_MODE:
1223                         break;
1224                 case CMD_ATTENTION:
1225                         /* Attention command does not have response */
1226                         *adev_action = ADEV_ATTENTION;
1227                         return 0;
1228                 default:
1229                         break;
1230                 }
1231                 if (rlen >= 1) {
1232                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_ACK);
1233                 } else if (rlen == 0) {
1234                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1235                         rlen = 1;
1236                 } else {
1237                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_BUSY);
1238                         rlen = 1;
1239                 }
1240                 break;
1241         case CMDT_RSP_ACK:
1242                 /* silently drop message if we are not connected */
1243                 if (IS_ERR_OR_NULL(port->partner))
1244                         break;
1245
1246                 switch (cmd) {
1247                 case CMD_DISCOVER_IDENT:
1248                         /* 6.4.4.3.1 */
1249                         svdm_consume_identity(port, p, cnt);
1250                         response[0] = VDO(USB_SID_PD, 1, CMD_DISCOVER_SVID);
1251                         rlen = 1;
1252                         break;
1253                 case CMD_DISCOVER_SVID:
1254                         /* 6.4.4.3.2 */
1255                         if (svdm_consume_svids(port, p, cnt)) {
1256                                 response[0] = VDO(USB_SID_PD, 1,
1257                                                   CMD_DISCOVER_SVID);
1258                                 rlen = 1;
1259                         } else if (modep->nsvids && supports_modal(port)) {
1260                                 response[0] = VDO(modep->svids[0], 1,
1261                                                   CMD_DISCOVER_MODES);
1262                                 rlen = 1;
1263                         }
1264                         break;
1265                 case CMD_DISCOVER_MODES:
1266                         /* 6.4.4.3.3 */
1267                         svdm_consume_modes(port, p, cnt);
1268                         modep->svid_index++;
1269                         if (modep->svid_index < modep->nsvids) {
1270                                 u16 svid = modep->svids[modep->svid_index];
1271                                 response[0] = VDO(svid, 1, CMD_DISCOVER_MODES);
1272                                 rlen = 1;
1273                         } else {
1274                                 tcpm_register_partner_altmodes(port);
1275                         }
1276                         break;
1277                 case CMD_ENTER_MODE:
1278                         if (adev && pdev) {
1279                                 typec_altmode_update_active(pdev, true);
1280                                 *adev_action = ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL;
1281                         }
1282                         return 0;
1283                 case CMD_EXIT_MODE:
1284                         if (adev && pdev) {
1285                                 typec_altmode_update_active(pdev, false);
1286                                 /* Back to USB Operation */
1287                                 *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
1288                                 return 0;
1289                         }
1290                         break;
1291                 default:
1292                         break;
1293                 }
1294                 break;
1295         case CMDT_RSP_NAK:
1296                 switch (cmd) {
1297                 case CMD_ENTER_MODE:
1298                         /* Back to USB Operation */
1299                         *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
1300                         return 0;
1301                 default:
1302                         break;
1303                 }
1304                 break;
1305         default:
1306                 break;
1307         }
1308
1309         /* Informing the alternate mode drivers about everything */
1310         *adev_action = ADEV_QUEUE_VDM;
1311         return rlen;
1312 }
1313
1314 static void tcpm_handle_vdm_request(struct tcpm_port *port,
1315                                     const __le32 *payload, int cnt)
1316 {
1317         enum adev_actions adev_action = ADEV_NONE;
1318         struct typec_altmode *adev;
1319         u32 p[PD_MAX_PAYLOAD];
1320         u32 response[8] = { };
1321         int i, rlen = 0;
1322
1323         for (i = 0; i < cnt; i++)
1324                 p[i] = le32_to_cpu(payload[i]);
1325
1326         adev = typec_match_altmode(port->port_altmode, ALTMODE_DISCOVERY_MAX,
1327                                    PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1328
1329         if (port->vdm_state == VDM_STATE_BUSY) {
1330                 /* If UFP responded busy retry after timeout */
1331                 if (PD_VDO_CMDT(p[0]) == CMDT_RSP_BUSY) {
1332                         port->vdm_state = VDM_STATE_WAIT_RSP_BUSY;
1333                         port->vdo_retry = (p[0] & ~VDO_CMDT_MASK) |
1334                                 CMDT_INIT;
1335                         mod_vdm_delayed_work(port, PD_T_VDM_BUSY);
1336                         return;
1337                 }
1338                 port->vdm_state = VDM_STATE_DONE;
1339         }
1340
1341         if (PD_VDO_SVDM(p[0]))
1342                 rlen = tcpm_pd_svdm(port, adev, p, cnt, response, &adev_action);
1343
1344         /*
1345          * We are done with any state stored in the port struct now, except
1346          * for any port struct changes done by the tcpm_queue_vdm() call
1347          * below, which is a separate operation.
1348          *
1349          * So we can safely release the lock here; and we MUST release the
1350          * lock here to avoid an AB BA lock inversion:
1351          *
1352          * If we keep the lock here then the lock ordering in this path is:
1353          * 1. tcpm_pd_rx_handler take the tcpm port lock
1354          * 2. One of the typec_altmode_* calls below takes the alt-mode's lock
1355          *
1356          * And we also have this ordering:
1357          * 1. alt-mode driver takes the alt-mode's lock
1358          * 2. alt-mode driver calls tcpm_altmode_enter which takes the
1359          *    tcpm port lock
1360          *
1361          * Dropping our lock here avoids this.
1362          */
1363         mutex_unlock(&port->lock);
1364
1365         if (adev) {
1366                 switch (adev_action) {
1367                 case ADEV_NONE:
1368                         break;
1369                 case ADEV_NOTIFY_USB_AND_QUEUE_VDM:
1370                         WARN_ON(typec_altmode_notify(adev, TYPEC_STATE_USB, NULL));
1371                         typec_altmode_vdm(adev, p[0], &p[1], cnt);
1372                         break;
1373                 case ADEV_QUEUE_VDM:
1374                         typec_altmode_vdm(adev, p[0], &p[1], cnt);
1375                         break;
1376                 case ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL:
1377                         if (typec_altmode_vdm(adev, p[0], &p[1], cnt)) {
1378                                 response[0] = VDO(adev->svid, 1, CMD_EXIT_MODE);
1379                                 response[0] |= VDO_OPOS(adev->mode);
1380                                 rlen = 1;
1381                         }
1382                         break;
1383                 case ADEV_ATTENTION:
1384                         typec_altmode_attention(adev, p[1]);
1385                         break;
1386                 }
1387         }
1388
1389         /*
1390          * We must re-take the lock here to balance the unlock in
1391          * tcpm_pd_rx_handler, note that no changes, other then the
1392          * tcpm_queue_vdm call, are made while the lock is held again.
1393          * All that is done after the call is unwinding the call stack until
1394          * we return to tcpm_pd_rx_handler and do the unlock there.
1395          */
1396         mutex_lock(&port->lock);
1397
1398         if (rlen > 0)
1399                 tcpm_queue_vdm(port, response[0], &response[1], rlen - 1);
1400 }
1401
1402 static void tcpm_send_vdm(struct tcpm_port *port, u32 vid, int cmd,
1403                           const u32 *data, int count)
1404 {
1405         u32 header;
1406
1407         if (WARN_ON(count > VDO_MAX_SIZE - 1))
1408                 count = VDO_MAX_SIZE - 1;
1409
1410         /* set VDM header with VID & CMD */
1411         header = VDO(vid, ((vid & USB_SID_PD) == USB_SID_PD) ?
1412                         1 : (PD_VDO_CMD(cmd) <= CMD_ATTENTION), cmd);
1413         tcpm_queue_vdm(port, header, data, count);
1414 }
1415
1416 static unsigned int vdm_ready_timeout(u32 vdm_hdr)
1417 {
1418         unsigned int timeout;
1419         int cmd = PD_VDO_CMD(vdm_hdr);
1420
1421         /* its not a structured VDM command */
1422         if (!PD_VDO_SVDM(vdm_hdr))
1423                 return PD_T_VDM_UNSTRUCTURED;
1424
1425         switch (PD_VDO_CMDT(vdm_hdr)) {
1426         case CMDT_INIT:
1427                 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1428                         timeout = PD_T_VDM_WAIT_MODE_E;
1429                 else
1430                         timeout = PD_T_VDM_SNDR_RSP;
1431                 break;
1432         default:
1433                 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1434                         timeout = PD_T_VDM_E_MODE;
1435                 else
1436                         timeout = PD_T_VDM_RCVR_RSP;
1437                 break;
1438         }
1439         return timeout;
1440 }
1441
1442 static void vdm_run_state_machine(struct tcpm_port *port)
1443 {
1444         struct pd_message msg;
1445         int i, res;
1446
1447         switch (port->vdm_state) {
1448         case VDM_STATE_READY:
1449                 /* Only transmit VDM if attached */
1450                 if (!port->attached) {
1451                         port->vdm_state = VDM_STATE_ERR_BUSY;
1452                         break;
1453                 }
1454
1455                 /*
1456                  * if there's traffic or we're not in PDO ready state don't send
1457                  * a VDM.
1458                  */
1459                 if (port->state != SRC_READY && port->state != SNK_READY)
1460                         break;
1461
1462                 /* Prepare and send VDM */
1463                 memset(&msg, 0, sizeof(msg));
1464                 msg.header = PD_HEADER_LE(PD_DATA_VENDOR_DEF,
1465                                           port->pwr_role,
1466                                           port->data_role,
1467                                           port->negotiated_rev,
1468                                           port->message_id, port->vdo_count);
1469                 for (i = 0; i < port->vdo_count; i++)
1470                         msg.payload[i] = cpu_to_le32(port->vdo_data[i]);
1471                 res = tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1472                 if (res < 0) {
1473                         port->vdm_state = VDM_STATE_ERR_SEND;
1474                 } else {
1475                         unsigned long timeout;
1476
1477                         port->vdm_retries = 0;
1478                         port->vdm_state = VDM_STATE_BUSY;
1479                         timeout = vdm_ready_timeout(port->vdo_data[0]);
1480                         mod_vdm_delayed_work(port, timeout);
1481                 }
1482                 break;
1483         case VDM_STATE_WAIT_RSP_BUSY:
1484                 port->vdo_data[0] = port->vdo_retry;
1485                 port->vdo_count = 1;
1486                 port->vdm_state = VDM_STATE_READY;
1487                 break;
1488         case VDM_STATE_BUSY:
1489                 port->vdm_state = VDM_STATE_ERR_TMOUT;
1490                 break;
1491         case VDM_STATE_ERR_SEND:
1492                 /*
1493                  * A partner which does not support USB PD will not reply,
1494                  * so this is not a fatal error. At the same time, some
1495                  * devices may not return GoodCRC under some circumstances,
1496                  * so we need to retry.
1497                  */
1498                 if (port->vdm_retries < 3) {
1499                         tcpm_log(port, "VDM Tx error, retry");
1500                         port->vdm_retries++;
1501                         port->vdm_state = VDM_STATE_READY;
1502                 }
1503                 break;
1504         default:
1505                 break;
1506         }
1507 }
1508
1509 static void vdm_state_machine_work(struct kthread_work *work)
1510 {
1511         struct tcpm_port *port = container_of(work, struct tcpm_port, vdm_state_machine);
1512         enum vdm_states prev_state;
1513
1514         mutex_lock(&port->lock);
1515
1516         /*
1517          * Continue running as long as the port is not busy and there was
1518          * a state change.
1519          */
1520         do {
1521                 prev_state = port->vdm_state;
1522                 vdm_run_state_machine(port);
1523         } while (port->vdm_state != prev_state &&
1524                  port->vdm_state != VDM_STATE_BUSY);
1525
1526         mutex_unlock(&port->lock);
1527 }
1528
1529 enum pdo_err {
1530         PDO_NO_ERR,
1531         PDO_ERR_NO_VSAFE5V,
1532         PDO_ERR_VSAFE5V_NOT_FIRST,
1533         PDO_ERR_PDO_TYPE_NOT_IN_ORDER,
1534         PDO_ERR_FIXED_NOT_SORTED,
1535         PDO_ERR_VARIABLE_BATT_NOT_SORTED,
1536         PDO_ERR_DUPE_PDO,
1537         PDO_ERR_PPS_APDO_NOT_SORTED,
1538         PDO_ERR_DUPE_PPS_APDO,
1539 };
1540
1541 static const char * const pdo_err_msg[] = {
1542         [PDO_ERR_NO_VSAFE5V] =
1543         " err: source/sink caps should atleast have vSafe5V",
1544         [PDO_ERR_VSAFE5V_NOT_FIRST] =
1545         " err: vSafe5V Fixed Supply Object Shall always be the first object",
1546         [PDO_ERR_PDO_TYPE_NOT_IN_ORDER] =
1547         " err: PDOs should be in the following order: Fixed; Battery; Variable",
1548         [PDO_ERR_FIXED_NOT_SORTED] =
1549         " err: Fixed supply pdos should be in increasing order of their fixed voltage",
1550         [PDO_ERR_VARIABLE_BATT_NOT_SORTED] =
1551         " err: Variable/Battery supply pdos should be in increasing order of their minimum voltage",
1552         [PDO_ERR_DUPE_PDO] =
1553         " err: Variable/Batt supply pdos cannot have same min/max voltage",
1554         [PDO_ERR_PPS_APDO_NOT_SORTED] =
1555         " err: Programmable power supply apdos should be in increasing order of their maximum voltage",
1556         [PDO_ERR_DUPE_PPS_APDO] =
1557         " err: Programmable power supply apdos cannot have same min/max voltage and max current",
1558 };
1559
1560 static enum pdo_err tcpm_caps_err(struct tcpm_port *port, const u32 *pdo,
1561                                   unsigned int nr_pdo)
1562 {
1563         unsigned int i;
1564
1565         /* Should at least contain vSafe5v */
1566         if (nr_pdo < 1)
1567                 return PDO_ERR_NO_VSAFE5V;
1568
1569         /* The vSafe5V Fixed Supply Object Shall always be the first object */
1570         if (pdo_type(pdo[0]) != PDO_TYPE_FIXED ||
1571             pdo_fixed_voltage(pdo[0]) != VSAFE5V)
1572                 return PDO_ERR_VSAFE5V_NOT_FIRST;
1573
1574         for (i = 1; i < nr_pdo; i++) {
1575                 if (pdo_type(pdo[i]) < pdo_type(pdo[i - 1])) {
1576                         return PDO_ERR_PDO_TYPE_NOT_IN_ORDER;
1577                 } else if (pdo_type(pdo[i]) == pdo_type(pdo[i - 1])) {
1578                         enum pd_pdo_type type = pdo_type(pdo[i]);
1579
1580                         switch (type) {
1581                         /*
1582                          * The remaining Fixed Supply Objects, if
1583                          * present, shall be sent in voltage order;
1584                          * lowest to highest.
1585                          */
1586                         case PDO_TYPE_FIXED:
1587                                 if (pdo_fixed_voltage(pdo[i]) <=
1588                                     pdo_fixed_voltage(pdo[i - 1]))
1589                                         return PDO_ERR_FIXED_NOT_SORTED;
1590                                 break;
1591                         /*
1592                          * The Battery Supply Objects and Variable
1593                          * supply, if present shall be sent in Minimum
1594                          * Voltage order; lowest to highest.
1595                          */
1596                         case PDO_TYPE_VAR:
1597                         case PDO_TYPE_BATT:
1598                                 if (pdo_min_voltage(pdo[i]) <
1599                                     pdo_min_voltage(pdo[i - 1]))
1600                                         return PDO_ERR_VARIABLE_BATT_NOT_SORTED;
1601                                 else if ((pdo_min_voltage(pdo[i]) ==
1602                                           pdo_min_voltage(pdo[i - 1])) &&
1603                                          (pdo_max_voltage(pdo[i]) ==
1604                                           pdo_max_voltage(pdo[i - 1])))
1605                                         return PDO_ERR_DUPE_PDO;
1606                                 break;
1607                         /*
1608                          * The Programmable Power Supply APDOs, if present,
1609                          * shall be sent in Maximum Voltage order;
1610                          * lowest to highest.
1611                          */
1612                         case PDO_TYPE_APDO:
1613                                 if (pdo_apdo_type(pdo[i]) != APDO_TYPE_PPS)
1614                                         break;
1615
1616                                 if (pdo_pps_apdo_max_voltage(pdo[i]) <
1617                                     pdo_pps_apdo_max_voltage(pdo[i - 1]))
1618                                         return PDO_ERR_PPS_APDO_NOT_SORTED;
1619                                 else if (pdo_pps_apdo_min_voltage(pdo[i]) ==
1620                                           pdo_pps_apdo_min_voltage(pdo[i - 1]) &&
1621                                          pdo_pps_apdo_max_voltage(pdo[i]) ==
1622                                           pdo_pps_apdo_max_voltage(pdo[i - 1]) &&
1623                                          pdo_pps_apdo_max_current(pdo[i]) ==
1624                                           pdo_pps_apdo_max_current(pdo[i - 1]))
1625                                         return PDO_ERR_DUPE_PPS_APDO;
1626                                 break;
1627                         default:
1628                                 tcpm_log_force(port, " Unknown pdo type");
1629                         }
1630                 }
1631         }
1632
1633         return PDO_NO_ERR;
1634 }
1635
1636 static int tcpm_validate_caps(struct tcpm_port *port, const u32 *pdo,
1637                               unsigned int nr_pdo)
1638 {
1639         enum pdo_err err_index = tcpm_caps_err(port, pdo, nr_pdo);
1640
1641         if (err_index != PDO_NO_ERR) {
1642                 tcpm_log_force(port, " %s", pdo_err_msg[err_index]);
1643                 return -EINVAL;
1644         }
1645
1646         return 0;
1647 }
1648
1649 static int tcpm_altmode_enter(struct typec_altmode *altmode, u32 *vdo)
1650 {
1651         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
1652         u32 header;
1653
1654         header = VDO(altmode->svid, vdo ? 2 : 1, CMD_ENTER_MODE);
1655         header |= VDO_OPOS(altmode->mode);
1656
1657         tcpm_queue_vdm_unlocked(port, header, vdo, vdo ? 1 : 0);
1658         return 0;
1659 }
1660
1661 static int tcpm_altmode_exit(struct typec_altmode *altmode)
1662 {
1663         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
1664         u32 header;
1665
1666         header = VDO(altmode->svid, 1, CMD_EXIT_MODE);
1667         header |= VDO_OPOS(altmode->mode);
1668
1669         tcpm_queue_vdm_unlocked(port, header, NULL, 0);
1670         return 0;
1671 }
1672
1673 static int tcpm_altmode_vdm(struct typec_altmode *altmode,
1674                             u32 header, const u32 *data, int count)
1675 {
1676         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
1677
1678         tcpm_queue_vdm_unlocked(port, header, data, count - 1);
1679
1680         return 0;
1681 }
1682
1683 static const struct typec_altmode_ops tcpm_altmode_ops = {
1684         .enter = tcpm_altmode_enter,
1685         .exit = tcpm_altmode_exit,
1686         .vdm = tcpm_altmode_vdm,
1687 };
1688
1689 /*
1690  * PD (data, control) command handling functions
1691  */
1692 static inline enum tcpm_state ready_state(struct tcpm_port *port)
1693 {
1694         if (port->pwr_role == TYPEC_SOURCE)
1695                 return SRC_READY;
1696         else
1697                 return SNK_READY;
1698 }
1699
1700 static int tcpm_pd_send_control(struct tcpm_port *port,
1701                                 enum pd_ctrl_msg_type type);
1702
1703 static void tcpm_handle_alert(struct tcpm_port *port, const __le32 *payload,
1704                               int cnt)
1705 {
1706         u32 p0 = le32_to_cpu(payload[0]);
1707         unsigned int type = usb_pd_ado_type(p0);
1708
1709         if (!type) {
1710                 tcpm_log(port, "Alert message received with no type");
1711                 return;
1712         }
1713
1714         /* Just handling non-battery alerts for now */
1715         if (!(type & USB_PD_ADO_TYPE_BATT_STATUS_CHANGE)) {
1716                 switch (port->state) {
1717                 case SRC_READY:
1718                 case SNK_READY:
1719                         tcpm_set_state(port, GET_STATUS_SEND, 0);
1720                         break;
1721                 default:
1722                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
1723                         break;
1724                 }
1725         }
1726 }
1727
1728 static void tcpm_pd_data_request(struct tcpm_port *port,
1729                                  const struct pd_message *msg)
1730 {
1731         enum pd_data_msg_type type = pd_header_type_le(msg->header);
1732         unsigned int cnt = pd_header_cnt_le(msg->header);
1733         unsigned int rev = pd_header_rev_le(msg->header);
1734         unsigned int i;
1735         enum frs_typec_current frs_current;
1736         bool frs_enable;
1737         int ret;
1738
1739         switch (type) {
1740         case PD_DATA_SOURCE_CAP:
1741                 if (port->pwr_role != TYPEC_SINK)
1742                         break;
1743
1744                 for (i = 0; i < cnt; i++)
1745                         port->source_caps[i] = le32_to_cpu(msg->payload[i]);
1746
1747                 port->nr_source_caps = cnt;
1748
1749                 tcpm_log_source_caps(port);
1750
1751                 tcpm_validate_caps(port, port->source_caps,
1752                                    port->nr_source_caps);
1753
1754                 /*
1755                  * Adjust revision in subsequent message headers, as required,
1756                  * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
1757                  * support Rev 1.0 so just do nothing in that scenario.
1758                  */
1759                 if (rev == PD_REV10)
1760                         break;
1761
1762                 if (rev < PD_MAX_REV)
1763                         port->negotiated_rev = rev;
1764
1765                 /*
1766                  * This message may be received even if VBUS is not
1767                  * present. This is quite unexpected; see USB PD
1768                  * specification, sections 8.3.3.6.3.1 and 8.3.3.6.3.2.
1769                  * However, at the same time, we must be ready to
1770                  * receive this message and respond to it 15ms after
1771                  * receiving PS_RDY during power swap operations, no matter
1772                  * if VBUS is available or not (USB PD specification,
1773                  * section 6.5.9.2).
1774                  * So we need to accept the message either way,
1775                  * but be prepared to keep waiting for VBUS after it was
1776                  * handled.
1777                  */
1778                 tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
1779                 break;
1780         case PD_DATA_REQUEST:
1781                 if (port->pwr_role != TYPEC_SOURCE ||
1782                     cnt != 1) {
1783                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1784                         break;
1785                 }
1786
1787                 /*
1788                  * Adjust revision in subsequent message headers, as required,
1789                  * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
1790                  * support Rev 1.0 so just reject in that scenario.
1791                  */
1792                 if (rev == PD_REV10) {
1793                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1794                         break;
1795                 }
1796
1797                 if (rev < PD_MAX_REV)
1798                         port->negotiated_rev = rev;
1799
1800                 port->sink_request = le32_to_cpu(msg->payload[0]);
1801                 tcpm_set_state(port, SRC_NEGOTIATE_CAPABILITIES, 0);
1802                 break;
1803         case PD_DATA_SINK_CAP:
1804                 /* We don't do anything with this at the moment... */
1805                 for (i = 0; i < cnt; i++)
1806                         port->sink_caps[i] = le32_to_cpu(msg->payload[i]);
1807
1808                 frs_current = (port->sink_caps[0] & PDO_FIXED_FRS_CURR_MASK) >>
1809                         PDO_FIXED_FRS_CURR_SHIFT;
1810                 frs_enable = frs_current && (frs_current <= port->frs_current);
1811                 tcpm_log(port,
1812                          "Port partner FRS capable partner_frs_current:%u port_frs_current:%u enable:%c",
1813                          frs_current, port->frs_current, frs_enable ? 'y' : 'n');
1814                 if (frs_enable) {
1815                         ret  = port->tcpc->enable_frs(port->tcpc, true);
1816                         tcpm_log(port, "Enable FRS %s, ret:%d\n", ret ? "fail" : "success", ret);
1817                 }
1818
1819                 port->nr_sink_caps = cnt;
1820                 port->sink_cap_done = true;
1821                 tcpm_set_state(port, SNK_READY, 0);
1822                 break;
1823         case PD_DATA_VENDOR_DEF:
1824                 tcpm_handle_vdm_request(port, msg->payload, cnt);
1825                 break;
1826         case PD_DATA_BIST:
1827                 if (port->state == SRC_READY || port->state == SNK_READY) {
1828                         port->bist_request = le32_to_cpu(msg->payload[0]);
1829                         tcpm_set_state(port, BIST_RX, 0);
1830                 }
1831                 break;
1832         case PD_DATA_ALERT:
1833                 tcpm_handle_alert(port, msg->payload, cnt);
1834                 break;
1835         case PD_DATA_BATT_STATUS:
1836         case PD_DATA_GET_COUNTRY_INFO:
1837                 /* Currently unsupported */
1838                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
1839                 break;
1840         default:
1841                 tcpm_log(port, "Unhandled data message type %#x", type);
1842                 break;
1843         }
1844 }
1845
1846 static void tcpm_pps_complete(struct tcpm_port *port, int result)
1847 {
1848         if (port->pps_pending) {
1849                 port->pps_status = result;
1850                 port->pps_pending = false;
1851                 complete(&port->pps_complete);
1852         }
1853 }
1854
1855 static void tcpm_pd_ctrl_request(struct tcpm_port *port,
1856                                  const struct pd_message *msg)
1857 {
1858         enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
1859         enum tcpm_state next_state;
1860
1861         switch (type) {
1862         case PD_CTRL_GOOD_CRC:
1863         case PD_CTRL_PING:
1864                 break;
1865         case PD_CTRL_GET_SOURCE_CAP:
1866                 switch (port->state) {
1867                 case SRC_READY:
1868                 case SNK_READY:
1869                         tcpm_queue_message(port, PD_MSG_DATA_SOURCE_CAP);
1870                         break;
1871                 default:
1872                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1873                         break;
1874                 }
1875                 break;
1876         case PD_CTRL_GET_SINK_CAP:
1877                 switch (port->state) {
1878                 case SRC_READY:
1879                 case SNK_READY:
1880                         tcpm_queue_message(port, PD_MSG_DATA_SINK_CAP);
1881                         break;
1882                 default:
1883                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1884                         break;
1885                 }
1886                 break;
1887         case PD_CTRL_GOTO_MIN:
1888                 break;
1889         case PD_CTRL_PS_RDY:
1890                 switch (port->state) {
1891                 case SNK_TRANSITION_SINK:
1892                         if (port->vbus_present) {
1893                                 tcpm_set_current_limit(port,
1894                                                        port->req_current_limit,
1895                                                        port->req_supply_voltage);
1896                                 port->explicit_contract = true;
1897                                 tcpm_set_state(port, SNK_READY, 0);
1898                         } else {
1899                                 /*
1900                                  * Seen after power swap. Keep waiting for VBUS
1901                                  * in a transitional state.
1902                                  */
1903                                 tcpm_set_state(port,
1904                                                SNK_TRANSITION_SINK_VBUS, 0);
1905                         }
1906                         break;
1907                 case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
1908                         tcpm_set_state(port, PR_SWAP_SRC_SNK_SINK_ON, 0);
1909                         break;
1910                 case PR_SWAP_SNK_SRC_SINK_OFF:
1911                         tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON, 0);
1912                         break;
1913                 case VCONN_SWAP_WAIT_FOR_VCONN:
1914                         tcpm_set_state(port, VCONN_SWAP_TURN_OFF_VCONN, 0);
1915                         break;
1916                 case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
1917                         tcpm_set_state(port, FR_SWAP_SNK_SRC_NEW_SINK_READY, 0);
1918                         break;
1919                 default:
1920                         break;
1921                 }
1922                 break;
1923         case PD_CTRL_REJECT:
1924         case PD_CTRL_WAIT:
1925         case PD_CTRL_NOT_SUPP:
1926                 switch (port->state) {
1927                 case SNK_NEGOTIATE_CAPABILITIES:
1928                         /* USB PD specification, Figure 8-43 */
1929                         if (port->explicit_contract)
1930                                 next_state = SNK_READY;
1931                         else
1932                                 next_state = SNK_WAIT_CAPABILITIES;
1933                         tcpm_set_state(port, next_state, 0);
1934                         break;
1935                 case SNK_NEGOTIATE_PPS_CAPABILITIES:
1936                         /* Revert data back from any requested PPS updates */
1937                         port->pps_data.req_out_volt = port->supply_voltage;
1938                         port->pps_data.req_op_curr = port->current_limit;
1939                         port->pps_status = (type == PD_CTRL_WAIT ?
1940                                             -EAGAIN : -EOPNOTSUPP);
1941                         tcpm_set_state(port, SNK_READY, 0);
1942                         break;
1943                 case DR_SWAP_SEND:
1944                         port->swap_status = (type == PD_CTRL_WAIT ?
1945                                              -EAGAIN : -EOPNOTSUPP);
1946                         tcpm_set_state(port, DR_SWAP_CANCEL, 0);
1947                         break;
1948                 case PR_SWAP_SEND:
1949                         port->swap_status = (type == PD_CTRL_WAIT ?
1950                                              -EAGAIN : -EOPNOTSUPP);
1951                         tcpm_set_state(port, PR_SWAP_CANCEL, 0);
1952                         break;
1953                 case VCONN_SWAP_SEND:
1954                         port->swap_status = (type == PD_CTRL_WAIT ?
1955                                              -EAGAIN : -EOPNOTSUPP);
1956                         tcpm_set_state(port, VCONN_SWAP_CANCEL, 0);
1957                         break;
1958                 case FR_SWAP_SEND:
1959                         tcpm_set_state(port, FR_SWAP_CANCEL, 0);
1960                         break;
1961                 case GET_SINK_CAP:
1962                         port->sink_cap_done = true;
1963                         tcpm_set_state(port, ready_state(port), 0);
1964                         break;
1965                 default:
1966                         break;
1967                 }
1968                 break;
1969         case PD_CTRL_ACCEPT:
1970                 switch (port->state) {
1971                 case SNK_NEGOTIATE_CAPABILITIES:
1972                         port->pps_data.active = false;
1973                         tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
1974                         break;
1975                 case SNK_NEGOTIATE_PPS_CAPABILITIES:
1976                         port->pps_data.active = true;
1977                         port->pps_data.min_volt = port->pps_data.req_min_volt;
1978                         port->pps_data.max_volt = port->pps_data.req_max_volt;
1979                         port->pps_data.max_curr = port->pps_data.req_max_curr;
1980                         port->req_supply_voltage = port->pps_data.req_out_volt;
1981                         port->req_current_limit = port->pps_data.req_op_curr;
1982                         power_supply_changed(port->psy);
1983                         tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
1984                         break;
1985                 case SOFT_RESET_SEND:
1986                         port->message_id = 0;
1987                         port->rx_msgid = -1;
1988                         if (port->pwr_role == TYPEC_SOURCE)
1989                                 next_state = SRC_SEND_CAPABILITIES;
1990                         else
1991                                 next_state = SNK_WAIT_CAPABILITIES;
1992                         tcpm_set_state(port, next_state, 0);
1993                         break;
1994                 case DR_SWAP_SEND:
1995                         tcpm_set_state(port, DR_SWAP_CHANGE_DR, 0);
1996                         break;
1997                 case PR_SWAP_SEND:
1998                         tcpm_set_state(port, PR_SWAP_START, 0);
1999                         break;
2000                 case VCONN_SWAP_SEND:
2001                         tcpm_set_state(port, VCONN_SWAP_START, 0);
2002                         break;
2003                 case FR_SWAP_SEND:
2004                         tcpm_set_state(port, FR_SWAP_SNK_SRC_TRANSITION_TO_OFF, 0);
2005                         break;
2006                 default:
2007                         break;
2008                 }
2009                 break;
2010         case PD_CTRL_SOFT_RESET:
2011                 tcpm_set_state(port, SOFT_RESET, 0);
2012                 break;
2013         case PD_CTRL_DR_SWAP:
2014                 if (port->typec_caps.data != TYPEC_PORT_DRD) {
2015                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
2016                         break;
2017                 }
2018                 /*
2019                  * XXX
2020                  * 6.3.9: If an alternate mode is active, a request to swap
2021                  * alternate modes shall trigger a port reset.
2022                  */
2023                 switch (port->state) {
2024                 case SRC_READY:
2025                 case SNK_READY:
2026                         tcpm_set_state(port, DR_SWAP_ACCEPT, 0);
2027                         break;
2028                 default:
2029                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2030                         break;
2031                 }
2032                 break;
2033         case PD_CTRL_PR_SWAP:
2034                 if (port->port_type != TYPEC_PORT_DRP) {
2035                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
2036                         break;
2037                 }
2038                 switch (port->state) {
2039                 case SRC_READY:
2040                 case SNK_READY:
2041                         tcpm_set_state(port, PR_SWAP_ACCEPT, 0);
2042                         break;
2043                 default:
2044                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2045                         break;
2046                 }
2047                 break;
2048         case PD_CTRL_VCONN_SWAP:
2049                 switch (port->state) {
2050                 case SRC_READY:
2051                 case SNK_READY:
2052                         tcpm_set_state(port, VCONN_SWAP_ACCEPT, 0);
2053                         break;
2054                 default:
2055                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2056                         break;
2057                 }
2058                 break;
2059         case PD_CTRL_GET_SOURCE_CAP_EXT:
2060         case PD_CTRL_GET_STATUS:
2061         case PD_CTRL_FR_SWAP:
2062         case PD_CTRL_GET_PPS_STATUS:
2063         case PD_CTRL_GET_COUNTRY_CODES:
2064                 /* Currently not supported */
2065                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2066                 break;
2067         default:
2068                 tcpm_log(port, "Unhandled ctrl message type %#x", type);
2069                 break;
2070         }
2071 }
2072
2073 static void tcpm_pd_ext_msg_request(struct tcpm_port *port,
2074                                     const struct pd_message *msg)
2075 {
2076         enum pd_ext_msg_type type = pd_header_type_le(msg->header);
2077         unsigned int data_size = pd_ext_header_data_size_le(msg->ext_msg.header);
2078
2079         if (!(msg->ext_msg.header & PD_EXT_HDR_CHUNKED)) {
2080                 tcpm_log(port, "Unchunked extended messages unsupported");
2081                 return;
2082         }
2083
2084         if (data_size > PD_EXT_MAX_CHUNK_DATA) {
2085                 tcpm_log(port, "Chunk handling not yet supported");
2086                 return;
2087         }
2088
2089         switch (type) {
2090         case PD_EXT_STATUS:
2091                 /*
2092                  * If PPS related events raised then get PPS status to clear
2093                  * (see USB PD 3.0 Spec, 6.5.2.4)
2094                  */
2095                 if (msg->ext_msg.data[USB_PD_EXT_SDB_EVENT_FLAGS] &
2096                     USB_PD_EXT_SDB_PPS_EVENTS)
2097                         tcpm_set_state(port, GET_PPS_STATUS_SEND, 0);
2098                 else
2099                         tcpm_set_state(port, ready_state(port), 0);
2100                 break;
2101         case PD_EXT_PPS_STATUS:
2102                 /*
2103                  * For now the PPS status message is used to clear events
2104                  * and nothing more.
2105                  */
2106                 tcpm_set_state(port, ready_state(port), 0);
2107                 break;
2108         case PD_EXT_SOURCE_CAP_EXT:
2109         case PD_EXT_GET_BATT_CAP:
2110         case PD_EXT_GET_BATT_STATUS:
2111         case PD_EXT_BATT_CAP:
2112         case PD_EXT_GET_MANUFACTURER_INFO:
2113         case PD_EXT_MANUFACTURER_INFO:
2114         case PD_EXT_SECURITY_REQUEST:
2115         case PD_EXT_SECURITY_RESPONSE:
2116         case PD_EXT_FW_UPDATE_REQUEST:
2117         case PD_EXT_FW_UPDATE_RESPONSE:
2118         case PD_EXT_COUNTRY_INFO:
2119         case PD_EXT_COUNTRY_CODES:
2120                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2121                 break;
2122         default:
2123                 tcpm_log(port, "Unhandled extended message type %#x", type);
2124                 break;
2125         }
2126 }
2127
2128 static void tcpm_pd_rx_handler(struct kthread_work *work)
2129 {
2130         struct pd_rx_event *event = container_of(work,
2131                                                  struct pd_rx_event, work);
2132         const struct pd_message *msg = &event->msg;
2133         unsigned int cnt = pd_header_cnt_le(msg->header);
2134         struct tcpm_port *port = event->port;
2135
2136         mutex_lock(&port->lock);
2137
2138         tcpm_log(port, "PD RX, header: %#x [%d]", le16_to_cpu(msg->header),
2139                  port->attached);
2140
2141         if (port->attached) {
2142                 enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
2143                 unsigned int msgid = pd_header_msgid_le(msg->header);
2144
2145                 /*
2146                  * USB PD standard, 6.6.1.2:
2147                  * "... if MessageID value in a received Message is the
2148                  * same as the stored value, the receiver shall return a
2149                  * GoodCRC Message with that MessageID value and drop
2150                  * the Message (this is a retry of an already received
2151                  * Message). Note: this shall not apply to the Soft_Reset
2152                  * Message which always has a MessageID value of zero."
2153                  */
2154                 if (msgid == port->rx_msgid && type != PD_CTRL_SOFT_RESET)
2155                         goto done;
2156                 port->rx_msgid = msgid;
2157
2158                 /*
2159                  * If both ends believe to be DFP/host, we have a data role
2160                  * mismatch.
2161                  */
2162                 if (!!(le16_to_cpu(msg->header) & PD_HEADER_DATA_ROLE) ==
2163                     (port->data_role == TYPEC_HOST)) {
2164                         tcpm_log(port,
2165                                  "Data role mismatch, initiating error recovery");
2166                         tcpm_set_state(port, ERROR_RECOVERY, 0);
2167                 } else {
2168                         if (msg->header & PD_HEADER_EXT_HDR)
2169                                 tcpm_pd_ext_msg_request(port, msg);
2170                         else if (cnt)
2171                                 tcpm_pd_data_request(port, msg);
2172                         else
2173                                 tcpm_pd_ctrl_request(port, msg);
2174                 }
2175         }
2176
2177 done:
2178         mutex_unlock(&port->lock);
2179         kfree(event);
2180 }
2181
2182 void tcpm_pd_receive(struct tcpm_port *port, const struct pd_message *msg)
2183 {
2184         struct pd_rx_event *event;
2185
2186         event = kzalloc(sizeof(*event), GFP_ATOMIC);
2187         if (!event)
2188                 return;
2189
2190         kthread_init_work(&event->work, tcpm_pd_rx_handler);
2191         event->port = port;
2192         memcpy(&event->msg, msg, sizeof(*msg));
2193         kthread_queue_work(port->wq, &event->work);
2194 }
2195 EXPORT_SYMBOL_GPL(tcpm_pd_receive);
2196
2197 static int tcpm_pd_send_control(struct tcpm_port *port,
2198                                 enum pd_ctrl_msg_type type)
2199 {
2200         struct pd_message msg;
2201
2202         memset(&msg, 0, sizeof(msg));
2203         msg.header = PD_HEADER_LE(type, port->pwr_role,
2204                                   port->data_role,
2205                                   port->negotiated_rev,
2206                                   port->message_id, 0);
2207
2208         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2209 }
2210
2211 /*
2212  * Send queued message without affecting state.
2213  * Return true if state machine should go back to sleep,
2214  * false otherwise.
2215  */
2216 static bool tcpm_send_queued_message(struct tcpm_port *port)
2217 {
2218         enum pd_msg_request queued_message;
2219
2220         do {
2221                 queued_message = port->queued_message;
2222                 port->queued_message = PD_MSG_NONE;
2223
2224                 switch (queued_message) {
2225                 case PD_MSG_CTRL_WAIT:
2226                         tcpm_pd_send_control(port, PD_CTRL_WAIT);
2227                         break;
2228                 case PD_MSG_CTRL_REJECT:
2229                         tcpm_pd_send_control(port, PD_CTRL_REJECT);
2230                         break;
2231                 case PD_MSG_CTRL_NOT_SUPP:
2232                         tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP);
2233                         break;
2234                 case PD_MSG_DATA_SINK_CAP:
2235                         tcpm_pd_send_sink_caps(port);
2236                         break;
2237                 case PD_MSG_DATA_SOURCE_CAP:
2238                         tcpm_pd_send_source_caps(port);
2239                         break;
2240                 default:
2241                         break;
2242                 }
2243         } while (port->queued_message != PD_MSG_NONE);
2244
2245         if (port->delayed_state != INVALID_STATE) {
2246                 if (ktime_after(port->delayed_runtime, ktime_get())) {
2247                         mod_tcpm_delayed_work(port, ktime_to_ms(ktime_sub(port->delayed_runtime,
2248                                                                           ktime_get())));
2249                         return true;
2250                 }
2251                 port->delayed_state = INVALID_STATE;
2252         }
2253         return false;
2254 }
2255
2256 static int tcpm_pd_check_request(struct tcpm_port *port)
2257 {
2258         u32 pdo, rdo = port->sink_request;
2259         unsigned int max, op, pdo_max, index;
2260         enum pd_pdo_type type;
2261
2262         index = rdo_index(rdo);
2263         if (!index || index > port->nr_src_pdo)
2264                 return -EINVAL;
2265
2266         pdo = port->src_pdo[index - 1];
2267         type = pdo_type(pdo);
2268         switch (type) {
2269         case PDO_TYPE_FIXED:
2270         case PDO_TYPE_VAR:
2271                 max = rdo_max_current(rdo);
2272                 op = rdo_op_current(rdo);
2273                 pdo_max = pdo_max_current(pdo);
2274
2275                 if (op > pdo_max)
2276                         return -EINVAL;
2277                 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
2278                         return -EINVAL;
2279
2280                 if (type == PDO_TYPE_FIXED)
2281                         tcpm_log(port,
2282                                  "Requested %u mV, %u mA for %u / %u mA",
2283                                  pdo_fixed_voltage(pdo), pdo_max, op, max);
2284                 else
2285                         tcpm_log(port,
2286                                  "Requested %u -> %u mV, %u mA for %u / %u mA",
2287                                  pdo_min_voltage(pdo), pdo_max_voltage(pdo),
2288                                  pdo_max, op, max);
2289                 break;
2290         case PDO_TYPE_BATT:
2291                 max = rdo_max_power(rdo);
2292                 op = rdo_op_power(rdo);
2293                 pdo_max = pdo_max_power(pdo);
2294
2295                 if (op > pdo_max)
2296                         return -EINVAL;
2297                 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
2298                         return -EINVAL;
2299                 tcpm_log(port,
2300                          "Requested %u -> %u mV, %u mW for %u / %u mW",
2301                          pdo_min_voltage(pdo), pdo_max_voltage(pdo),
2302                          pdo_max, op, max);
2303                 break;
2304         default:
2305                 return -EINVAL;
2306         }
2307
2308         port->op_vsafe5v = index == 1;
2309
2310         return 0;
2311 }
2312
2313 #define min_power(x, y) min(pdo_max_power(x), pdo_max_power(y))
2314 #define min_current(x, y) min(pdo_max_current(x), pdo_max_current(y))
2315
2316 static int tcpm_pd_select_pdo(struct tcpm_port *port, int *sink_pdo,
2317                               int *src_pdo)
2318 {
2319         unsigned int i, j, max_src_mv = 0, min_src_mv = 0, max_mw = 0,
2320                      max_mv = 0, src_mw = 0, src_ma = 0, max_snk_mv = 0,
2321                      min_snk_mv = 0;
2322         int ret = -EINVAL;
2323
2324         port->pps_data.supported = false;
2325         port->usb_type = POWER_SUPPLY_USB_TYPE_PD;
2326         power_supply_changed(port->psy);
2327
2328         /*
2329          * Select the source PDO providing the most power which has a
2330          * matchig sink cap.
2331          */
2332         for (i = 0; i < port->nr_source_caps; i++) {
2333                 u32 pdo = port->source_caps[i];
2334                 enum pd_pdo_type type = pdo_type(pdo);
2335
2336                 switch (type) {
2337                 case PDO_TYPE_FIXED:
2338                         max_src_mv = pdo_fixed_voltage(pdo);
2339                         min_src_mv = max_src_mv;
2340                         break;
2341                 case PDO_TYPE_BATT:
2342                 case PDO_TYPE_VAR:
2343                         max_src_mv = pdo_max_voltage(pdo);
2344                         min_src_mv = pdo_min_voltage(pdo);
2345                         break;
2346                 case PDO_TYPE_APDO:
2347                         if (pdo_apdo_type(pdo) == APDO_TYPE_PPS) {
2348                                 port->pps_data.supported = true;
2349                                 port->usb_type =
2350                                         POWER_SUPPLY_USB_TYPE_PD_PPS;
2351                                 power_supply_changed(port->psy);
2352                         }
2353                         continue;
2354                 default:
2355                         tcpm_log(port, "Invalid source PDO type, ignoring");
2356                         continue;
2357                 }
2358
2359                 switch (type) {
2360                 case PDO_TYPE_FIXED:
2361                 case PDO_TYPE_VAR:
2362                         src_ma = pdo_max_current(pdo);
2363                         src_mw = src_ma * min_src_mv / 1000;
2364                         break;
2365                 case PDO_TYPE_BATT:
2366                         src_mw = pdo_max_power(pdo);
2367                         break;
2368                 case PDO_TYPE_APDO:
2369                         continue;
2370                 default:
2371                         tcpm_log(port, "Invalid source PDO type, ignoring");
2372                         continue;
2373                 }
2374
2375                 for (j = 0; j < port->nr_snk_pdo; j++) {
2376                         pdo = port->snk_pdo[j];
2377
2378                         switch (pdo_type(pdo)) {
2379                         case PDO_TYPE_FIXED:
2380                                 max_snk_mv = pdo_fixed_voltage(pdo);
2381                                 min_snk_mv = max_snk_mv;
2382                                 break;
2383                         case PDO_TYPE_BATT:
2384                         case PDO_TYPE_VAR:
2385                                 max_snk_mv = pdo_max_voltage(pdo);
2386                                 min_snk_mv = pdo_min_voltage(pdo);
2387                                 break;
2388                         case PDO_TYPE_APDO:
2389                                 continue;
2390                         default:
2391                                 tcpm_log(port, "Invalid sink PDO type, ignoring");
2392                                 continue;
2393                         }
2394
2395                         if (max_src_mv <= max_snk_mv &&
2396                                 min_src_mv >= min_snk_mv) {
2397                                 /* Prefer higher voltages if available */
2398                                 if ((src_mw == max_mw && min_src_mv > max_mv) ||
2399                                                         src_mw > max_mw) {
2400                                         *src_pdo = i;
2401                                         *sink_pdo = j;
2402                                         max_mw = src_mw;
2403                                         max_mv = min_src_mv;
2404                                         ret = 0;
2405                                 }
2406                         }
2407                 }
2408         }
2409
2410         return ret;
2411 }
2412
2413 #define min_pps_apdo_current(x, y)      \
2414         min(pdo_pps_apdo_max_current(x), pdo_pps_apdo_max_current(y))
2415
2416 static unsigned int tcpm_pd_select_pps_apdo(struct tcpm_port *port)
2417 {
2418         unsigned int i, j, max_mw = 0, max_mv = 0;
2419         unsigned int min_src_mv, max_src_mv, src_ma, src_mw;
2420         unsigned int min_snk_mv, max_snk_mv;
2421         unsigned int max_op_mv;
2422         u32 pdo, src, snk;
2423         unsigned int src_pdo = 0, snk_pdo = 0;
2424
2425         /*
2426          * Select the source PPS APDO providing the most power while staying
2427          * within the board's limits. We skip the first PDO as this is always
2428          * 5V 3A.
2429          */
2430         for (i = 1; i < port->nr_source_caps; ++i) {
2431                 pdo = port->source_caps[i];
2432
2433                 switch (pdo_type(pdo)) {
2434                 case PDO_TYPE_APDO:
2435                         if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
2436                                 tcpm_log(port, "Not PPS APDO (source), ignoring");
2437                                 continue;
2438                         }
2439
2440                         min_src_mv = pdo_pps_apdo_min_voltage(pdo);
2441                         max_src_mv = pdo_pps_apdo_max_voltage(pdo);
2442                         src_ma = pdo_pps_apdo_max_current(pdo);
2443                         src_mw = (src_ma * max_src_mv) / 1000;
2444
2445                         /*
2446                          * Now search through the sink PDOs to find a matching
2447                          * PPS APDO. Again skip the first sink PDO as this will
2448                          * always be 5V 3A.
2449                          */
2450                         for (j = 1; j < port->nr_snk_pdo; j++) {
2451                                 pdo = port->snk_pdo[j];
2452
2453                                 switch (pdo_type(pdo)) {
2454                                 case PDO_TYPE_APDO:
2455                                         if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
2456                                                 tcpm_log(port,
2457                                                          "Not PPS APDO (sink), ignoring");
2458                                                 continue;
2459                                         }
2460
2461                                         min_snk_mv =
2462                                                 pdo_pps_apdo_min_voltage(pdo);
2463                                         max_snk_mv =
2464                                                 pdo_pps_apdo_max_voltage(pdo);
2465                                         break;
2466                                 default:
2467                                         tcpm_log(port,
2468                                                  "Not APDO type (sink), ignoring");
2469                                         continue;
2470                                 }
2471
2472                                 if (min_src_mv <= max_snk_mv &&
2473                                     max_src_mv >= min_snk_mv) {
2474                                         max_op_mv = min(max_src_mv, max_snk_mv);
2475                                         src_mw = (max_op_mv * src_ma) / 1000;
2476                                         /* Prefer higher voltages if available */
2477                                         if ((src_mw == max_mw &&
2478                                              max_op_mv > max_mv) ||
2479                                             src_mw > max_mw) {
2480                                                 src_pdo = i;
2481                                                 snk_pdo = j;
2482                                                 max_mw = src_mw;
2483                                                 max_mv = max_op_mv;
2484                                         }
2485                                 }
2486                         }
2487
2488                         break;
2489                 default:
2490                         tcpm_log(port, "Not APDO type (source), ignoring");
2491                         continue;
2492                 }
2493         }
2494
2495         if (src_pdo) {
2496                 src = port->source_caps[src_pdo];
2497                 snk = port->snk_pdo[snk_pdo];
2498
2499                 port->pps_data.req_min_volt = max(pdo_pps_apdo_min_voltage(src),
2500                                                   pdo_pps_apdo_min_voltage(snk));
2501                 port->pps_data.req_max_volt = min(pdo_pps_apdo_max_voltage(src),
2502                                                   pdo_pps_apdo_max_voltage(snk));
2503                 port->pps_data.req_max_curr = min_pps_apdo_current(src, snk);
2504                 port->pps_data.req_out_volt = min(port->pps_data.req_max_volt,
2505                                                   max(port->pps_data.req_min_volt,
2506                                                       port->pps_data.req_out_volt));
2507                 port->pps_data.req_op_curr = min(port->pps_data.req_max_curr,
2508                                                  port->pps_data.req_op_curr);
2509         }
2510
2511         return src_pdo;
2512 }
2513
2514 static int tcpm_pd_build_request(struct tcpm_port *port, u32 *rdo)
2515 {
2516         unsigned int mv, ma, mw, flags;
2517         unsigned int max_ma, max_mw;
2518         enum pd_pdo_type type;
2519         u32 pdo, matching_snk_pdo;
2520         int src_pdo_index = 0;
2521         int snk_pdo_index = 0;
2522         int ret;
2523
2524         ret = tcpm_pd_select_pdo(port, &snk_pdo_index, &src_pdo_index);
2525         if (ret < 0)
2526                 return ret;
2527
2528         pdo = port->source_caps[src_pdo_index];
2529         matching_snk_pdo = port->snk_pdo[snk_pdo_index];
2530         type = pdo_type(pdo);
2531
2532         switch (type) {
2533         case PDO_TYPE_FIXED:
2534                 mv = pdo_fixed_voltage(pdo);
2535                 break;
2536         case PDO_TYPE_BATT:
2537         case PDO_TYPE_VAR:
2538                 mv = pdo_min_voltage(pdo);
2539                 break;
2540         default:
2541                 tcpm_log(port, "Invalid PDO selected!");
2542                 return -EINVAL;
2543         }
2544
2545         /* Select maximum available current within the sink pdo's limit */
2546         if (type == PDO_TYPE_BATT) {
2547                 mw = min_power(pdo, matching_snk_pdo);
2548                 ma = 1000 * mw / mv;
2549         } else {
2550                 ma = min_current(pdo, matching_snk_pdo);
2551                 mw = ma * mv / 1000;
2552         }
2553
2554         flags = RDO_USB_COMM | RDO_NO_SUSPEND;
2555
2556         /* Set mismatch bit if offered power is less than operating power */
2557         max_ma = ma;
2558         max_mw = mw;
2559         if (mw < port->operating_snk_mw) {
2560                 flags |= RDO_CAP_MISMATCH;
2561                 if (type == PDO_TYPE_BATT &&
2562                     (pdo_max_power(matching_snk_pdo) > pdo_max_power(pdo)))
2563                         max_mw = pdo_max_power(matching_snk_pdo);
2564                 else if (pdo_max_current(matching_snk_pdo) >
2565                          pdo_max_current(pdo))
2566                         max_ma = pdo_max_current(matching_snk_pdo);
2567         }
2568
2569         tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
2570                  port->cc_req, port->cc1, port->cc2, port->vbus_source,
2571                  port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
2572                  port->polarity);
2573
2574         if (type == PDO_TYPE_BATT) {
2575                 *rdo = RDO_BATT(src_pdo_index + 1, mw, max_mw, flags);
2576
2577                 tcpm_log(port, "Requesting PDO %d: %u mV, %u mW%s",
2578                          src_pdo_index, mv, mw,
2579                          flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
2580         } else {
2581                 *rdo = RDO_FIXED(src_pdo_index + 1, ma, max_ma, flags);
2582
2583                 tcpm_log(port, "Requesting PDO %d: %u mV, %u mA%s",
2584                          src_pdo_index, mv, ma,
2585                          flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
2586         }
2587
2588         port->req_current_limit = ma;
2589         port->req_supply_voltage = mv;
2590
2591         return 0;
2592 }
2593
2594 static int tcpm_pd_send_request(struct tcpm_port *port)
2595 {
2596         struct pd_message msg;
2597         int ret;
2598         u32 rdo;
2599
2600         ret = tcpm_pd_build_request(port, &rdo);
2601         if (ret < 0)
2602                 return ret;
2603
2604         memset(&msg, 0, sizeof(msg));
2605         msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
2606                                   port->pwr_role,
2607                                   port->data_role,
2608                                   port->negotiated_rev,
2609                                   port->message_id, 1);
2610         msg.payload[0] = cpu_to_le32(rdo);
2611
2612         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2613 }
2614
2615 static int tcpm_pd_build_pps_request(struct tcpm_port *port, u32 *rdo)
2616 {
2617         unsigned int out_mv, op_ma, op_mw, max_mv, max_ma, flags;
2618         enum pd_pdo_type type;
2619         unsigned int src_pdo_index;
2620         u32 pdo;
2621
2622         src_pdo_index = tcpm_pd_select_pps_apdo(port);
2623         if (!src_pdo_index)
2624                 return -EOPNOTSUPP;
2625
2626         pdo = port->source_caps[src_pdo_index];
2627         type = pdo_type(pdo);
2628
2629         switch (type) {
2630         case PDO_TYPE_APDO:
2631                 if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
2632                         tcpm_log(port, "Invalid APDO selected!");
2633                         return -EINVAL;
2634                 }
2635                 max_mv = port->pps_data.req_max_volt;
2636                 max_ma = port->pps_data.req_max_curr;
2637                 out_mv = port->pps_data.req_out_volt;
2638                 op_ma = port->pps_data.req_op_curr;
2639                 break;
2640         default:
2641                 tcpm_log(port, "Invalid PDO selected!");
2642                 return -EINVAL;
2643         }
2644
2645         flags = RDO_USB_COMM | RDO_NO_SUSPEND;
2646
2647         op_mw = (op_ma * out_mv) / 1000;
2648         if (op_mw < port->operating_snk_mw) {
2649                 /*
2650                  * Try raising current to meet power needs. If that's not enough
2651                  * then try upping the voltage. If that's still not enough
2652                  * then we've obviously chosen a PPS APDO which really isn't
2653                  * suitable so abandon ship.
2654                  */
2655                 op_ma = (port->operating_snk_mw * 1000) / out_mv;
2656                 if ((port->operating_snk_mw * 1000) % out_mv)
2657                         ++op_ma;
2658                 op_ma += RDO_PROG_CURR_MA_STEP - (op_ma % RDO_PROG_CURR_MA_STEP);
2659
2660                 if (op_ma > max_ma) {
2661                         op_ma = max_ma;
2662                         out_mv = (port->operating_snk_mw * 1000) / op_ma;
2663                         if ((port->operating_snk_mw * 1000) % op_ma)
2664                                 ++out_mv;
2665                         out_mv += RDO_PROG_VOLT_MV_STEP -
2666                                   (out_mv % RDO_PROG_VOLT_MV_STEP);
2667
2668                         if (out_mv > max_mv) {
2669                                 tcpm_log(port, "Invalid PPS APDO selected!");
2670                                 return -EINVAL;
2671                         }
2672                 }
2673         }
2674
2675         tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
2676                  port->cc_req, port->cc1, port->cc2, port->vbus_source,
2677                  port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
2678                  port->polarity);
2679
2680         *rdo = RDO_PROG(src_pdo_index + 1, out_mv, op_ma, flags);
2681
2682         tcpm_log(port, "Requesting APDO %d: %u mV, %u mA",
2683                  src_pdo_index, out_mv, op_ma);
2684
2685         port->pps_data.req_op_curr = op_ma;
2686         port->pps_data.req_out_volt = out_mv;
2687
2688         return 0;
2689 }
2690
2691 static int tcpm_pd_send_pps_request(struct tcpm_port *port)
2692 {
2693         struct pd_message msg;
2694         int ret;
2695         u32 rdo;
2696
2697         ret = tcpm_pd_build_pps_request(port, &rdo);
2698         if (ret < 0)
2699                 return ret;
2700
2701         memset(&msg, 0, sizeof(msg));
2702         msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
2703                                   port->pwr_role,
2704                                   port->data_role,
2705                                   port->negotiated_rev,
2706                                   port->message_id, 1);
2707         msg.payload[0] = cpu_to_le32(rdo);
2708
2709         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2710 }
2711
2712 static int tcpm_set_vbus(struct tcpm_port *port, bool enable)
2713 {
2714         int ret;
2715
2716         if (enable && port->vbus_charge)
2717                 return -EINVAL;
2718
2719         tcpm_log(port, "vbus:=%d charge=%d", enable, port->vbus_charge);
2720
2721         ret = port->tcpc->set_vbus(port->tcpc, enable, port->vbus_charge);
2722         if (ret < 0)
2723                 return ret;
2724
2725         port->vbus_source = enable;
2726         return 0;
2727 }
2728
2729 static int tcpm_set_charge(struct tcpm_port *port, bool charge)
2730 {
2731         int ret;
2732
2733         if (charge && port->vbus_source)
2734                 return -EINVAL;
2735
2736         if (charge != port->vbus_charge) {
2737                 tcpm_log(port, "vbus=%d charge:=%d", port->vbus_source, charge);
2738                 ret = port->tcpc->set_vbus(port->tcpc, port->vbus_source,
2739                                            charge);
2740                 if (ret < 0)
2741                         return ret;
2742         }
2743         port->vbus_charge = charge;
2744         power_supply_changed(port->psy);
2745         return 0;
2746 }
2747
2748 static bool tcpm_start_toggling(struct tcpm_port *port, enum typec_cc_status cc)
2749 {
2750         int ret;
2751
2752         if (!port->tcpc->start_toggling)
2753                 return false;
2754
2755         tcpm_log_force(port, "Start toggling");
2756         ret = port->tcpc->start_toggling(port->tcpc, port->port_type, cc);
2757         return ret == 0;
2758 }
2759
2760 static void tcpm_set_cc(struct tcpm_port *port, enum typec_cc_status cc)
2761 {
2762         tcpm_log(port, "cc:=%d", cc);
2763         port->cc_req = cc;
2764         port->tcpc->set_cc(port->tcpc, cc);
2765 }
2766
2767 static int tcpm_init_vbus(struct tcpm_port *port)
2768 {
2769         int ret;
2770
2771         ret = port->tcpc->set_vbus(port->tcpc, false, false);
2772         port->vbus_source = false;
2773         port->vbus_charge = false;
2774         return ret;
2775 }
2776
2777 static int tcpm_init_vconn(struct tcpm_port *port)
2778 {
2779         int ret;
2780
2781         ret = port->tcpc->set_vconn(port->tcpc, false);
2782         port->vconn_role = TYPEC_SINK;
2783         return ret;
2784 }
2785
2786 static void tcpm_typec_connect(struct tcpm_port *port)
2787 {
2788         if (!port->connected) {
2789                 /* Make sure we don't report stale identity information */
2790                 memset(&port->partner_ident, 0, sizeof(port->partner_ident));
2791                 port->partner_desc.usb_pd = port->pd_capable;
2792                 if (tcpm_port_is_debug(port))
2793                         port->partner_desc.accessory = TYPEC_ACCESSORY_DEBUG;
2794                 else if (tcpm_port_is_audio(port))
2795                         port->partner_desc.accessory = TYPEC_ACCESSORY_AUDIO;
2796                 else
2797                         port->partner_desc.accessory = TYPEC_ACCESSORY_NONE;
2798                 port->partner = typec_register_partner(port->typec_port,
2799                                                        &port->partner_desc);
2800                 port->connected = true;
2801         }
2802 }
2803
2804 static int tcpm_src_attach(struct tcpm_port *port)
2805 {
2806         enum typec_cc_polarity polarity =
2807                                 port->cc2 == TYPEC_CC_RD ? TYPEC_POLARITY_CC2
2808                                                          : TYPEC_POLARITY_CC1;
2809         int ret;
2810
2811         if (port->attached)
2812                 return 0;
2813
2814         ret = tcpm_set_polarity(port, polarity);
2815         if (ret < 0)
2816                 return ret;
2817
2818         ret = tcpm_set_roles(port, true, TYPEC_SOURCE,
2819                              tcpm_data_role_for_source(port));
2820         if (ret < 0)
2821                 return ret;
2822
2823         ret = port->tcpc->set_pd_rx(port->tcpc, true);
2824         if (ret < 0)
2825                 goto out_disable_mux;
2826
2827         /*
2828          * USB Type-C specification, version 1.2,
2829          * chapter 4.5.2.2.8.1 (Attached.SRC Requirements)
2830          * Enable VCONN only if the non-RD port is set to RA.
2831          */
2832         if ((polarity == TYPEC_POLARITY_CC1 && port->cc2 == TYPEC_CC_RA) ||
2833             (polarity == TYPEC_POLARITY_CC2 && port->cc1 == TYPEC_CC_RA)) {
2834                 ret = tcpm_set_vconn(port, true);
2835                 if (ret < 0)
2836                         goto out_disable_pd;
2837         }
2838
2839         ret = tcpm_set_vbus(port, true);
2840         if (ret < 0)
2841                 goto out_disable_vconn;
2842
2843         port->pd_capable = false;
2844
2845         port->partner = NULL;
2846
2847         port->attached = true;
2848         port->send_discover = true;
2849
2850         return 0;
2851
2852 out_disable_vconn:
2853         tcpm_set_vconn(port, false);
2854 out_disable_pd:
2855         port->tcpc->set_pd_rx(port->tcpc, false);
2856 out_disable_mux:
2857         tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
2858                      TYPEC_ORIENTATION_NONE);
2859         return ret;
2860 }
2861
2862 static void tcpm_typec_disconnect(struct tcpm_port *port)
2863 {
2864         if (port->connected) {
2865                 typec_unregister_partner(port->partner);
2866                 port->partner = NULL;
2867                 port->connected = false;
2868         }
2869 }
2870
2871 static void tcpm_unregister_altmodes(struct tcpm_port *port)
2872 {
2873         struct pd_mode_data *modep = &port->mode_data;
2874         int i;
2875
2876         for (i = 0; i < modep->altmodes; i++) {
2877                 typec_unregister_altmode(port->partner_altmode[i]);
2878                 port->partner_altmode[i] = NULL;
2879         }
2880
2881         memset(modep, 0, sizeof(*modep));
2882 }
2883
2884 static void tcpm_reset_port(struct tcpm_port *port)
2885 {
2886         tcpm_unregister_altmodes(port);
2887         tcpm_typec_disconnect(port);
2888         port->attached = false;
2889         port->pd_capable = false;
2890         port->pps_data.supported = false;
2891
2892         /*
2893          * First Rx ID should be 0; set this to a sentinel of -1 so that
2894          * we can check tcpm_pd_rx_handler() if we had seen it before.
2895          */
2896         port->rx_msgid = -1;
2897
2898         port->tcpc->set_pd_rx(port->tcpc, false);
2899         tcpm_init_vbus(port);   /* also disables charging */
2900         tcpm_init_vconn(port);
2901         tcpm_set_current_limit(port, 0, 0);
2902         tcpm_set_polarity(port, TYPEC_POLARITY_CC1);
2903         tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
2904                      TYPEC_ORIENTATION_NONE);
2905         tcpm_set_attached_state(port, false);
2906         port->try_src_count = 0;
2907         port->try_snk_count = 0;
2908         port->usb_type = POWER_SUPPLY_USB_TYPE_C;
2909         power_supply_changed(port->psy);
2910         port->nr_sink_caps = 0;
2911         port->sink_cap_done = false;
2912         if (port->tcpc->enable_frs)
2913                 port->tcpc->enable_frs(port->tcpc, false);
2914 }
2915
2916 static void tcpm_detach(struct tcpm_port *port)
2917 {
2918         if (tcpm_port_is_disconnected(port))
2919                 port->hard_reset_count = 0;
2920
2921         if (!port->attached)
2922                 return;
2923
2924         if (port->tcpc->set_bist_data) {
2925                 tcpm_log(port, "disable BIST MODE TESTDATA");
2926                 port->tcpc->set_bist_data(port->tcpc, false);
2927         }
2928
2929         tcpm_reset_port(port);
2930 }
2931
2932 static void tcpm_src_detach(struct tcpm_port *port)
2933 {
2934         tcpm_detach(port);
2935 }
2936
2937 static int tcpm_snk_attach(struct tcpm_port *port)
2938 {
2939         int ret;
2940
2941         if (port->attached)
2942                 return 0;
2943
2944         ret = tcpm_set_polarity(port, port->cc2 != TYPEC_CC_OPEN ?
2945                                 TYPEC_POLARITY_CC2 : TYPEC_POLARITY_CC1);
2946         if (ret < 0)
2947                 return ret;
2948
2949         ret = tcpm_set_roles(port, true, TYPEC_SINK,
2950                              tcpm_data_role_for_sink(port));
2951         if (ret < 0)
2952                 return ret;
2953
2954         port->pd_capable = false;
2955
2956         port->partner = NULL;
2957
2958         port->attached = true;
2959         port->send_discover = true;
2960
2961         return 0;
2962 }
2963
2964 static void tcpm_snk_detach(struct tcpm_port *port)
2965 {
2966         tcpm_detach(port);
2967 }
2968
2969 static int tcpm_acc_attach(struct tcpm_port *port)
2970 {
2971         int ret;
2972
2973         if (port->attached)
2974                 return 0;
2975
2976         ret = tcpm_set_roles(port, true, TYPEC_SOURCE,
2977                              tcpm_data_role_for_source(port));
2978         if (ret < 0)
2979                 return ret;
2980
2981         port->partner = NULL;
2982
2983         tcpm_typec_connect(port);
2984
2985         port->attached = true;
2986
2987         return 0;
2988 }
2989
2990 static void tcpm_acc_detach(struct tcpm_port *port)
2991 {
2992         tcpm_detach(port);
2993 }
2994
2995 static inline enum tcpm_state hard_reset_state(struct tcpm_port *port)
2996 {
2997         if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
2998                 return HARD_RESET_SEND;
2999         if (port->pd_capable)
3000                 return ERROR_RECOVERY;
3001         if (port->pwr_role == TYPEC_SOURCE)
3002                 return SRC_UNATTACHED;
3003         if (port->state == SNK_WAIT_CAPABILITIES)
3004                 return SNK_READY;
3005         return SNK_UNATTACHED;
3006 }
3007
3008 static inline enum tcpm_state unattached_state(struct tcpm_port *port)
3009 {
3010         if (port->port_type == TYPEC_PORT_DRP) {
3011                 if (port->pwr_role == TYPEC_SOURCE)
3012                         return SRC_UNATTACHED;
3013                 else
3014                         return SNK_UNATTACHED;
3015         } else if (port->port_type == TYPEC_PORT_SRC) {
3016                 return SRC_UNATTACHED;
3017         }
3018
3019         return SNK_UNATTACHED;
3020 }
3021
3022 static void tcpm_check_send_discover(struct tcpm_port *port)
3023 {
3024         if (port->data_role == TYPEC_HOST && port->send_discover &&
3025             port->pd_capable) {
3026                 tcpm_send_vdm(port, USB_SID_PD, CMD_DISCOVER_IDENT, NULL, 0);
3027                 port->send_discover = false;
3028         }
3029 }
3030
3031 static void tcpm_swap_complete(struct tcpm_port *port, int result)
3032 {
3033         if (port->swap_pending) {
3034                 port->swap_status = result;
3035                 port->swap_pending = false;
3036                 port->non_pd_role_swap = false;
3037                 complete(&port->swap_complete);
3038         }
3039 }
3040
3041 static enum typec_pwr_opmode tcpm_get_pwr_opmode(enum typec_cc_status cc)
3042 {
3043         switch (cc) {
3044         case TYPEC_CC_RP_1_5:
3045                 return TYPEC_PWR_MODE_1_5A;
3046         case TYPEC_CC_RP_3_0:
3047                 return TYPEC_PWR_MODE_3_0A;
3048         case TYPEC_CC_RP_DEF:
3049         default:
3050                 return TYPEC_PWR_MODE_USB;
3051         }
3052 }
3053
3054 static void run_state_machine(struct tcpm_port *port)
3055 {
3056         int ret;
3057         enum typec_pwr_opmode opmode;
3058         unsigned int msecs;
3059
3060         port->enter_state = port->state;
3061         switch (port->state) {
3062         case TOGGLING:
3063                 break;
3064         /* SRC states */
3065         case SRC_UNATTACHED:
3066                 if (!port->non_pd_role_swap)
3067                         tcpm_swap_complete(port, -ENOTCONN);
3068                 tcpm_src_detach(port);
3069                 if (tcpm_start_toggling(port, tcpm_rp_cc(port))) {
3070                         tcpm_set_state(port, TOGGLING, 0);
3071                         break;
3072                 }
3073                 tcpm_set_cc(port, tcpm_rp_cc(port));
3074                 if (port->port_type == TYPEC_PORT_DRP)
3075                         tcpm_set_state(port, SNK_UNATTACHED, PD_T_DRP_SNK);
3076                 break;
3077         case SRC_ATTACH_WAIT:
3078                 if (tcpm_port_is_debug(port))
3079                         tcpm_set_state(port, DEBUG_ACC_ATTACHED,
3080                                        PD_T_CC_DEBOUNCE);
3081                 else if (tcpm_port_is_audio(port))
3082                         tcpm_set_state(port, AUDIO_ACC_ATTACHED,
3083                                        PD_T_CC_DEBOUNCE);
3084                 else if (tcpm_port_is_source(port))
3085                         tcpm_set_state(port,
3086                                        tcpm_try_snk(port) ? SNK_TRY
3087                                                           : SRC_ATTACHED,
3088                                        PD_T_CC_DEBOUNCE);
3089                 break;
3090
3091         case SNK_TRY:
3092                 port->try_snk_count++;
3093                 /*
3094                  * Requirements:
3095                  * - Do not drive vconn or vbus
3096                  * - Terminate CC pins (both) to Rd
3097                  * Action:
3098                  * - Wait for tDRPTry (PD_T_DRP_TRY).
3099                  *   Until then, ignore any state changes.
3100                  */
3101                 tcpm_set_cc(port, TYPEC_CC_RD);
3102                 tcpm_set_state(port, SNK_TRY_WAIT, PD_T_DRP_TRY);
3103                 break;
3104         case SNK_TRY_WAIT:
3105                 if (tcpm_port_is_sink(port)) {
3106                         tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE, 0);
3107                 } else {
3108                         tcpm_set_state(port, SRC_TRYWAIT, 0);
3109                         port->max_wait = 0;
3110                 }
3111                 break;
3112         case SNK_TRY_WAIT_DEBOUNCE:
3113                 tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS,
3114                                PD_T_PD_DEBOUNCE);
3115                 break;
3116         case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
3117                 if (port->vbus_present && tcpm_port_is_sink(port)) {
3118                         tcpm_set_state(port, SNK_ATTACHED, 0);
3119                 } else {
3120                         tcpm_set_state(port, SRC_TRYWAIT, 0);
3121                         port->max_wait = 0;
3122                 }
3123                 break;
3124         case SRC_TRYWAIT:
3125                 tcpm_set_cc(port, tcpm_rp_cc(port));
3126                 if (port->max_wait == 0) {
3127                         port->max_wait = jiffies +
3128                                          msecs_to_jiffies(PD_T_DRP_TRY);
3129                         tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
3130                                        PD_T_DRP_TRY);
3131                 } else {
3132                         if (time_is_after_jiffies(port->max_wait))
3133                                 tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
3134                                                jiffies_to_msecs(port->max_wait -
3135                                                                 jiffies));
3136                         else
3137                                 tcpm_set_state(port, SNK_UNATTACHED, 0);
3138                 }
3139                 break;
3140         case SRC_TRYWAIT_DEBOUNCE:
3141                 tcpm_set_state(port, SRC_ATTACHED, PD_T_CC_DEBOUNCE);
3142                 break;
3143         case SRC_TRYWAIT_UNATTACHED:
3144                 tcpm_set_state(port, SNK_UNATTACHED, 0);
3145                 break;
3146
3147         case SRC_ATTACHED:
3148                 ret = tcpm_src_attach(port);
3149                 tcpm_set_state(port, SRC_UNATTACHED,
3150                                ret < 0 ? 0 : PD_T_PS_SOURCE_ON);
3151                 break;
3152         case SRC_STARTUP:
3153                 opmode =  tcpm_get_pwr_opmode(tcpm_rp_cc(port));
3154                 typec_set_pwr_opmode(port->typec_port, opmode);
3155                 port->pwr_opmode = TYPEC_PWR_MODE_USB;
3156                 port->caps_count = 0;
3157                 port->negotiated_rev = PD_MAX_REV;
3158                 port->message_id = 0;
3159                 port->rx_msgid = -1;
3160                 port->explicit_contract = false;
3161                 tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
3162                 break;
3163         case SRC_SEND_CAPABILITIES:
3164                 port->caps_count++;
3165                 if (port->caps_count > PD_N_CAPS_COUNT) {
3166                         tcpm_set_state(port, SRC_READY, 0);
3167                         break;
3168                 }
3169                 ret = tcpm_pd_send_source_caps(port);
3170                 if (ret < 0) {
3171                         tcpm_set_state(port, SRC_SEND_CAPABILITIES,
3172                                        PD_T_SEND_SOURCE_CAP);
3173                 } else {
3174                         /*
3175                          * Per standard, we should clear the reset counter here.
3176                          * However, that can result in state machine hang-ups.
3177                          * Reset it only in READY state to improve stability.
3178                          */
3179                         /* port->hard_reset_count = 0; */
3180                         port->caps_count = 0;
3181                         port->pd_capable = true;
3182                         tcpm_set_state_cond(port, SRC_SEND_CAPABILITIES_TIMEOUT,
3183                                             PD_T_SEND_SOURCE_CAP);
3184                 }
3185                 break;
3186         case SRC_SEND_CAPABILITIES_TIMEOUT:
3187                 /*
3188                  * Error recovery for a PD_DATA_SOURCE_CAP reply timeout.
3189                  *
3190                  * PD 2.0 sinks are supposed to accept src-capabilities with a
3191                  * 3.0 header and simply ignore any src PDOs which the sink does
3192                  * not understand such as PPS but some 2.0 sinks instead ignore
3193                  * the entire PD_DATA_SOURCE_CAP message, causing contract
3194                  * negotiation to fail.
3195                  *
3196                  * After PD_N_HARD_RESET_COUNT hard-reset attempts, we try
3197                  * sending src-capabilities with a lower PD revision to
3198                  * make these broken sinks work.
3199                  */
3200                 if (port->hard_reset_count < PD_N_HARD_RESET_COUNT) {
3201                         tcpm_set_state(port, HARD_RESET_SEND, 0);
3202                 } else if (port->negotiated_rev > PD_REV20) {
3203                         port->negotiated_rev--;
3204                         port->hard_reset_count = 0;
3205                         tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
3206                 } else {
3207                         tcpm_set_state(port, hard_reset_state(port), 0);
3208                 }
3209                 break;
3210         case SRC_NEGOTIATE_CAPABILITIES:
3211                 ret = tcpm_pd_check_request(port);
3212                 if (ret < 0) {
3213                         tcpm_pd_send_control(port, PD_CTRL_REJECT);
3214                         if (!port->explicit_contract) {
3215                                 tcpm_set_state(port,
3216                                                SRC_WAIT_NEW_CAPABILITIES, 0);
3217                         } else {
3218                                 tcpm_set_state(port, SRC_READY, 0);
3219                         }
3220                 } else {
3221                         tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
3222                         tcpm_set_state(port, SRC_TRANSITION_SUPPLY,
3223                                        PD_T_SRC_TRANSITION);
3224                 }
3225                 break;
3226         case SRC_TRANSITION_SUPPLY:
3227                 /* XXX: regulator_set_voltage(vbus, ...) */
3228                 tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
3229                 port->explicit_contract = true;
3230                 typec_set_pwr_opmode(port->typec_port, TYPEC_PWR_MODE_PD);
3231                 port->pwr_opmode = TYPEC_PWR_MODE_PD;
3232                 tcpm_set_state_cond(port, SRC_READY, 0);
3233                 break;
3234         case SRC_READY:
3235 #if 1
3236                 port->hard_reset_count = 0;
3237 #endif
3238                 port->try_src_count = 0;
3239
3240                 tcpm_swap_complete(port, 0);
3241                 tcpm_typec_connect(port);
3242
3243                 tcpm_check_send_discover(port);
3244                 /*
3245                  * 6.3.5
3246                  * Sending ping messages is not necessary if
3247                  * - the source operates at vSafe5V
3248                  * or
3249                  * - The system is not operating in PD mode
3250                  * or
3251                  * - Both partners are connected using a Type-C connector
3252                  *
3253                  * There is no actual need to send PD messages since the local
3254                  * port type-c and the spec does not clearly say whether PD is
3255                  * possible when type-c is connected to Type-A/B
3256                  */
3257                 break;
3258         case SRC_WAIT_NEW_CAPABILITIES:
3259                 /* Nothing to do... */
3260                 break;
3261
3262         /* SNK states */
3263         case SNK_UNATTACHED:
3264                 if (!port->non_pd_role_swap)
3265                         tcpm_swap_complete(port, -ENOTCONN);
3266                 tcpm_pps_complete(port, -ENOTCONN);
3267                 tcpm_snk_detach(port);
3268                 if (tcpm_start_toggling(port, TYPEC_CC_RD)) {
3269                         tcpm_set_state(port, TOGGLING, 0);
3270                         break;
3271                 }
3272                 tcpm_set_cc(port, TYPEC_CC_RD);
3273                 if (port->port_type == TYPEC_PORT_DRP)
3274                         tcpm_set_state(port, SRC_UNATTACHED, PD_T_DRP_SRC);
3275                 break;
3276         case SNK_ATTACH_WAIT:
3277                 if ((port->cc1 == TYPEC_CC_OPEN &&
3278                      port->cc2 != TYPEC_CC_OPEN) ||
3279                     (port->cc1 != TYPEC_CC_OPEN &&
3280                      port->cc2 == TYPEC_CC_OPEN))
3281                         tcpm_set_state(port, SNK_DEBOUNCED,
3282                                        PD_T_CC_DEBOUNCE);
3283                 else if (tcpm_port_is_disconnected(port))
3284                         tcpm_set_state(port, SNK_UNATTACHED,
3285                                        PD_T_PD_DEBOUNCE);
3286                 break;
3287         case SNK_DEBOUNCED:
3288                 if (tcpm_port_is_disconnected(port))
3289                         tcpm_set_state(port, SNK_UNATTACHED,
3290                                        PD_T_PD_DEBOUNCE);
3291                 else if (port->vbus_present)
3292                         tcpm_set_state(port,
3293                                        tcpm_try_src(port) ? SRC_TRY
3294                                                           : SNK_ATTACHED,
3295                                        0);
3296                 break;
3297         case SRC_TRY:
3298                 port->try_src_count++;
3299                 tcpm_set_cc(port, tcpm_rp_cc(port));
3300                 port->max_wait = 0;
3301                 tcpm_set_state(port, SRC_TRY_WAIT, 0);
3302                 break;
3303         case SRC_TRY_WAIT:
3304                 if (port->max_wait == 0) {
3305                         port->max_wait = jiffies +
3306                                          msecs_to_jiffies(PD_T_DRP_TRY);
3307                         msecs = PD_T_DRP_TRY;
3308                 } else {
3309                         if (time_is_after_jiffies(port->max_wait))
3310                                 msecs = jiffies_to_msecs(port->max_wait -
3311                                                          jiffies);
3312                         else
3313                                 msecs = 0;
3314                 }
3315                 tcpm_set_state(port, SNK_TRYWAIT, msecs);
3316                 break;
3317         case SRC_TRY_DEBOUNCE:
3318                 tcpm_set_state(port, SRC_ATTACHED, PD_T_PD_DEBOUNCE);
3319                 break;
3320         case SNK_TRYWAIT:
3321                 tcpm_set_cc(port, TYPEC_CC_RD);
3322                 tcpm_set_state(port, SNK_TRYWAIT_VBUS, PD_T_CC_DEBOUNCE);
3323                 break;
3324         case SNK_TRYWAIT_VBUS:
3325                 /*
3326                  * TCPM stays in this state indefinitely until VBUS
3327                  * is detected as long as Rp is not detected for
3328                  * more than a time period of tPDDebounce.
3329                  */
3330                 if (port->vbus_present && tcpm_port_is_sink(port)) {
3331                         tcpm_set_state(port, SNK_ATTACHED, 0);
3332                         break;
3333                 }
3334                 if (!tcpm_port_is_sink(port))
3335                         tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
3336                 break;
3337         case SNK_TRYWAIT_DEBOUNCE:
3338                 tcpm_set_state(port, SNK_UNATTACHED, PD_T_PD_DEBOUNCE);
3339                 break;
3340         case SNK_ATTACHED:
3341                 ret = tcpm_snk_attach(port);
3342                 if (ret < 0)
3343                         tcpm_set_state(port, SNK_UNATTACHED, 0);
3344                 else
3345                         tcpm_set_state(port, SNK_STARTUP, 0);
3346                 break;
3347         case SNK_STARTUP:
3348                 opmode =  tcpm_get_pwr_opmode(port->polarity ?
3349                                               port->cc2 : port->cc1);
3350                 typec_set_pwr_opmode(port->typec_port, opmode);
3351                 port->pwr_opmode = TYPEC_PWR_MODE_USB;
3352                 port->negotiated_rev = PD_MAX_REV;
3353                 port->message_id = 0;
3354                 port->rx_msgid = -1;
3355                 port->explicit_contract = false;
3356                 tcpm_set_state(port, SNK_DISCOVERY, 0);
3357                 break;
3358         case SNK_DISCOVERY:
3359                 if (port->vbus_present) {
3360                         tcpm_set_current_limit(port,
3361                                                tcpm_get_current_limit(port),
3362                                                5000);
3363                         tcpm_set_charge(port, true);
3364                         tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
3365                         break;
3366                 }
3367                 /*
3368                  * For DRP, timeouts differ. Also, handling is supposed to be
3369                  * different and much more complex (dead battery detection;
3370                  * see USB power delivery specification, section 8.3.3.6.1.5.1).
3371                  */
3372                 tcpm_set_state(port, hard_reset_state(port),
3373                                port->port_type == TYPEC_PORT_DRP ?
3374                                         PD_T_DB_DETECT : PD_T_NO_RESPONSE);
3375                 break;
3376         case SNK_DISCOVERY_DEBOUNCE:
3377                 tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE_DONE,
3378                                PD_T_CC_DEBOUNCE);
3379                 break;
3380         case SNK_DISCOVERY_DEBOUNCE_DONE:
3381                 if (!tcpm_port_is_disconnected(port) &&
3382                     tcpm_port_is_sink(port) &&
3383                     ktime_after(port->delayed_runtime, ktime_get())) {
3384                         tcpm_set_state(port, SNK_DISCOVERY,
3385                                        ktime_to_ms(ktime_sub(port->delayed_runtime, ktime_get())));
3386                         break;
3387                 }
3388                 tcpm_set_state(port, unattached_state(port), 0);
3389                 break;
3390         case SNK_WAIT_CAPABILITIES:
3391                 ret = port->tcpc->set_pd_rx(port->tcpc, true);
3392                 if (ret < 0) {
3393                         tcpm_set_state(port, SNK_READY, 0);
3394                         break;
3395                 }
3396                 /*
3397                  * If VBUS has never been low, and we time out waiting
3398                  * for source cap, try a soft reset first, in case we
3399                  * were already in a stable contract before this boot.
3400                  * Do this only once.
3401                  */
3402                 if (port->vbus_never_low) {
3403                         port->vbus_never_low = false;
3404                         tcpm_set_state(port, SOFT_RESET_SEND,
3405                                        PD_T_SINK_WAIT_CAP);
3406                 } else {
3407                         tcpm_set_state(port, hard_reset_state(port),
3408                                        PD_T_SINK_WAIT_CAP);
3409                 }
3410                 break;
3411         case SNK_NEGOTIATE_CAPABILITIES:
3412                 port->pd_capable = true;
3413                 port->hard_reset_count = 0;
3414                 ret = tcpm_pd_send_request(port);
3415                 if (ret < 0) {
3416                         /* Let the Source send capabilities again. */
3417                         tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
3418                 } else {
3419                         tcpm_set_state_cond(port, hard_reset_state(port),
3420                                             PD_T_SENDER_RESPONSE);
3421                 }
3422                 break;
3423         case SNK_NEGOTIATE_PPS_CAPABILITIES:
3424                 ret = tcpm_pd_send_pps_request(port);
3425                 if (ret < 0) {
3426                         port->pps_status = ret;
3427                         /*
3428                          * If this was called due to updates to sink
3429                          * capabilities, and pps is no longer valid, we should
3430                          * safely fall back to a standard PDO.
3431                          */
3432                         if (port->update_sink_caps)
3433                                 tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
3434                         else
3435                                 tcpm_set_state(port, SNK_READY, 0);
3436                 } else {
3437                         tcpm_set_state_cond(port, hard_reset_state(port),
3438                                             PD_T_SENDER_RESPONSE);
3439                 }
3440                 break;
3441         case SNK_TRANSITION_SINK:
3442         case SNK_TRANSITION_SINK_VBUS:
3443                 tcpm_set_state(port, hard_reset_state(port),
3444                                PD_T_PS_TRANSITION);
3445                 break;
3446         case SNK_READY:
3447                 port->try_snk_count = 0;
3448                 port->update_sink_caps = false;
3449                 if (port->explicit_contract) {
3450                         typec_set_pwr_opmode(port->typec_port,
3451                                              TYPEC_PWR_MODE_PD);
3452                         port->pwr_opmode = TYPEC_PWR_MODE_PD;
3453                 }
3454
3455                 tcpm_swap_complete(port, 0);
3456                 tcpm_typec_connect(port);
3457                 tcpm_check_send_discover(port);
3458                 mod_enable_frs_delayed_work(port, 0);
3459                 tcpm_pps_complete(port, port->pps_status);
3460                 power_supply_changed(port->psy);
3461                 break;
3462
3463         /* Accessory states */
3464         case ACC_UNATTACHED:
3465                 tcpm_acc_detach(port);
3466                 tcpm_set_state(port, SRC_UNATTACHED, 0);
3467                 break;
3468         case DEBUG_ACC_ATTACHED:
3469         case AUDIO_ACC_ATTACHED:
3470                 ret = tcpm_acc_attach(port);
3471                 if (ret < 0)
3472                         tcpm_set_state(port, ACC_UNATTACHED, 0);
3473                 break;
3474         case AUDIO_ACC_DEBOUNCE:
3475                 tcpm_set_state(port, ACC_UNATTACHED, PD_T_CC_DEBOUNCE);
3476                 break;
3477
3478         /* Hard_Reset states */
3479         case HARD_RESET_SEND:
3480                 tcpm_pd_transmit(port, TCPC_TX_HARD_RESET, NULL);
3481                 tcpm_set_state(port, HARD_RESET_START, 0);
3482                 break;
3483         case HARD_RESET_START:
3484                 port->sink_cap_done = false;
3485                 if (port->tcpc->enable_frs)
3486                         port->tcpc->enable_frs(port->tcpc, false);
3487                 port->hard_reset_count++;
3488                 port->tcpc->set_pd_rx(port->tcpc, false);
3489                 tcpm_unregister_altmodes(port);
3490                 port->nr_sink_caps = 0;
3491                 port->send_discover = true;
3492                 if (port->pwr_role == TYPEC_SOURCE)
3493                         tcpm_set_state(port, SRC_HARD_RESET_VBUS_OFF,
3494                                        PD_T_PS_HARD_RESET);
3495                 else
3496                         tcpm_set_state(port, SNK_HARD_RESET_SINK_OFF, 0);
3497                 break;
3498         case SRC_HARD_RESET_VBUS_OFF:
3499                 /*
3500                  * 7.1.5 Response to Hard Resets
3501                  * Hard Reset Signaling indicates a communication failure has occurred and the
3502                  * Source Shall stop driving VCONN, Shall remove Rp from the VCONN pin and Shall
3503                  * drive VBUS to vSafe0V as shown in Figure 7-9.
3504                  */
3505                 tcpm_set_vconn(port, false);
3506                 tcpm_set_vbus(port, false);
3507                 tcpm_set_roles(port, port->self_powered, TYPEC_SOURCE,
3508                                tcpm_data_role_for_source(port));
3509                 /*
3510                  * If tcpc fails to notify vbus off, TCPM will wait for PD_T_SAFE_0V +
3511                  * PD_T_SRC_RECOVER before turning vbus back on.
3512                  * From Table 7-12 Sequence Description for a Source Initiated Hard Reset:
3513                  * 4. Policy Engine waits tPSHardReset after sending Hard Reset Signaling and then
3514                  * tells the Device Policy Manager to instruct the power supply to perform a
3515                  * Hard Reset. The transition to vSafe0V Shall occur within tSafe0V (t2).
3516                  * 5. After tSrcRecover the Source applies power to VBUS in an attempt to
3517                  * re-establish communication with the Sink and resume USB Default Operation.
3518                  * The transition to vSafe5V Shall occur within tSrcTurnOn(t4).
3519                  */
3520                 tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SAFE_0V + PD_T_SRC_RECOVER);
3521                 break;
3522         case SRC_HARD_RESET_VBUS_ON:
3523                 tcpm_set_vconn(port, true);
3524                 tcpm_set_vbus(port, true);
3525                 port->tcpc->set_pd_rx(port->tcpc, true);
3526                 tcpm_set_attached_state(port, true);
3527                 tcpm_set_state(port, SRC_UNATTACHED, PD_T_PS_SOURCE_ON);
3528                 break;
3529         case SNK_HARD_RESET_SINK_OFF:
3530                 memset(&port->pps_data, 0, sizeof(port->pps_data));
3531                 tcpm_set_vconn(port, false);
3532                 if (port->pd_capable)
3533                         tcpm_set_charge(port, false);
3534                 tcpm_set_roles(port, port->self_powered, TYPEC_SINK,
3535                                tcpm_data_role_for_sink(port));
3536                 /*
3537                  * VBUS may or may not toggle, depending on the adapter.
3538                  * If it doesn't toggle, transition to SNK_HARD_RESET_SINK_ON
3539                  * directly after timeout.
3540                  */
3541                 tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, PD_T_SAFE_0V);
3542                 break;
3543         case SNK_HARD_RESET_WAIT_VBUS:
3544                 /* Assume we're disconnected if VBUS doesn't come back. */
3545                 tcpm_set_state(port, SNK_UNATTACHED,
3546                                PD_T_SRC_RECOVER_MAX + PD_T_SRC_TURN_ON);
3547                 break;
3548         case SNK_HARD_RESET_SINK_ON:
3549                 /* Note: There is no guarantee that VBUS is on in this state */
3550                 /*
3551                  * XXX:
3552                  * The specification suggests that dual mode ports in sink
3553                  * mode should transition to state PE_SRC_Transition_to_default.
3554                  * See USB power delivery specification chapter 8.3.3.6.1.3.
3555                  * This would mean to to
3556                  * - turn off VCONN, reset power supply
3557                  * - request hardware reset
3558                  * - turn on VCONN
3559                  * - Transition to state PE_Src_Startup
3560                  * SNK only ports shall transition to state Snk_Startup
3561                  * (see chapter 8.3.3.3.8).
3562                  * Similar, dual-mode ports in source mode should transition
3563                  * to PE_SNK_Transition_to_default.
3564                  */
3565                 if (port->pd_capable) {
3566                         tcpm_set_current_limit(port,
3567                                                tcpm_get_current_limit(port),
3568                                                5000);
3569                         tcpm_set_charge(port, true);
3570                 }
3571                 tcpm_set_attached_state(port, true);
3572                 tcpm_set_state(port, SNK_STARTUP, 0);
3573                 break;
3574
3575         /* Soft_Reset states */
3576         case SOFT_RESET:
3577                 port->message_id = 0;
3578                 port->rx_msgid = -1;
3579                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
3580                 if (port->pwr_role == TYPEC_SOURCE)
3581                         tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
3582                 else
3583                         tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
3584                 break;
3585         case SOFT_RESET_SEND:
3586                 port->message_id = 0;
3587                 port->rx_msgid = -1;
3588                 if (tcpm_pd_send_control(port, PD_CTRL_SOFT_RESET))
3589                         tcpm_set_state_cond(port, hard_reset_state(port), 0);
3590                 else
3591                         tcpm_set_state_cond(port, hard_reset_state(port),
3592                                             PD_T_SENDER_RESPONSE);
3593                 break;
3594
3595         /* DR_Swap states */
3596         case DR_SWAP_SEND:
3597                 tcpm_pd_send_control(port, PD_CTRL_DR_SWAP);
3598                 tcpm_set_state_cond(port, DR_SWAP_SEND_TIMEOUT,
3599                                     PD_T_SENDER_RESPONSE);
3600                 break;
3601         case DR_SWAP_ACCEPT:
3602                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
3603                 tcpm_set_state_cond(port, DR_SWAP_CHANGE_DR, 0);
3604                 break;
3605         case DR_SWAP_SEND_TIMEOUT:
3606                 tcpm_swap_complete(port, -ETIMEDOUT);
3607                 tcpm_set_state(port, ready_state(port), 0);
3608                 break;
3609         case DR_SWAP_CHANGE_DR:
3610                 if (port->data_role == TYPEC_HOST) {
3611                         tcpm_unregister_altmodes(port);
3612                         tcpm_set_roles(port, true, port->pwr_role,
3613                                        TYPEC_DEVICE);
3614                 } else {
3615                         tcpm_set_roles(port, true, port->pwr_role,
3616                                        TYPEC_HOST);
3617                         port->send_discover = true;
3618                 }
3619                 tcpm_set_state(port, ready_state(port), 0);
3620                 break;
3621
3622         case FR_SWAP_SEND:
3623                 if (tcpm_pd_send_control(port, PD_CTRL_FR_SWAP)) {
3624                         tcpm_set_state(port, ERROR_RECOVERY, 0);
3625                         break;
3626                 }
3627                 tcpm_set_state_cond(port, FR_SWAP_SEND_TIMEOUT, PD_T_SENDER_RESPONSE);
3628                 break;
3629         case FR_SWAP_SEND_TIMEOUT:
3630                 tcpm_set_state(port, ERROR_RECOVERY, 0);
3631                 break;
3632         case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
3633                 tcpm_set_state(port, ERROR_RECOVERY, PD_T_PS_SOURCE_OFF);
3634                 break;
3635         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
3636                 if (port->vbus_source)
3637                         tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
3638                 else
3639                         tcpm_set_state(port, ERROR_RECOVERY, PD_T_RECEIVER_RESPONSE);
3640                 break;
3641         case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
3642                 tcpm_set_pwr_role(port, TYPEC_SOURCE);
3643                 if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY)) {
3644                         tcpm_set_state(port, ERROR_RECOVERY, 0);
3645                         break;
3646                 }
3647                 tcpm_set_cc(port, tcpm_rp_cc(port));
3648                 tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
3649                 break;
3650
3651         /* PR_Swap states */
3652         case PR_SWAP_ACCEPT:
3653                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
3654                 tcpm_set_state(port, PR_SWAP_START, 0);
3655                 break;
3656         case PR_SWAP_SEND:
3657                 tcpm_pd_send_control(port, PD_CTRL_PR_SWAP);
3658                 tcpm_set_state_cond(port, PR_SWAP_SEND_TIMEOUT,
3659                                     PD_T_SENDER_RESPONSE);
3660                 break;
3661         case PR_SWAP_SEND_TIMEOUT:
3662                 tcpm_swap_complete(port, -ETIMEDOUT);
3663                 tcpm_set_state(port, ready_state(port), 0);
3664                 break;
3665         case PR_SWAP_START:
3666                 if (port->pwr_role == TYPEC_SOURCE)
3667                         tcpm_set_state(port, PR_SWAP_SRC_SNK_TRANSITION_OFF,
3668                                        PD_T_SRC_TRANSITION);
3669                 else
3670                         tcpm_set_state(port, PR_SWAP_SNK_SRC_SINK_OFF, 0);
3671                 break;
3672         case PR_SWAP_SRC_SNK_TRANSITION_OFF:
3673                 tcpm_set_vbus(port, false);
3674                 port->explicit_contract = false;
3675                 /* allow time for Vbus discharge, must be < tSrcSwapStdby */
3676                 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF,
3677                                PD_T_SRCSWAPSTDBY);
3678                 break;
3679         case PR_SWAP_SRC_SNK_SOURCE_OFF:
3680                 tcpm_set_cc(port, TYPEC_CC_RD);
3681                 /* allow CC debounce */
3682                 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED,
3683                                PD_T_CC_DEBOUNCE);
3684                 break;
3685         case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
3686                 /*
3687                  * USB-PD standard, 6.2.1.4, Port Power Role:
3688                  * "During the Power Role Swap Sequence, for the initial Source
3689                  * Port, the Port Power Role field shall be set to Sink in the
3690                  * PS_RDY Message indicating that the initial Source’s power
3691                  * supply is turned off"
3692                  */
3693                 tcpm_set_pwr_role(port, TYPEC_SINK);
3694                 if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY)) {
3695                         tcpm_set_state(port, ERROR_RECOVERY, 0);
3696                         break;
3697                 }
3698                 tcpm_set_state_cond(port, SNK_UNATTACHED, PD_T_PS_SOURCE_ON);
3699                 break;
3700         case PR_SWAP_SRC_SNK_SINK_ON:
3701                 tcpm_set_state(port, SNK_STARTUP, 0);
3702                 break;
3703         case PR_SWAP_SNK_SRC_SINK_OFF:
3704                 tcpm_set_charge(port, false);
3705                 tcpm_set_state(port, hard_reset_state(port),
3706                                PD_T_PS_SOURCE_OFF);
3707                 break;
3708         case PR_SWAP_SNK_SRC_SOURCE_ON:
3709                 tcpm_set_cc(port, tcpm_rp_cc(port));
3710                 tcpm_set_vbus(port, true);
3711                 /*
3712                  * allow time VBUS ramp-up, must be < tNewSrc
3713                  * Also, this window overlaps with CC debounce as well.
3714                  * So, Wait for the max of two which is PD_T_NEWSRC
3715                  */
3716                 tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP,
3717                                PD_T_NEWSRC);
3718                 break;
3719         case PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP:
3720                 /*
3721                  * USB PD standard, 6.2.1.4:
3722                  * "Subsequent Messages initiated by the Policy Engine,
3723                  * such as the PS_RDY Message sent to indicate that Vbus
3724                  * is ready, will have the Port Power Role field set to
3725                  * Source."
3726                  */
3727                 tcpm_set_pwr_role(port, TYPEC_SOURCE);
3728                 tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
3729                 tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
3730                 break;
3731
3732         case VCONN_SWAP_ACCEPT:
3733                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
3734                 tcpm_set_state(port, VCONN_SWAP_START, 0);
3735                 break;
3736         case VCONN_SWAP_SEND:
3737                 tcpm_pd_send_control(port, PD_CTRL_VCONN_SWAP);
3738                 tcpm_set_state(port, VCONN_SWAP_SEND_TIMEOUT,
3739                                PD_T_SENDER_RESPONSE);
3740                 break;
3741         case VCONN_SWAP_SEND_TIMEOUT:
3742                 tcpm_swap_complete(port, -ETIMEDOUT);
3743                 tcpm_set_state(port, ready_state(port), 0);
3744                 break;
3745         case VCONN_SWAP_START:
3746                 if (port->vconn_role == TYPEC_SOURCE)
3747                         tcpm_set_state(port, VCONN_SWAP_WAIT_FOR_VCONN, 0);
3748                 else
3749                         tcpm_set_state(port, VCONN_SWAP_TURN_ON_VCONN, 0);
3750                 break;
3751         case VCONN_SWAP_WAIT_FOR_VCONN:
3752                 tcpm_set_state(port, hard_reset_state(port),
3753                                PD_T_VCONN_SOURCE_ON);
3754                 break;
3755         case VCONN_SWAP_TURN_ON_VCONN:
3756                 tcpm_set_vconn(port, true);
3757                 tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
3758                 tcpm_set_state(port, ready_state(port), 0);
3759                 break;
3760         case VCONN_SWAP_TURN_OFF_VCONN:
3761                 tcpm_set_vconn(port, false);
3762                 tcpm_set_state(port, ready_state(port), 0);
3763                 break;
3764
3765         case DR_SWAP_CANCEL:
3766         case PR_SWAP_CANCEL:
3767         case VCONN_SWAP_CANCEL:
3768                 tcpm_swap_complete(port, port->swap_status);
3769                 if (port->pwr_role == TYPEC_SOURCE)
3770                         tcpm_set_state(port, SRC_READY, 0);
3771                 else
3772                         tcpm_set_state(port, SNK_READY, 0);
3773                 break;
3774         case FR_SWAP_CANCEL:
3775                 if (port->pwr_role == TYPEC_SOURCE)
3776                         tcpm_set_state(port, SRC_READY, 0);
3777                 else
3778                         tcpm_set_state(port, SNK_READY, 0);
3779                 break;
3780
3781         case BIST_RX:
3782                 switch (BDO_MODE_MASK(port->bist_request)) {
3783                 case BDO_MODE_CARRIER2:
3784                         tcpm_pd_transmit(port, TCPC_TX_BIST_MODE_2, NULL);
3785                         tcpm_set_state(port, unattached_state(port),
3786                                        PD_T_BIST_CONT_MODE);
3787                         break;
3788                 case BDO_MODE_TESTDATA:
3789                         if (port->tcpc->set_bist_data) {
3790                                 tcpm_log(port, "Enable BIST MODE TESTDATA");
3791                                 port->tcpc->set_bist_data(port->tcpc, true);
3792                         }
3793                         break;
3794                 default:
3795                         break;
3796                 }
3797                 break;
3798         case GET_STATUS_SEND:
3799                 tcpm_pd_send_control(port, PD_CTRL_GET_STATUS);
3800                 tcpm_set_state(port, GET_STATUS_SEND_TIMEOUT,
3801                                PD_T_SENDER_RESPONSE);
3802                 break;
3803         case GET_STATUS_SEND_TIMEOUT:
3804                 tcpm_set_state(port, ready_state(port), 0);
3805                 break;
3806         case GET_PPS_STATUS_SEND:
3807                 tcpm_pd_send_control(port, PD_CTRL_GET_PPS_STATUS);
3808                 tcpm_set_state(port, GET_PPS_STATUS_SEND_TIMEOUT,
3809                                PD_T_SENDER_RESPONSE);
3810                 break;
3811         case GET_PPS_STATUS_SEND_TIMEOUT:
3812                 tcpm_set_state(port, ready_state(port), 0);
3813                 break;
3814         case GET_SINK_CAP:
3815                 tcpm_pd_send_control(port, PD_CTRL_GET_SINK_CAP);
3816                 tcpm_set_state(port, GET_SINK_CAP_TIMEOUT, PD_T_SENDER_RESPONSE);
3817                 break;
3818         case GET_SINK_CAP_TIMEOUT:
3819                 port->sink_cap_done = true;
3820                 tcpm_set_state(port, ready_state(port), 0);
3821                 break;
3822         case ERROR_RECOVERY:
3823                 tcpm_swap_complete(port, -EPROTO);
3824                 tcpm_pps_complete(port, -EPROTO);
3825                 tcpm_set_state(port, PORT_RESET, 0);
3826                 break;
3827         case PORT_RESET:
3828                 tcpm_reset_port(port);
3829                 tcpm_set_cc(port, TYPEC_CC_OPEN);
3830                 tcpm_set_state(port, PORT_RESET_WAIT_OFF,
3831                                PD_T_ERROR_RECOVERY);
3832                 break;
3833         case PORT_RESET_WAIT_OFF:
3834                 tcpm_set_state(port,
3835                                tcpm_default_state(port),
3836                                port->vbus_present ? PD_T_PS_SOURCE_OFF : 0);
3837                 break;
3838         default:
3839                 WARN(1, "Unexpected port state %d\n", port->state);
3840                 break;
3841         }
3842 }
3843
3844 static void tcpm_state_machine_work(struct kthread_work *work)
3845 {
3846         struct tcpm_port *port = container_of(work, struct tcpm_port, state_machine);
3847         enum tcpm_state prev_state;
3848
3849         mutex_lock(&port->lock);
3850         port->state_machine_running = true;
3851
3852         if (port->queued_message && tcpm_send_queued_message(port))
3853                 goto done;
3854
3855         /* If we were queued due to a delayed state change, update it now */
3856         if (port->delayed_state) {
3857                 tcpm_log(port, "state change %s -> %s [delayed %ld ms]",
3858                          tcpm_states[port->state],
3859                          tcpm_states[port->delayed_state], port->delay_ms);
3860                 port->prev_state = port->state;
3861                 port->state = port->delayed_state;
3862                 port->delayed_state = INVALID_STATE;
3863         }
3864
3865         /*
3866          * Continue running as long as we have (non-delayed) state changes
3867          * to make.
3868          */
3869         do {
3870                 prev_state = port->state;
3871                 run_state_machine(port);
3872                 if (port->queued_message)
3873                         tcpm_send_queued_message(port);
3874         } while (port->state != prev_state && !port->delayed_state);
3875
3876 done:
3877         port->state_machine_running = false;
3878         mutex_unlock(&port->lock);
3879 }
3880
3881 static void _tcpm_cc_change(struct tcpm_port *port, enum typec_cc_status cc1,
3882                             enum typec_cc_status cc2)
3883 {
3884         enum typec_cc_status old_cc1, old_cc2;
3885         enum tcpm_state new_state;
3886
3887         old_cc1 = port->cc1;
3888         old_cc2 = port->cc2;
3889         port->cc1 = cc1;
3890         port->cc2 = cc2;
3891
3892         tcpm_log_force(port,
3893                        "CC1: %u -> %u, CC2: %u -> %u [state %s, polarity %d, %s]",
3894                        old_cc1, cc1, old_cc2, cc2, tcpm_states[port->state],
3895                        port->polarity,
3896                        tcpm_port_is_disconnected(port) ? "disconnected"
3897                                                        : "connected");
3898
3899         switch (port->state) {
3900         case TOGGLING:
3901                 if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
3902                     tcpm_port_is_source(port))
3903                         tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
3904                 else if (tcpm_port_is_sink(port))
3905                         tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
3906                 break;
3907         case SRC_UNATTACHED:
3908         case ACC_UNATTACHED:
3909                 if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
3910                     tcpm_port_is_source(port))
3911                         tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
3912                 break;
3913         case SRC_ATTACH_WAIT:
3914                 if (tcpm_port_is_disconnected(port) ||
3915                     tcpm_port_is_audio_detached(port))
3916                         tcpm_set_state(port, SRC_UNATTACHED, 0);
3917                 else if (cc1 != old_cc1 || cc2 != old_cc2)
3918                         tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
3919                 break;
3920         case SRC_ATTACHED:
3921         case SRC_STARTUP:
3922         case SRC_SEND_CAPABILITIES:
3923         case SRC_READY:
3924                 if (tcpm_port_is_disconnected(port) ||
3925                     !tcpm_port_is_source(port)) {
3926                         if (port->port_type == TYPEC_PORT_SRC)
3927                                 tcpm_set_state(port, SRC_UNATTACHED, 0);
3928                         else
3929                                 tcpm_set_state(port, SNK_UNATTACHED, 0);
3930                 }
3931                 break;
3932         case SNK_UNATTACHED:
3933                 if (tcpm_port_is_sink(port))
3934                         tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
3935                 break;
3936         case SNK_ATTACH_WAIT:
3937                 if ((port->cc1 == TYPEC_CC_OPEN &&
3938                      port->cc2 != TYPEC_CC_OPEN) ||
3939                     (port->cc1 != TYPEC_CC_OPEN &&
3940                      port->cc2 == TYPEC_CC_OPEN))
3941                         new_state = SNK_DEBOUNCED;
3942                 else if (tcpm_port_is_disconnected(port))
3943                         new_state = SNK_UNATTACHED;
3944                 else
3945                         break;
3946                 if (new_state != port->delayed_state)
3947                         tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
3948                 break;
3949         case SNK_DEBOUNCED:
3950                 if (tcpm_port_is_disconnected(port))
3951                         new_state = SNK_UNATTACHED;
3952                 else if (port->vbus_present)
3953                         new_state = tcpm_try_src(port) ? SRC_TRY : SNK_ATTACHED;
3954                 else
3955                         new_state = SNK_UNATTACHED;
3956                 if (new_state != port->delayed_state)
3957                         tcpm_set_state(port, SNK_DEBOUNCED, 0);
3958                 break;
3959         case SNK_READY:
3960                 if (tcpm_port_is_disconnected(port))
3961                         tcpm_set_state(port, unattached_state(port), 0);
3962                 else if (!port->pd_capable &&
3963                          (cc1 != old_cc1 || cc2 != old_cc2))
3964                         tcpm_set_current_limit(port,
3965                                                tcpm_get_current_limit(port),
3966                                                5000);
3967                 break;
3968
3969         case AUDIO_ACC_ATTACHED:
3970                 if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
3971                         tcpm_set_state(port, AUDIO_ACC_DEBOUNCE, 0);
3972                 break;
3973         case AUDIO_ACC_DEBOUNCE:
3974                 if (tcpm_port_is_audio(port))
3975                         tcpm_set_state(port, AUDIO_ACC_ATTACHED, 0);
3976                 break;
3977
3978         case DEBUG_ACC_ATTACHED:
3979                 if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
3980                         tcpm_set_state(port, ACC_UNATTACHED, 0);
3981                 break;
3982
3983         case SNK_TRY:
3984                 /* Do nothing, waiting for timeout */
3985                 break;
3986
3987         case SNK_DISCOVERY:
3988                 /* CC line is unstable, wait for debounce */
3989                 if (tcpm_port_is_disconnected(port))
3990                         tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE, 0);
3991                 break;
3992         case SNK_DISCOVERY_DEBOUNCE:
3993                 break;
3994
3995         case SRC_TRYWAIT:
3996                 /* Hand over to state machine if needed */
3997                 if (!port->vbus_present && tcpm_port_is_source(port))
3998                         tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
3999                 break;
4000         case SRC_TRYWAIT_DEBOUNCE:
4001                 if (port->vbus_present || !tcpm_port_is_source(port))
4002                         tcpm_set_state(port, SRC_TRYWAIT, 0);
4003                 break;
4004         case SNK_TRY_WAIT_DEBOUNCE:
4005                 if (!tcpm_port_is_sink(port)) {
4006                         port->max_wait = 0;
4007                         tcpm_set_state(port, SRC_TRYWAIT, 0);
4008                 }
4009                 break;
4010         case SRC_TRY_WAIT:
4011                 if (tcpm_port_is_source(port))
4012                         tcpm_set_state(port, SRC_TRY_DEBOUNCE, 0);
4013                 break;
4014         case SRC_TRY_DEBOUNCE:
4015                 tcpm_set_state(port, SRC_TRY_WAIT, 0);
4016                 break;
4017         case SNK_TRYWAIT_DEBOUNCE:
4018                 if (tcpm_port_is_sink(port))
4019                         tcpm_set_state(port, SNK_TRYWAIT_VBUS, 0);
4020                 break;
4021         case SNK_TRYWAIT_VBUS:
4022                 if (!tcpm_port_is_sink(port))
4023                         tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
4024                 break;
4025         case SNK_TRYWAIT:
4026                 /* Do nothing, waiting for tCCDebounce */
4027                 break;
4028         case PR_SWAP_SNK_SRC_SINK_OFF:
4029         case PR_SWAP_SRC_SNK_TRANSITION_OFF:
4030         case PR_SWAP_SRC_SNK_SOURCE_OFF:
4031         case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
4032         case PR_SWAP_SNK_SRC_SOURCE_ON:
4033                 /*
4034                  * CC state change is expected in PR_SWAP
4035                  * Ignore it.
4036                  */
4037                 break;
4038         case FR_SWAP_SEND:
4039         case FR_SWAP_SEND_TIMEOUT:
4040         case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
4041         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
4042         case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
4043                 /* Do nothing, CC change expected */
4044                 break;
4045
4046         case PORT_RESET:
4047         case PORT_RESET_WAIT_OFF:
4048                 /*
4049                  * State set back to default mode once the timer completes.
4050                  * Ignore CC changes here.
4051                  */
4052                 break;
4053
4054         default:
4055                 if (tcpm_port_is_disconnected(port))
4056                         tcpm_set_state(port, unattached_state(port), 0);
4057                 break;
4058         }
4059 }
4060
4061 static void _tcpm_pd_vbus_on(struct tcpm_port *port)
4062 {
4063         tcpm_log_force(port, "VBUS on");
4064         port->vbus_present = true;
4065         switch (port->state) {
4066         case SNK_TRANSITION_SINK_VBUS:
4067                 port->explicit_contract = true;
4068                 tcpm_set_state(port, SNK_READY, 0);
4069                 break;
4070         case SNK_DISCOVERY:
4071                 tcpm_set_state(port, SNK_DISCOVERY, 0);
4072                 break;
4073
4074         case SNK_DEBOUNCED:
4075                 tcpm_set_state(port, tcpm_try_src(port) ? SRC_TRY
4076                                                         : SNK_ATTACHED,
4077                                        0);
4078                 break;
4079         case SNK_HARD_RESET_WAIT_VBUS:
4080                 tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, 0);
4081                 break;
4082         case SRC_ATTACHED:
4083                 tcpm_set_state(port, SRC_STARTUP, 0);
4084                 break;
4085         case SRC_HARD_RESET_VBUS_ON:
4086                 tcpm_set_state(port, SRC_STARTUP, 0);
4087                 break;
4088
4089         case SNK_TRY:
4090                 /* Do nothing, waiting for timeout */
4091                 break;
4092         case SRC_TRYWAIT:
4093                 /* Do nothing, Waiting for Rd to be detected */
4094                 break;
4095         case SRC_TRYWAIT_DEBOUNCE:
4096                 tcpm_set_state(port, SRC_TRYWAIT, 0);
4097                 break;
4098         case SNK_TRY_WAIT_DEBOUNCE:
4099                 /* Do nothing, waiting for PD_DEBOUNCE to do be done */
4100                 break;
4101         case SNK_TRYWAIT:
4102                 /* Do nothing, waiting for tCCDebounce */
4103                 break;
4104         case SNK_TRYWAIT_VBUS:
4105                 if (tcpm_port_is_sink(port))
4106                         tcpm_set_state(port, SNK_ATTACHED, 0);
4107                 break;
4108         case SNK_TRYWAIT_DEBOUNCE:
4109                 /* Do nothing, waiting for Rp */
4110                 break;
4111         case SRC_TRY_WAIT:
4112         case SRC_TRY_DEBOUNCE:
4113                 /* Do nothing, waiting for sink detection */
4114                 break;
4115         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
4116                 tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
4117                 break;
4118
4119         case PORT_RESET:
4120         case PORT_RESET_WAIT_OFF:
4121                 /*
4122                  * State set back to default mode once the timer completes.
4123                  * Ignore vbus changes here.
4124                  */
4125                 break;
4126
4127         default:
4128                 break;
4129         }
4130 }
4131
4132 static void _tcpm_pd_vbus_off(struct tcpm_port *port)
4133 {
4134         tcpm_log_force(port, "VBUS off");
4135         port->vbus_present = false;
4136         port->vbus_never_low = false;
4137         switch (port->state) {
4138         case SNK_HARD_RESET_SINK_OFF:
4139                 tcpm_set_state(port, SNK_HARD_RESET_WAIT_VBUS, 0);
4140                 break;
4141         case SRC_HARD_RESET_VBUS_OFF:
4142                 /*
4143                  * After establishing the vSafe0V voltage condition on VBUS, the Source Shall wait
4144                  * tSrcRecover before re-applying VCONN and restoring VBUS to vSafe5V.
4145                  */
4146                 tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SRC_RECOVER);
4147                 break;
4148         case HARD_RESET_SEND:
4149                 break;
4150
4151         case SNK_TRY:
4152                 /* Do nothing, waiting for timeout */
4153                 break;
4154         case SRC_TRYWAIT:
4155                 /* Hand over to state machine if needed */
4156                 if (tcpm_port_is_source(port))
4157                         tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
4158                 break;
4159         case SNK_TRY_WAIT_DEBOUNCE:
4160                 /* Do nothing, waiting for PD_DEBOUNCE to do be done */
4161                 break;
4162         case SNK_TRYWAIT:
4163         case SNK_TRYWAIT_VBUS:
4164         case SNK_TRYWAIT_DEBOUNCE:
4165                 break;
4166         case SNK_ATTACH_WAIT:
4167         case SNK_DEBOUNCED:
4168                 /* Do nothing, as TCPM is still waiting for vbus to reaach VSAFE5V to connect */
4169                 break;
4170
4171         case SNK_NEGOTIATE_CAPABILITIES:
4172                 break;
4173
4174         case PR_SWAP_SRC_SNK_TRANSITION_OFF:
4175                 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF, 0);
4176                 break;
4177
4178         case PR_SWAP_SNK_SRC_SINK_OFF:
4179                 /* Do nothing, expected */
4180                 break;
4181
4182         case PORT_RESET_WAIT_OFF:
4183                 tcpm_set_state(port, tcpm_default_state(port), 0);
4184                 break;
4185
4186         case SRC_TRY_WAIT:
4187         case SRC_TRY_DEBOUNCE:
4188                 /* Do nothing, waiting for sink detection */
4189                 break;
4190
4191         case PORT_RESET:
4192                 /*
4193                  * State set back to default mode once the timer completes.
4194                  * Ignore vbus changes here.
4195                  */
4196                 break;
4197
4198         case FR_SWAP_SEND:
4199         case FR_SWAP_SEND_TIMEOUT:
4200         case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
4201         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
4202         case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
4203                 /* Do nothing, vbus drop expected */
4204                 break;
4205
4206         default:
4207                 if (port->pwr_role == TYPEC_SINK &&
4208                     port->attached)
4209                         tcpm_set_state(port, SNK_UNATTACHED, 0);
4210                 break;
4211         }
4212 }
4213
4214 static void _tcpm_pd_hard_reset(struct tcpm_port *port)
4215 {
4216         tcpm_log_force(port, "Received hard reset");
4217         if (port->bist_request == BDO_MODE_TESTDATA && port->tcpc->set_bist_data)
4218                 port->tcpc->set_bist_data(port->tcpc, false);
4219
4220         /*
4221          * If we keep receiving hard reset requests, executing the hard reset
4222          * must have failed. Revert to error recovery if that happens.
4223          */
4224         tcpm_set_state(port,
4225                        port->hard_reset_count < PD_N_HARD_RESET_COUNT ?
4226                                 HARD_RESET_START : ERROR_RECOVERY,
4227                        0);
4228 }
4229
4230 static void tcpm_pd_event_handler(struct kthread_work *work)
4231 {
4232         struct tcpm_port *port = container_of(work, struct tcpm_port,
4233                                               event_work);
4234         u32 events;
4235
4236         mutex_lock(&port->lock);
4237
4238         spin_lock(&port->pd_event_lock);
4239         while (port->pd_events) {
4240                 events = port->pd_events;
4241                 port->pd_events = 0;
4242                 spin_unlock(&port->pd_event_lock);
4243                 if (events & TCPM_RESET_EVENT)
4244                         _tcpm_pd_hard_reset(port);
4245                 if (events & TCPM_VBUS_EVENT) {
4246                         bool vbus;
4247
4248                         vbus = port->tcpc->get_vbus(port->tcpc);
4249                         if (vbus)
4250                                 _tcpm_pd_vbus_on(port);
4251                         else
4252                                 _tcpm_pd_vbus_off(port);
4253                 }
4254                 if (events & TCPM_CC_EVENT) {
4255                         enum typec_cc_status cc1, cc2;
4256
4257                         if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
4258                                 _tcpm_cc_change(port, cc1, cc2);
4259                 }
4260                 if (events & TCPM_FRS_EVENT) {
4261                         if (port->state == SNK_READY)
4262                                 tcpm_set_state(port, FR_SWAP_SEND, 0);
4263                         else
4264                                 tcpm_log(port, "Discarding FRS_SIGNAL! Not in sink ready");
4265                 }
4266                 if (events & TCPM_SOURCING_VBUS) {
4267                         tcpm_log(port, "sourcing vbus");
4268                         /*
4269                          * In fast role swap case TCPC autonomously sources vbus. Set vbus_source
4270                          * true as TCPM wouldn't have called tcpm_set_vbus.
4271                          *
4272                          * When vbus is sourced on the command on TCPM i.e. TCPM called
4273                          * tcpm_set_vbus to source vbus, vbus_source would already be true.
4274                          */
4275                         port->vbus_source = true;
4276                         _tcpm_pd_vbus_on(port);
4277                 }
4278
4279                 spin_lock(&port->pd_event_lock);
4280         }
4281         spin_unlock(&port->pd_event_lock);
4282         mutex_unlock(&port->lock);
4283 }
4284
4285 void tcpm_cc_change(struct tcpm_port *port)
4286 {
4287         spin_lock(&port->pd_event_lock);
4288         port->pd_events |= TCPM_CC_EVENT;
4289         spin_unlock(&port->pd_event_lock);
4290         kthread_queue_work(port->wq, &port->event_work);
4291 }
4292 EXPORT_SYMBOL_GPL(tcpm_cc_change);
4293
4294 void tcpm_vbus_change(struct tcpm_port *port)
4295 {
4296         spin_lock(&port->pd_event_lock);
4297         port->pd_events |= TCPM_VBUS_EVENT;
4298         spin_unlock(&port->pd_event_lock);
4299         kthread_queue_work(port->wq, &port->event_work);
4300 }
4301 EXPORT_SYMBOL_GPL(tcpm_vbus_change);
4302
4303 void tcpm_pd_hard_reset(struct tcpm_port *port)
4304 {
4305         spin_lock(&port->pd_event_lock);
4306         port->pd_events = TCPM_RESET_EVENT;
4307         spin_unlock(&port->pd_event_lock);
4308         kthread_queue_work(port->wq, &port->event_work);
4309 }
4310 EXPORT_SYMBOL_GPL(tcpm_pd_hard_reset);
4311
4312 void tcpm_sink_frs(struct tcpm_port *port)
4313 {
4314         spin_lock(&port->pd_event_lock);
4315         port->pd_events |= TCPM_FRS_EVENT;
4316         spin_unlock(&port->pd_event_lock);
4317         kthread_queue_work(port->wq, &port->event_work);
4318 }
4319 EXPORT_SYMBOL_GPL(tcpm_sink_frs);
4320
4321 void tcpm_sourcing_vbus(struct tcpm_port *port)
4322 {
4323         spin_lock(&port->pd_event_lock);
4324         port->pd_events |= TCPM_SOURCING_VBUS;
4325         spin_unlock(&port->pd_event_lock);
4326         kthread_queue_work(port->wq, &port->event_work);
4327 }
4328 EXPORT_SYMBOL_GPL(tcpm_sourcing_vbus);
4329
4330 static void tcpm_enable_frs_work(struct kthread_work *work)
4331 {
4332         struct tcpm_port *port = container_of(work, struct tcpm_port, enable_frs);
4333
4334         mutex_lock(&port->lock);
4335         /* Not FRS capable */
4336         if (!port->connected || port->port_type != TYPEC_PORT_DRP ||
4337             port->pwr_opmode != TYPEC_PWR_MODE_PD ||
4338             !port->tcpc->enable_frs ||
4339             /* Sink caps queried */
4340             port->sink_cap_done || port->negotiated_rev < PD_REV30)
4341                 goto unlock;
4342
4343         /* Send when the state machine is idle */
4344         if (port->state != SNK_READY || port->vdm_state != VDM_STATE_DONE || port->send_discover)
4345                 goto resched;
4346
4347         tcpm_set_state(port, GET_SINK_CAP, 0);
4348         port->sink_cap_done = true;
4349
4350 resched:
4351         mod_enable_frs_delayed_work(port, GET_SINK_CAP_RETRY_MS);
4352 unlock:
4353         mutex_unlock(&port->lock);
4354 }
4355
4356 static int tcpm_dr_set(struct typec_port *p, enum typec_data_role data)
4357 {
4358         struct tcpm_port *port = typec_get_drvdata(p);
4359         int ret;
4360
4361         mutex_lock(&port->swap_lock);
4362         mutex_lock(&port->lock);
4363
4364         if (port->typec_caps.data != TYPEC_PORT_DRD) {
4365                 ret = -EINVAL;
4366                 goto port_unlock;
4367         }
4368         if (port->state != SRC_READY && port->state != SNK_READY) {
4369                 ret = -EAGAIN;
4370                 goto port_unlock;
4371         }
4372
4373         if (port->data_role == data) {
4374                 ret = 0;
4375                 goto port_unlock;
4376         }
4377
4378         /*
4379          * XXX
4380          * 6.3.9: If an alternate mode is active, a request to swap
4381          * alternate modes shall trigger a port reset.
4382          * Reject data role swap request in this case.
4383          */
4384
4385         if (!port->pd_capable) {
4386                 /*
4387                  * If the partner is not PD capable, reset the port to
4388                  * trigger a role change. This can only work if a preferred
4389                  * role is configured, and if it matches the requested role.
4390                  */
4391                 if (port->try_role == TYPEC_NO_PREFERRED_ROLE ||
4392                     port->try_role == port->pwr_role) {
4393                         ret = -EINVAL;
4394                         goto port_unlock;
4395                 }
4396                 port->non_pd_role_swap = true;
4397                 tcpm_set_state(port, PORT_RESET, 0);
4398         } else {
4399                 tcpm_set_state(port, DR_SWAP_SEND, 0);
4400         }
4401
4402         port->swap_status = 0;
4403         port->swap_pending = true;
4404         reinit_completion(&port->swap_complete);
4405         mutex_unlock(&port->lock);
4406
4407         if (!wait_for_completion_timeout(&port->swap_complete,
4408                                 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
4409                 ret = -ETIMEDOUT;
4410         else
4411                 ret = port->swap_status;
4412
4413         port->non_pd_role_swap = false;
4414         goto swap_unlock;
4415
4416 port_unlock:
4417         mutex_unlock(&port->lock);
4418 swap_unlock:
4419         mutex_unlock(&port->swap_lock);
4420         return ret;
4421 }
4422
4423 static int tcpm_pr_set(struct typec_port *p, enum typec_role role)
4424 {
4425         struct tcpm_port *port = typec_get_drvdata(p);
4426         int ret;
4427
4428         mutex_lock(&port->swap_lock);
4429         mutex_lock(&port->lock);
4430
4431         if (port->port_type != TYPEC_PORT_DRP) {
4432                 ret = -EINVAL;
4433                 goto port_unlock;
4434         }
4435         if (port->state != SRC_READY && port->state != SNK_READY) {
4436                 ret = -EAGAIN;
4437                 goto port_unlock;
4438         }
4439
4440         if (role == port->pwr_role) {
4441                 ret = 0;
4442                 goto port_unlock;
4443         }
4444
4445         port->swap_status = 0;
4446         port->swap_pending = true;
4447         reinit_completion(&port->swap_complete);
4448         tcpm_set_state(port, PR_SWAP_SEND, 0);
4449         mutex_unlock(&port->lock);
4450
4451         if (!wait_for_completion_timeout(&port->swap_complete,
4452                                 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
4453                 ret = -ETIMEDOUT;
4454         else
4455                 ret = port->swap_status;
4456
4457         goto swap_unlock;
4458
4459 port_unlock:
4460         mutex_unlock(&port->lock);
4461 swap_unlock:
4462         mutex_unlock(&port->swap_lock);
4463         return ret;
4464 }
4465
4466 static int tcpm_vconn_set(struct typec_port *p, enum typec_role role)
4467 {
4468         struct tcpm_port *port = typec_get_drvdata(p);
4469         int ret;
4470
4471         mutex_lock(&port->swap_lock);
4472         mutex_lock(&port->lock);
4473
4474         if (port->state != SRC_READY && port->state != SNK_READY) {
4475                 ret = -EAGAIN;
4476                 goto port_unlock;
4477         }
4478
4479         if (role == port->vconn_role) {
4480                 ret = 0;
4481                 goto port_unlock;
4482         }
4483
4484         port->swap_status = 0;
4485         port->swap_pending = true;
4486         reinit_completion(&port->swap_complete);
4487         tcpm_set_state(port, VCONN_SWAP_SEND, 0);
4488         mutex_unlock(&port->lock);
4489
4490         if (!wait_for_completion_timeout(&port->swap_complete,
4491                                 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
4492                 ret = -ETIMEDOUT;
4493         else
4494                 ret = port->swap_status;
4495
4496         goto swap_unlock;
4497
4498 port_unlock:
4499         mutex_unlock(&port->lock);
4500 swap_unlock:
4501         mutex_unlock(&port->swap_lock);
4502         return ret;
4503 }
4504
4505 static int tcpm_try_role(struct typec_port *p, int role)
4506 {
4507         struct tcpm_port *port = typec_get_drvdata(p);
4508         struct tcpc_dev *tcpc = port->tcpc;
4509         int ret = 0;
4510
4511         mutex_lock(&port->lock);
4512         if (tcpc->try_role)
4513                 ret = tcpc->try_role(tcpc, role);
4514         if (!ret)
4515                 port->try_role = role;
4516         port->try_src_count = 0;
4517         port->try_snk_count = 0;
4518         mutex_unlock(&port->lock);
4519
4520         return ret;
4521 }
4522
4523 static int tcpm_pps_set_op_curr(struct tcpm_port *port, u16 req_op_curr)
4524 {
4525         unsigned int target_mw;
4526         int ret;
4527
4528         mutex_lock(&port->swap_lock);
4529         mutex_lock(&port->lock);
4530
4531         if (!port->pps_data.active) {
4532                 ret = -EOPNOTSUPP;
4533                 goto port_unlock;
4534         }
4535
4536         if (port->state != SNK_READY) {
4537                 ret = -EAGAIN;
4538                 goto port_unlock;
4539         }
4540
4541         if (req_op_curr > port->pps_data.max_curr) {
4542                 ret = -EINVAL;
4543                 goto port_unlock;
4544         }
4545
4546         target_mw = (req_op_curr * port->supply_voltage) / 1000;
4547         if (target_mw < port->operating_snk_mw) {
4548                 ret = -EINVAL;
4549                 goto port_unlock;
4550         }
4551
4552         /* Round down operating current to align with PPS valid steps */
4553         req_op_curr = req_op_curr - (req_op_curr % RDO_PROG_CURR_MA_STEP);
4554
4555         reinit_completion(&port->pps_complete);
4556         port->pps_data.req_op_curr = req_op_curr;
4557         port->pps_status = 0;
4558         port->pps_pending = true;
4559         tcpm_set_state(port, SNK_NEGOTIATE_PPS_CAPABILITIES, 0);
4560         mutex_unlock(&port->lock);
4561
4562         if (!wait_for_completion_timeout(&port->pps_complete,
4563                                 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
4564                 ret = -ETIMEDOUT;
4565         else
4566                 ret = port->pps_status;
4567
4568         goto swap_unlock;
4569
4570 port_unlock:
4571         mutex_unlock(&port->lock);
4572 swap_unlock:
4573         mutex_unlock(&port->swap_lock);
4574
4575         return ret;
4576 }
4577
4578 static int tcpm_pps_set_out_volt(struct tcpm_port *port, u16 req_out_volt)
4579 {
4580         unsigned int target_mw;
4581         int ret;
4582
4583         mutex_lock(&port->swap_lock);
4584         mutex_lock(&port->lock);
4585
4586         if (!port->pps_data.active) {
4587                 ret = -EOPNOTSUPP;
4588                 goto port_unlock;
4589         }
4590
4591         if (port->state != SNK_READY) {
4592                 ret = -EAGAIN;
4593                 goto port_unlock;
4594         }
4595
4596         if (req_out_volt < port->pps_data.min_volt ||
4597             req_out_volt > port->pps_data.max_volt) {
4598                 ret = -EINVAL;
4599                 goto port_unlock;
4600         }
4601
4602         target_mw = (port->current_limit * req_out_volt) / 1000;
4603         if (target_mw < port->operating_snk_mw) {
4604                 ret = -EINVAL;
4605                 goto port_unlock;
4606         }
4607
4608         /* Round down output voltage to align with PPS valid steps */
4609         req_out_volt = req_out_volt - (req_out_volt % RDO_PROG_VOLT_MV_STEP);
4610
4611         reinit_completion(&port->pps_complete);
4612         port->pps_data.req_out_volt = req_out_volt;
4613         port->pps_status = 0;
4614         port->pps_pending = true;
4615         tcpm_set_state(port, SNK_NEGOTIATE_PPS_CAPABILITIES, 0);
4616         mutex_unlock(&port->lock);
4617
4618         if (!wait_for_completion_timeout(&port->pps_complete,
4619                                 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
4620                 ret = -ETIMEDOUT;
4621         else
4622                 ret = port->pps_status;
4623
4624         goto swap_unlock;
4625
4626 port_unlock:
4627         mutex_unlock(&port->lock);
4628 swap_unlock:
4629         mutex_unlock(&port->swap_lock);
4630
4631         return ret;
4632 }
4633
4634 static int tcpm_pps_activate(struct tcpm_port *port, bool activate)
4635 {
4636         int ret = 0;
4637
4638         mutex_lock(&port->swap_lock);
4639         mutex_lock(&port->lock);
4640
4641         if (!port->pps_data.supported) {
4642                 ret = -EOPNOTSUPP;
4643                 goto port_unlock;
4644         }
4645
4646         /* Trying to deactivate PPS when already deactivated so just bail */
4647         if (!port->pps_data.active && !activate)
4648                 goto port_unlock;
4649
4650         if (port->state != SNK_READY) {
4651                 ret = -EAGAIN;
4652                 goto port_unlock;
4653         }
4654
4655         reinit_completion(&port->pps_complete);
4656         port->pps_status = 0;
4657         port->pps_pending = true;
4658
4659         /* Trigger PPS request or move back to standard PDO contract */
4660         if (activate) {
4661                 port->pps_data.req_out_volt = port->supply_voltage;
4662                 port->pps_data.req_op_curr = port->current_limit;
4663                 tcpm_set_state(port, SNK_NEGOTIATE_PPS_CAPABILITIES, 0);
4664         } else {
4665                 tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
4666         }
4667         mutex_unlock(&port->lock);
4668
4669         if (!wait_for_completion_timeout(&port->pps_complete,
4670                                 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
4671                 ret = -ETIMEDOUT;
4672         else
4673                 ret = port->pps_status;
4674
4675         goto swap_unlock;
4676
4677 port_unlock:
4678         mutex_unlock(&port->lock);
4679 swap_unlock:
4680         mutex_unlock(&port->swap_lock);
4681
4682         return ret;
4683 }
4684
4685 static void tcpm_init(struct tcpm_port *port)
4686 {
4687         enum typec_cc_status cc1, cc2;
4688
4689         port->tcpc->init(port->tcpc);
4690
4691         tcpm_reset_port(port);
4692
4693         /*
4694          * XXX
4695          * Should possibly wait for VBUS to settle if it was enabled locally
4696          * since tcpm_reset_port() will disable VBUS.
4697          */
4698         port->vbus_present = port->tcpc->get_vbus(port->tcpc);
4699         if (port->vbus_present)
4700                 port->vbus_never_low = true;
4701
4702         tcpm_set_state(port, tcpm_default_state(port), 0);
4703
4704         if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
4705                 _tcpm_cc_change(port, cc1, cc2);
4706
4707         /*
4708          * Some adapters need a clean slate at startup, and won't recover
4709          * otherwise. So do not try to be fancy and force a clean disconnect.
4710          */
4711         tcpm_set_state(port, PORT_RESET, 0);
4712 }
4713
4714 static int tcpm_port_type_set(struct typec_port *p, enum typec_port_type type)
4715 {
4716         struct tcpm_port *port = typec_get_drvdata(p);
4717
4718         mutex_lock(&port->lock);
4719         if (type == port->port_type)
4720                 goto port_unlock;
4721
4722         port->port_type = type;
4723
4724         if (!port->connected) {
4725                 tcpm_set_state(port, PORT_RESET, 0);
4726         } else if (type == TYPEC_PORT_SNK) {
4727                 if (!(port->pwr_role == TYPEC_SINK &&
4728                       port->data_role == TYPEC_DEVICE))
4729                         tcpm_set_state(port, PORT_RESET, 0);
4730         } else if (type == TYPEC_PORT_SRC) {
4731                 if (!(port->pwr_role == TYPEC_SOURCE &&
4732                       port->data_role == TYPEC_HOST))
4733                         tcpm_set_state(port, PORT_RESET, 0);
4734         }
4735
4736 port_unlock:
4737         mutex_unlock(&port->lock);
4738         return 0;
4739 }
4740
4741 static const struct typec_operations tcpm_ops = {
4742         .try_role = tcpm_try_role,
4743         .dr_set = tcpm_dr_set,
4744         .pr_set = tcpm_pr_set,
4745         .vconn_set = tcpm_vconn_set,
4746         .port_type_set = tcpm_port_type_set
4747 };
4748
4749 void tcpm_tcpc_reset(struct tcpm_port *port)
4750 {
4751         mutex_lock(&port->lock);
4752         /* XXX: Maintain PD connection if possible? */
4753         tcpm_init(port);
4754         mutex_unlock(&port->lock);
4755 }
4756 EXPORT_SYMBOL_GPL(tcpm_tcpc_reset);
4757
4758 static int tcpm_fw_get_caps(struct tcpm_port *port,
4759                             struct fwnode_handle *fwnode)
4760 {
4761         const char *cap_str;
4762         int ret;
4763         u32 mw, frs_current;
4764
4765         if (!fwnode)
4766                 return -EINVAL;
4767
4768         /* USB data support is optional */
4769         ret = fwnode_property_read_string(fwnode, "data-role", &cap_str);
4770         if (ret == 0) {
4771                 ret = typec_find_port_data_role(cap_str);
4772                 if (ret < 0)
4773                         return ret;
4774                 port->typec_caps.data = ret;
4775         }
4776
4777         ret = fwnode_property_read_string(fwnode, "power-role", &cap_str);
4778         if (ret < 0)
4779                 return ret;
4780
4781         ret = typec_find_port_power_role(cap_str);
4782         if (ret < 0)
4783                 return ret;
4784         port->typec_caps.type = ret;
4785         port->port_type = port->typec_caps.type;
4786
4787         if (port->port_type == TYPEC_PORT_SNK)
4788                 goto sink;
4789
4790         /* Get source pdos */
4791         ret = fwnode_property_count_u32(fwnode, "source-pdos");
4792         if (ret <= 0)
4793                 return -EINVAL;
4794
4795         port->nr_src_pdo = min(ret, PDO_MAX_OBJECTS);
4796         ret = fwnode_property_read_u32_array(fwnode, "source-pdos",
4797                                              port->src_pdo, port->nr_src_pdo);
4798         if ((ret < 0) || tcpm_validate_caps(port, port->src_pdo,
4799                                             port->nr_src_pdo))
4800                 return -EINVAL;
4801
4802         if (port->port_type == TYPEC_PORT_SRC)
4803                 return 0;
4804
4805         /* Get the preferred power role for DRP */
4806         ret = fwnode_property_read_string(fwnode, "try-power-role", &cap_str);
4807         if (ret < 0)
4808                 return ret;
4809
4810         port->typec_caps.prefer_role = typec_find_power_role(cap_str);
4811         if (port->typec_caps.prefer_role < 0)
4812                 return -EINVAL;
4813 sink:
4814         /* Get sink pdos */
4815         ret = fwnode_property_count_u32(fwnode, "sink-pdos");
4816         if (ret <= 0)
4817                 return -EINVAL;
4818
4819         port->nr_snk_pdo = min(ret, PDO_MAX_OBJECTS);
4820         ret = fwnode_property_read_u32_array(fwnode, "sink-pdos",
4821                                              port->snk_pdo, port->nr_snk_pdo);
4822         if ((ret < 0) || tcpm_validate_caps(port, port->snk_pdo,
4823                                             port->nr_snk_pdo))
4824                 return -EINVAL;
4825
4826         if (fwnode_property_read_u32(fwnode, "op-sink-microwatt", &mw) < 0)
4827                 return -EINVAL;
4828         port->operating_snk_mw = mw / 1000;
4829
4830         port->self_powered = fwnode_property_read_bool(fwnode, "self-powered");
4831
4832         /* FRS can only be supported byb DRP ports */
4833         if (port->port_type == TYPEC_PORT_DRP) {
4834                 ret = fwnode_property_read_u32(fwnode, "frs-typec-current", &frs_current);
4835                 if (ret >= 0 && frs_current <= FRS_5V_3A)
4836                         port->frs_current = frs_current;
4837         }
4838
4839         return 0;
4840 }
4841
4842 /* Power Supply access to expose source power information */
4843 enum tcpm_psy_online_states {
4844         TCPM_PSY_OFFLINE = 0,
4845         TCPM_PSY_FIXED_ONLINE,
4846         TCPM_PSY_PROG_ONLINE,
4847 };
4848
4849 static enum power_supply_property tcpm_psy_props[] = {
4850         POWER_SUPPLY_PROP_USB_TYPE,
4851         POWER_SUPPLY_PROP_ONLINE,
4852         POWER_SUPPLY_PROP_VOLTAGE_MIN,
4853         POWER_SUPPLY_PROP_VOLTAGE_MAX,
4854         POWER_SUPPLY_PROP_VOLTAGE_NOW,
4855         POWER_SUPPLY_PROP_CURRENT_MAX,
4856         POWER_SUPPLY_PROP_CURRENT_NOW,
4857 };
4858
4859 static int tcpm_psy_get_online(struct tcpm_port *port,
4860                                union power_supply_propval *val)
4861 {
4862         if (port->vbus_charge) {
4863                 if (port->pps_data.active)
4864                         val->intval = TCPM_PSY_PROG_ONLINE;
4865                 else
4866                         val->intval = TCPM_PSY_FIXED_ONLINE;
4867         } else {
4868                 val->intval = TCPM_PSY_OFFLINE;
4869         }
4870
4871         return 0;
4872 }
4873
4874 static int tcpm_psy_get_voltage_min(struct tcpm_port *port,
4875                                     union power_supply_propval *val)
4876 {
4877         if (port->pps_data.active)
4878                 val->intval = port->pps_data.min_volt * 1000;
4879         else
4880                 val->intval = port->supply_voltage * 1000;
4881
4882         return 0;
4883 }
4884
4885 static int tcpm_psy_get_voltage_max(struct tcpm_port *port,
4886                                     union power_supply_propval *val)
4887 {
4888         if (port->pps_data.active)
4889                 val->intval = port->pps_data.max_volt * 1000;
4890         else
4891                 val->intval = port->supply_voltage * 1000;
4892
4893         return 0;
4894 }
4895
4896 static int tcpm_psy_get_voltage_now(struct tcpm_port *port,
4897                                     union power_supply_propval *val)
4898 {
4899         val->intval = port->supply_voltage * 1000;
4900
4901         return 0;
4902 }
4903
4904 static int tcpm_psy_get_current_max(struct tcpm_port *port,
4905                                     union power_supply_propval *val)
4906 {
4907         if (port->pps_data.active)
4908                 val->intval = port->pps_data.max_curr * 1000;
4909         else
4910                 val->intval = port->current_limit * 1000;
4911
4912         return 0;
4913 }
4914
4915 static int tcpm_psy_get_current_now(struct tcpm_port *port,
4916                                     union power_supply_propval *val)
4917 {
4918         val->intval = port->current_limit * 1000;
4919
4920         return 0;
4921 }
4922
4923 static int tcpm_psy_get_prop(struct power_supply *psy,
4924                              enum power_supply_property psp,
4925                              union power_supply_propval *val)
4926 {
4927         struct tcpm_port *port = power_supply_get_drvdata(psy);
4928         int ret = 0;
4929
4930         switch (psp) {
4931         case POWER_SUPPLY_PROP_USB_TYPE:
4932                 val->intval = port->usb_type;
4933                 break;
4934         case POWER_SUPPLY_PROP_ONLINE:
4935                 ret = tcpm_psy_get_online(port, val);
4936                 break;
4937         case POWER_SUPPLY_PROP_VOLTAGE_MIN:
4938                 ret = tcpm_psy_get_voltage_min(port, val);
4939                 break;
4940         case POWER_SUPPLY_PROP_VOLTAGE_MAX:
4941                 ret = tcpm_psy_get_voltage_max(port, val);
4942                 break;
4943         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
4944                 ret = tcpm_psy_get_voltage_now(port, val);
4945                 break;
4946         case POWER_SUPPLY_PROP_CURRENT_MAX:
4947                 ret = tcpm_psy_get_current_max(port, val);
4948                 break;
4949         case POWER_SUPPLY_PROP_CURRENT_NOW:
4950                 ret = tcpm_psy_get_current_now(port, val);
4951                 break;
4952         default:
4953                 ret = -EINVAL;
4954                 break;
4955         }
4956
4957         return ret;
4958 }
4959
4960 static int tcpm_psy_set_online(struct tcpm_port *port,
4961                                const union power_supply_propval *val)
4962 {
4963         int ret;
4964
4965         switch (val->intval) {
4966         case TCPM_PSY_FIXED_ONLINE:
4967                 ret = tcpm_pps_activate(port, false);
4968                 break;
4969         case TCPM_PSY_PROG_ONLINE:
4970                 ret = tcpm_pps_activate(port, true);
4971                 break;
4972         default:
4973                 ret = -EINVAL;
4974                 break;
4975         }
4976
4977         return ret;
4978 }
4979
4980 static int tcpm_psy_set_prop(struct power_supply *psy,
4981                              enum power_supply_property psp,
4982                              const union power_supply_propval *val)
4983 {
4984         struct tcpm_port *port = power_supply_get_drvdata(psy);
4985         int ret;
4986
4987         switch (psp) {
4988         case POWER_SUPPLY_PROP_ONLINE:
4989                 ret = tcpm_psy_set_online(port, val);
4990                 break;
4991         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
4992                 if (val->intval < port->pps_data.min_volt * 1000 ||
4993                     val->intval > port->pps_data.max_volt * 1000)
4994                         ret = -EINVAL;
4995                 else
4996                         ret = tcpm_pps_set_out_volt(port, val->intval / 1000);
4997                 break;
4998         case POWER_SUPPLY_PROP_CURRENT_NOW:
4999                 if (val->intval > port->pps_data.max_curr * 1000)
5000                         ret = -EINVAL;
5001                 else
5002                         ret = tcpm_pps_set_op_curr(port, val->intval / 1000);
5003                 break;
5004         default:
5005                 ret = -EINVAL;
5006                 break;
5007         }
5008         power_supply_changed(port->psy);
5009         return ret;
5010 }
5011
5012 static int tcpm_psy_prop_writeable(struct power_supply *psy,
5013                                    enum power_supply_property psp)
5014 {
5015         switch (psp) {
5016         case POWER_SUPPLY_PROP_ONLINE:
5017         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
5018         case POWER_SUPPLY_PROP_CURRENT_NOW:
5019                 return 1;
5020         default:
5021                 return 0;
5022         }
5023 }
5024
5025 static enum power_supply_usb_type tcpm_psy_usb_types[] = {
5026         POWER_SUPPLY_USB_TYPE_C,
5027         POWER_SUPPLY_USB_TYPE_PD,
5028         POWER_SUPPLY_USB_TYPE_PD_PPS,
5029 };
5030
5031 static const char *tcpm_psy_name_prefix = "tcpm-source-psy-";
5032
5033 static int devm_tcpm_psy_register(struct tcpm_port *port)
5034 {
5035         struct power_supply_config psy_cfg = {};
5036         const char *port_dev_name = dev_name(port->dev);
5037         size_t psy_name_len = strlen(tcpm_psy_name_prefix) +
5038                                      strlen(port_dev_name) + 1;
5039         char *psy_name;
5040
5041         psy_cfg.drv_data = port;
5042         psy_cfg.fwnode = dev_fwnode(port->dev);
5043         psy_name = devm_kzalloc(port->dev, psy_name_len, GFP_KERNEL);
5044         if (!psy_name)
5045                 return -ENOMEM;
5046
5047         snprintf(psy_name, psy_name_len, "%s%s", tcpm_psy_name_prefix,
5048                  port_dev_name);
5049         port->psy_desc.name = psy_name;
5050         port->psy_desc.type = POWER_SUPPLY_TYPE_USB,
5051         port->psy_desc.usb_types = tcpm_psy_usb_types;
5052         port->psy_desc.num_usb_types = ARRAY_SIZE(tcpm_psy_usb_types);
5053         port->psy_desc.properties = tcpm_psy_props,
5054         port->psy_desc.num_properties = ARRAY_SIZE(tcpm_psy_props),
5055         port->psy_desc.get_property = tcpm_psy_get_prop,
5056         port->psy_desc.set_property = tcpm_psy_set_prop,
5057         port->psy_desc.property_is_writeable = tcpm_psy_prop_writeable,
5058
5059         port->usb_type = POWER_SUPPLY_USB_TYPE_C;
5060
5061         port->psy = devm_power_supply_register(port->dev, &port->psy_desc,
5062                                                &psy_cfg);
5063
5064         return PTR_ERR_OR_ZERO(port->psy);
5065 }
5066
5067 static enum hrtimer_restart state_machine_timer_handler(struct hrtimer *timer)
5068 {
5069         struct tcpm_port *port = container_of(timer, struct tcpm_port, state_machine_timer);
5070
5071         kthread_queue_work(port->wq, &port->state_machine);
5072         return HRTIMER_NORESTART;
5073 }
5074
5075 static enum hrtimer_restart vdm_state_machine_timer_handler(struct hrtimer *timer)
5076 {
5077         struct tcpm_port *port = container_of(timer, struct tcpm_port, vdm_state_machine_timer);
5078
5079         kthread_queue_work(port->wq, &port->vdm_state_machine);
5080         return HRTIMER_NORESTART;
5081 }
5082
5083 static enum hrtimer_restart enable_frs_timer_handler(struct hrtimer *timer)
5084 {
5085         struct tcpm_port *port = container_of(timer, struct tcpm_port, enable_frs_timer);
5086
5087         kthread_queue_work(port->wq, &port->enable_frs);
5088         return HRTIMER_NORESTART;
5089 }
5090
5091 struct tcpm_port *tcpm_register_port(struct device *dev, struct tcpc_dev *tcpc)
5092 {
5093         struct tcpm_port *port;
5094         int err;
5095
5096         if (!dev || !tcpc ||
5097             !tcpc->get_vbus || !tcpc->set_cc || !tcpc->get_cc ||
5098             !tcpc->set_polarity || !tcpc->set_vconn || !tcpc->set_vbus ||
5099             !tcpc->set_pd_rx || !tcpc->set_roles || !tcpc->pd_transmit)
5100                 return ERR_PTR(-EINVAL);
5101
5102         port = devm_kzalloc(dev, sizeof(*port), GFP_KERNEL);
5103         if (!port)
5104                 return ERR_PTR(-ENOMEM);
5105
5106         port->dev = dev;
5107         port->tcpc = tcpc;
5108
5109         mutex_init(&port->lock);
5110         mutex_init(&port->swap_lock);
5111
5112         port->wq = kthread_create_worker(0, dev_name(dev));
5113         if (IS_ERR(port->wq))
5114                 return ERR_CAST(port->wq);
5115         sched_set_fifo(port->wq->task);
5116
5117         kthread_init_work(&port->state_machine, tcpm_state_machine_work);
5118         kthread_init_work(&port->vdm_state_machine, vdm_state_machine_work);
5119         kthread_init_work(&port->event_work, tcpm_pd_event_handler);
5120         kthread_init_work(&port->enable_frs, tcpm_enable_frs_work);
5121         hrtimer_init(&port->state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5122         port->state_machine_timer.function = state_machine_timer_handler;
5123         hrtimer_init(&port->vdm_state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5124         port->vdm_state_machine_timer.function = vdm_state_machine_timer_handler;
5125         hrtimer_init(&port->enable_frs_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5126         port->enable_frs_timer.function = enable_frs_timer_handler;
5127
5128         spin_lock_init(&port->pd_event_lock);
5129
5130         init_completion(&port->tx_complete);
5131         init_completion(&port->swap_complete);
5132         init_completion(&port->pps_complete);
5133         tcpm_debugfs_init(port);
5134
5135         err = tcpm_fw_get_caps(port, tcpc->fwnode);
5136         if (err < 0)
5137                 goto out_destroy_wq;
5138
5139         port->try_role = port->typec_caps.prefer_role;
5140
5141         port->typec_caps.fwnode = tcpc->fwnode;
5142         port->typec_caps.revision = 0x0120;     /* Type-C spec release 1.2 */
5143         port->typec_caps.pd_revision = 0x0300;  /* USB-PD spec release 3.0 */
5144         port->typec_caps.driver_data = port;
5145         port->typec_caps.ops = &tcpm_ops;
5146         port->typec_caps.orientation_aware = 1;
5147
5148         port->partner_desc.identity = &port->partner_ident;
5149         port->port_type = port->typec_caps.type;
5150
5151         port->role_sw = usb_role_switch_get(port->dev);
5152         if (IS_ERR(port->role_sw)) {
5153                 err = PTR_ERR(port->role_sw);
5154                 goto out_destroy_wq;
5155         }
5156
5157         err = devm_tcpm_psy_register(port);
5158         if (err)
5159                 goto out_role_sw_put;
5160         power_supply_changed(port->psy);
5161
5162         port->typec_port = typec_register_port(port->dev, &port->typec_caps);
5163         if (IS_ERR(port->typec_port)) {
5164                 err = PTR_ERR(port->typec_port);
5165                 goto out_role_sw_put;
5166         }
5167
5168         mutex_lock(&port->lock);
5169         tcpm_init(port);
5170         mutex_unlock(&port->lock);
5171
5172         tcpm_log(port, "%s: registered", dev_name(dev));
5173         return port;
5174
5175 out_role_sw_put:
5176         usb_role_switch_put(port->role_sw);
5177 out_destroy_wq:
5178         tcpm_debugfs_exit(port);
5179         kthread_destroy_worker(port->wq);
5180         return ERR_PTR(err);
5181 }
5182 EXPORT_SYMBOL_GPL(tcpm_register_port);
5183
5184 void tcpm_unregister_port(struct tcpm_port *port)
5185 {
5186         int i;
5187
5188         hrtimer_cancel(&port->enable_frs_timer);
5189         hrtimer_cancel(&port->vdm_state_machine_timer);
5190         hrtimer_cancel(&port->state_machine_timer);
5191
5192         tcpm_reset_port(port);
5193         for (i = 0; i < ARRAY_SIZE(port->port_altmode); i++)
5194                 typec_unregister_altmode(port->port_altmode[i]);
5195         typec_unregister_port(port->typec_port);
5196         usb_role_switch_put(port->role_sw);
5197         tcpm_debugfs_exit(port);
5198         kthread_destroy_worker(port->wq);
5199 }
5200 EXPORT_SYMBOL_GPL(tcpm_unregister_port);
5201
5202 MODULE_AUTHOR("Guenter Roeck <groeck@chromium.org>");
5203 MODULE_DESCRIPTION("USB Type-C Port Manager");
5204 MODULE_LICENSE("GPL");