Merge tag 'usb-5.1-rc3' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/usb
[muen/linux.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/jiffies.h>
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/mutex.h>
15 #include <linux/power_supply.h>
16 #include <linux/proc_fs.h>
17 #include <linux/property.h>
18 #include <linux/sched/clock.h>
19 #include <linux/seq_file.h>
20 #include <linux/slab.h>
21 #include <linux/spinlock.h>
22 #include <linux/usb/pd.h>
23 #include <linux/usb/pd_ado.h>
24 #include <linux/usb/pd_bdo.h>
25 #include <linux/usb/pd_ext_sdb.h>
26 #include <linux/usb/pd_vdo.h>
27 #include <linux/usb/role.h>
28 #include <linux/usb/tcpm.h>
29 #include <linux/usb/typec_altmode.h>
30 #include <linux/workqueue.h>
31
32 #define FOREACH_STATE(S)                        \
33         S(INVALID_STATE),                       \
34         S(DRP_TOGGLING),                        \
35         S(SRC_UNATTACHED),                      \
36         S(SRC_ATTACH_WAIT),                     \
37         S(SRC_ATTACHED),                        \
38         S(SRC_STARTUP),                         \
39         S(SRC_SEND_CAPABILITIES),               \
40         S(SRC_SEND_CAPABILITIES_TIMEOUT),       \
41         S(SRC_NEGOTIATE_CAPABILITIES),          \
42         S(SRC_TRANSITION_SUPPLY),               \
43         S(SRC_READY),                           \
44         S(SRC_WAIT_NEW_CAPABILITIES),           \
45                                                 \
46         S(SNK_UNATTACHED),                      \
47         S(SNK_ATTACH_WAIT),                     \
48         S(SNK_DEBOUNCED),                       \
49         S(SNK_ATTACHED),                        \
50         S(SNK_STARTUP),                         \
51         S(SNK_DISCOVERY),                       \
52         S(SNK_DISCOVERY_DEBOUNCE),              \
53         S(SNK_DISCOVERY_DEBOUNCE_DONE),         \
54         S(SNK_WAIT_CAPABILITIES),               \
55         S(SNK_NEGOTIATE_CAPABILITIES),          \
56         S(SNK_NEGOTIATE_PPS_CAPABILITIES),      \
57         S(SNK_TRANSITION_SINK),                 \
58         S(SNK_TRANSITION_SINK_VBUS),            \
59         S(SNK_READY),                           \
60                                                 \
61         S(ACC_UNATTACHED),                      \
62         S(DEBUG_ACC_ATTACHED),                  \
63         S(AUDIO_ACC_ATTACHED),                  \
64         S(AUDIO_ACC_DEBOUNCE),                  \
65                                                 \
66         S(HARD_RESET_SEND),                     \
67         S(HARD_RESET_START),                    \
68         S(SRC_HARD_RESET_VBUS_OFF),             \
69         S(SRC_HARD_RESET_VBUS_ON),              \
70         S(SNK_HARD_RESET_SINK_OFF),             \
71         S(SNK_HARD_RESET_WAIT_VBUS),            \
72         S(SNK_HARD_RESET_SINK_ON),              \
73                                                 \
74         S(SOFT_RESET),                          \
75         S(SOFT_RESET_SEND),                     \
76                                                 \
77         S(DR_SWAP_ACCEPT),                      \
78         S(DR_SWAP_SEND),                        \
79         S(DR_SWAP_SEND_TIMEOUT),                \
80         S(DR_SWAP_CANCEL),                      \
81         S(DR_SWAP_CHANGE_DR),                   \
82                                                 \
83         S(PR_SWAP_ACCEPT),                      \
84         S(PR_SWAP_SEND),                        \
85         S(PR_SWAP_SEND_TIMEOUT),                \
86         S(PR_SWAP_CANCEL),                      \
87         S(PR_SWAP_START),                       \
88         S(PR_SWAP_SRC_SNK_TRANSITION_OFF),      \
89         S(PR_SWAP_SRC_SNK_SOURCE_OFF),          \
90         S(PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED), \
91         S(PR_SWAP_SRC_SNK_SINK_ON),             \
92         S(PR_SWAP_SNK_SRC_SINK_OFF),            \
93         S(PR_SWAP_SNK_SRC_SOURCE_ON),           \
94         S(PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP),    \
95                                                 \
96         S(VCONN_SWAP_ACCEPT),                   \
97         S(VCONN_SWAP_SEND),                     \
98         S(VCONN_SWAP_SEND_TIMEOUT),             \
99         S(VCONN_SWAP_CANCEL),                   \
100         S(VCONN_SWAP_START),                    \
101         S(VCONN_SWAP_WAIT_FOR_VCONN),           \
102         S(VCONN_SWAP_TURN_ON_VCONN),            \
103         S(VCONN_SWAP_TURN_OFF_VCONN),           \
104                                                 \
105         S(SNK_TRY),                             \
106         S(SNK_TRY_WAIT),                        \
107         S(SNK_TRY_WAIT_DEBOUNCE),               \
108         S(SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS),    \
109         S(SRC_TRYWAIT),                         \
110         S(SRC_TRYWAIT_DEBOUNCE),                \
111         S(SRC_TRYWAIT_UNATTACHED),              \
112                                                 \
113         S(SRC_TRY),                             \
114         S(SRC_TRY_WAIT),                        \
115         S(SRC_TRY_DEBOUNCE),                    \
116         S(SNK_TRYWAIT),                         \
117         S(SNK_TRYWAIT_DEBOUNCE),                \
118         S(SNK_TRYWAIT_VBUS),                    \
119         S(BIST_RX),                             \
120                                                 \
121         S(GET_STATUS_SEND),                     \
122         S(GET_STATUS_SEND_TIMEOUT),             \
123         S(GET_PPS_STATUS_SEND),                 \
124         S(GET_PPS_STATUS_SEND_TIMEOUT),         \
125                                                 \
126         S(ERROR_RECOVERY),                      \
127         S(PORT_RESET),                          \
128         S(PORT_RESET_WAIT_OFF)
129
130 #define GENERATE_ENUM(e)        e
131 #define GENERATE_STRING(s)      #s
132
133 enum tcpm_state {
134         FOREACH_STATE(GENERATE_ENUM)
135 };
136
137 static const char * const tcpm_states[] = {
138         FOREACH_STATE(GENERATE_STRING)
139 };
140
141 enum vdm_states {
142         VDM_STATE_ERR_BUSY = -3,
143         VDM_STATE_ERR_SEND = -2,
144         VDM_STATE_ERR_TMOUT = -1,
145         VDM_STATE_DONE = 0,
146         /* Anything >0 represents an active state */
147         VDM_STATE_READY = 1,
148         VDM_STATE_BUSY = 2,
149         VDM_STATE_WAIT_RSP_BUSY = 3,
150 };
151
152 enum pd_msg_request {
153         PD_MSG_NONE = 0,
154         PD_MSG_CTRL_REJECT,
155         PD_MSG_CTRL_WAIT,
156         PD_MSG_CTRL_NOT_SUPP,
157         PD_MSG_DATA_SINK_CAP,
158         PD_MSG_DATA_SOURCE_CAP,
159 };
160
161 /* Events from low level driver */
162
163 #define TCPM_CC_EVENT           BIT(0)
164 #define TCPM_VBUS_EVENT         BIT(1)
165 #define TCPM_RESET_EVENT        BIT(2)
166
167 #define LOG_BUFFER_ENTRIES      1024
168 #define LOG_BUFFER_ENTRY_SIZE   128
169
170 /* Alternate mode support */
171
172 #define SVID_DISCOVERY_MAX      16
173 #define ALTMODE_DISCOVERY_MAX   (SVID_DISCOVERY_MAX * MODE_DISCOVERY_MAX)
174
175 struct pd_mode_data {
176         int svid_index;         /* current SVID index           */
177         int nsvids;
178         u16 svids[SVID_DISCOVERY_MAX];
179         int altmodes;           /* number of alternate modes    */
180         struct typec_altmode_desc altmode_desc[ALTMODE_DISCOVERY_MAX];
181 };
182
183 struct pd_pps_data {
184         u32 min_volt;
185         u32 max_volt;
186         u32 max_curr;
187         u32 out_volt;
188         u32 op_curr;
189         bool supported;
190         bool active;
191 };
192
193 struct tcpm_port {
194         struct device *dev;
195
196         struct mutex lock;              /* tcpm state machine lock */
197         struct workqueue_struct *wq;
198
199         struct typec_capability typec_caps;
200         struct typec_port *typec_port;
201
202         struct tcpc_dev *tcpc;
203         struct usb_role_switch *role_sw;
204
205         enum typec_role vconn_role;
206         enum typec_role pwr_role;
207         enum typec_data_role data_role;
208         enum typec_pwr_opmode pwr_opmode;
209
210         struct usb_pd_identity partner_ident;
211         struct typec_partner_desc partner_desc;
212         struct typec_partner *partner;
213
214         enum typec_cc_status cc_req;
215
216         enum typec_cc_status cc1;
217         enum typec_cc_status cc2;
218         enum typec_cc_polarity polarity;
219
220         bool attached;
221         bool connected;
222         enum typec_port_type port_type;
223         bool vbus_present;
224         bool vbus_never_low;
225         bool vbus_source;
226         bool vbus_charge;
227
228         bool send_discover;
229         bool op_vsafe5v;
230
231         int try_role;
232         int try_snk_count;
233         int try_src_count;
234
235         enum pd_msg_request queued_message;
236
237         enum tcpm_state enter_state;
238         enum tcpm_state prev_state;
239         enum tcpm_state state;
240         enum tcpm_state delayed_state;
241         unsigned long delayed_runtime;
242         unsigned long delay_ms;
243
244         spinlock_t pd_event_lock;
245         u32 pd_events;
246
247         struct work_struct event_work;
248         struct delayed_work state_machine;
249         struct delayed_work vdm_state_machine;
250         bool state_machine_running;
251
252         struct completion tx_complete;
253         enum tcpm_transmit_status tx_status;
254
255         struct mutex swap_lock;         /* swap command lock */
256         bool swap_pending;
257         bool non_pd_role_swap;
258         struct completion swap_complete;
259         int swap_status;
260
261         unsigned int negotiated_rev;
262         unsigned int message_id;
263         unsigned int caps_count;
264         unsigned int hard_reset_count;
265         bool pd_capable;
266         bool explicit_contract;
267         unsigned int rx_msgid;
268
269         /* Partner capabilities/requests */
270         u32 sink_request;
271         u32 source_caps[PDO_MAX_OBJECTS];
272         unsigned int nr_source_caps;
273         u32 sink_caps[PDO_MAX_OBJECTS];
274         unsigned int nr_sink_caps;
275
276         /* Local capabilities */
277         u32 src_pdo[PDO_MAX_OBJECTS];
278         unsigned int nr_src_pdo;
279         u32 snk_pdo[PDO_MAX_OBJECTS];
280         unsigned int nr_snk_pdo;
281         u32 snk_vdo[VDO_MAX_OBJECTS];
282         unsigned int nr_snk_vdo;
283
284         unsigned int operating_snk_mw;
285         bool update_sink_caps;
286
287         /* Requested current / voltage */
288         u32 current_limit;
289         u32 supply_voltage;
290
291         /* Used to export TA voltage and current */
292         struct power_supply *psy;
293         struct power_supply_desc psy_desc;
294         enum power_supply_usb_type usb_type;
295
296         u32 bist_request;
297
298         /* PD state for Vendor Defined Messages */
299         enum vdm_states vdm_state;
300         u32 vdm_retries;
301         /* next Vendor Defined Message to send */
302         u32 vdo_data[VDO_MAX_SIZE];
303         u8 vdo_count;
304         /* VDO to retry if UFP responder replied busy */
305         u32 vdo_retry;
306
307         /* PPS */
308         struct pd_pps_data pps_data;
309         struct completion pps_complete;
310         bool pps_pending;
311         int pps_status;
312
313         /* Alternate mode data */
314         struct pd_mode_data mode_data;
315         struct typec_altmode *partner_altmode[ALTMODE_DISCOVERY_MAX];
316         struct typec_altmode *port_altmode[ALTMODE_DISCOVERY_MAX];
317
318         /* Deadline in jiffies to exit src_try_wait state */
319         unsigned long max_wait;
320
321         /* port belongs to a self powered device */
322         bool self_powered;
323
324 #ifdef CONFIG_DEBUG_FS
325         struct dentry *dentry;
326         struct mutex logbuffer_lock;    /* log buffer access lock */
327         int logbuffer_head;
328         int logbuffer_tail;
329         u8 *logbuffer[LOG_BUFFER_ENTRIES];
330 #endif
331 };
332
333 struct pd_rx_event {
334         struct work_struct work;
335         struct tcpm_port *port;
336         struct pd_message msg;
337 };
338
339 #define tcpm_cc_is_sink(cc) \
340         ((cc) == TYPEC_CC_RP_DEF || (cc) == TYPEC_CC_RP_1_5 || \
341          (cc) == TYPEC_CC_RP_3_0)
342
343 #define tcpm_port_is_sink(port) \
344         ((tcpm_cc_is_sink((port)->cc1) && !tcpm_cc_is_sink((port)->cc2)) || \
345          (tcpm_cc_is_sink((port)->cc2) && !tcpm_cc_is_sink((port)->cc1)))
346
347 #define tcpm_cc_is_source(cc) ((cc) == TYPEC_CC_RD)
348 #define tcpm_cc_is_audio(cc) ((cc) == TYPEC_CC_RA)
349 #define tcpm_cc_is_open(cc) ((cc) == TYPEC_CC_OPEN)
350
351 #define tcpm_port_is_source(port) \
352         ((tcpm_cc_is_source((port)->cc1) && \
353          !tcpm_cc_is_source((port)->cc2)) || \
354          (tcpm_cc_is_source((port)->cc2) && \
355           !tcpm_cc_is_source((port)->cc1)))
356
357 #define tcpm_port_is_debug(port) \
358         (tcpm_cc_is_source((port)->cc1) && tcpm_cc_is_source((port)->cc2))
359
360 #define tcpm_port_is_audio(port) \
361         (tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_audio((port)->cc2))
362
363 #define tcpm_port_is_audio_detached(port) \
364         ((tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_open((port)->cc2)) || \
365          (tcpm_cc_is_audio((port)->cc2) && tcpm_cc_is_open((port)->cc1)))
366
367 #define tcpm_try_snk(port) \
368         ((port)->try_snk_count == 0 && (port)->try_role == TYPEC_SINK && \
369         (port)->port_type == TYPEC_PORT_DRP)
370
371 #define tcpm_try_src(port) \
372         ((port)->try_src_count == 0 && (port)->try_role == TYPEC_SOURCE && \
373         (port)->port_type == TYPEC_PORT_DRP)
374
375 static enum tcpm_state tcpm_default_state(struct tcpm_port *port)
376 {
377         if (port->port_type == TYPEC_PORT_DRP) {
378                 if (port->try_role == TYPEC_SINK)
379                         return SNK_UNATTACHED;
380                 else if (port->try_role == TYPEC_SOURCE)
381                         return SRC_UNATTACHED;
382                 else if (port->tcpc->config->default_role == TYPEC_SINK)
383                         return SNK_UNATTACHED;
384                 /* Fall through to return SRC_UNATTACHED */
385         } else if (port->port_type == TYPEC_PORT_SNK) {
386                 return SNK_UNATTACHED;
387         }
388         return SRC_UNATTACHED;
389 }
390
391 static inline
392 struct tcpm_port *typec_cap_to_tcpm(const struct typec_capability *cap)
393 {
394         return container_of(cap, struct tcpm_port, typec_caps);
395 }
396
397 static bool tcpm_port_is_disconnected(struct tcpm_port *port)
398 {
399         return (!port->attached && port->cc1 == TYPEC_CC_OPEN &&
400                 port->cc2 == TYPEC_CC_OPEN) ||
401                (port->attached && ((port->polarity == TYPEC_POLARITY_CC1 &&
402                                     port->cc1 == TYPEC_CC_OPEN) ||
403                                    (port->polarity == TYPEC_POLARITY_CC2 &&
404                                     port->cc2 == TYPEC_CC_OPEN)));
405 }
406
407 /*
408  * Logging
409  */
410
411 #ifdef CONFIG_DEBUG_FS
412
413 static bool tcpm_log_full(struct tcpm_port *port)
414 {
415         return port->logbuffer_tail ==
416                 (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
417 }
418
419 __printf(2, 0)
420 static void _tcpm_log(struct tcpm_port *port, const char *fmt, va_list args)
421 {
422         char tmpbuffer[LOG_BUFFER_ENTRY_SIZE];
423         u64 ts_nsec = local_clock();
424         unsigned long rem_nsec;
425
426         mutex_lock(&port->logbuffer_lock);
427         if (!port->logbuffer[port->logbuffer_head]) {
428                 port->logbuffer[port->logbuffer_head] =
429                                 kzalloc(LOG_BUFFER_ENTRY_SIZE, GFP_KERNEL);
430                 if (!port->logbuffer[port->logbuffer_head]) {
431                         mutex_unlock(&port->logbuffer_lock);
432                         return;
433                 }
434         }
435
436         vsnprintf(tmpbuffer, sizeof(tmpbuffer), fmt, args);
437
438         if (tcpm_log_full(port)) {
439                 port->logbuffer_head = max(port->logbuffer_head - 1, 0);
440                 strcpy(tmpbuffer, "overflow");
441         }
442
443         if (port->logbuffer_head < 0 ||
444             port->logbuffer_head >= LOG_BUFFER_ENTRIES) {
445                 dev_warn(port->dev,
446                          "Bad log buffer index %d\n", port->logbuffer_head);
447                 goto abort;
448         }
449
450         if (!port->logbuffer[port->logbuffer_head]) {
451                 dev_warn(port->dev,
452                          "Log buffer index %d is NULL\n", port->logbuffer_head);
453                 goto abort;
454         }
455
456         rem_nsec = do_div(ts_nsec, 1000000000);
457         scnprintf(port->logbuffer[port->logbuffer_head],
458                   LOG_BUFFER_ENTRY_SIZE, "[%5lu.%06lu] %s",
459                   (unsigned long)ts_nsec, rem_nsec / 1000,
460                   tmpbuffer);
461         port->logbuffer_head = (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
462
463 abort:
464         mutex_unlock(&port->logbuffer_lock);
465 }
466
467 __printf(2, 3)
468 static void tcpm_log(struct tcpm_port *port, const char *fmt, ...)
469 {
470         va_list args;
471
472         /* Do not log while disconnected and unattached */
473         if (tcpm_port_is_disconnected(port) &&
474             (port->state == SRC_UNATTACHED || port->state == SNK_UNATTACHED ||
475              port->state == DRP_TOGGLING))
476                 return;
477
478         va_start(args, fmt);
479         _tcpm_log(port, fmt, args);
480         va_end(args);
481 }
482
483 __printf(2, 3)
484 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...)
485 {
486         va_list args;
487
488         va_start(args, fmt);
489         _tcpm_log(port, fmt, args);
490         va_end(args);
491 }
492
493 static void tcpm_log_source_caps(struct tcpm_port *port)
494 {
495         int i;
496
497         for (i = 0; i < port->nr_source_caps; i++) {
498                 u32 pdo = port->source_caps[i];
499                 enum pd_pdo_type type = pdo_type(pdo);
500                 char msg[64];
501
502                 switch (type) {
503                 case PDO_TYPE_FIXED:
504                         scnprintf(msg, sizeof(msg),
505                                   "%u mV, %u mA [%s%s%s%s%s%s]",
506                                   pdo_fixed_voltage(pdo),
507                                   pdo_max_current(pdo),
508                                   (pdo & PDO_FIXED_DUAL_ROLE) ?
509                                                         "R" : "",
510                                   (pdo & PDO_FIXED_SUSPEND) ?
511                                                         "S" : "",
512                                   (pdo & PDO_FIXED_HIGHER_CAP) ?
513                                                         "H" : "",
514                                   (pdo & PDO_FIXED_USB_COMM) ?
515                                                         "U" : "",
516                                   (pdo & PDO_FIXED_DATA_SWAP) ?
517                                                         "D" : "",
518                                   (pdo & PDO_FIXED_EXTPOWER) ?
519                                                         "E" : "");
520                         break;
521                 case PDO_TYPE_VAR:
522                         scnprintf(msg, sizeof(msg),
523                                   "%u-%u mV, %u mA",
524                                   pdo_min_voltage(pdo),
525                                   pdo_max_voltage(pdo),
526                                   pdo_max_current(pdo));
527                         break;
528                 case PDO_TYPE_BATT:
529                         scnprintf(msg, sizeof(msg),
530                                   "%u-%u mV, %u mW",
531                                   pdo_min_voltage(pdo),
532                                   pdo_max_voltage(pdo),
533                                   pdo_max_power(pdo));
534                         break;
535                 case PDO_TYPE_APDO:
536                         if (pdo_apdo_type(pdo) == APDO_TYPE_PPS)
537                                 scnprintf(msg, sizeof(msg),
538                                           "%u-%u mV, %u mA",
539                                           pdo_pps_apdo_min_voltage(pdo),
540                                           pdo_pps_apdo_max_voltage(pdo),
541                                           pdo_pps_apdo_max_current(pdo));
542                         else
543                                 strcpy(msg, "undefined APDO");
544                         break;
545                 default:
546                         strcpy(msg, "undefined");
547                         break;
548                 }
549                 tcpm_log(port, " PDO %d: type %d, %s",
550                          i, type, msg);
551         }
552 }
553
554 static int tcpm_debug_show(struct seq_file *s, void *v)
555 {
556         struct tcpm_port *port = (struct tcpm_port *)s->private;
557         int tail;
558
559         mutex_lock(&port->logbuffer_lock);
560         tail = port->logbuffer_tail;
561         while (tail != port->logbuffer_head) {
562                 seq_printf(s, "%s\n", port->logbuffer[tail]);
563                 tail = (tail + 1) % LOG_BUFFER_ENTRIES;
564         }
565         if (!seq_has_overflowed(s))
566                 port->logbuffer_tail = tail;
567         mutex_unlock(&port->logbuffer_lock);
568
569         return 0;
570 }
571 DEFINE_SHOW_ATTRIBUTE(tcpm_debug);
572
573 static struct dentry *rootdir;
574
575 static void tcpm_debugfs_init(struct tcpm_port *port)
576 {
577         mutex_init(&port->logbuffer_lock);
578         /* /sys/kernel/debug/tcpm/usbcX */
579         if (!rootdir)
580                 rootdir = debugfs_create_dir("tcpm", NULL);
581
582         port->dentry = debugfs_create_file(dev_name(port->dev),
583                                            S_IFREG | 0444, rootdir,
584                                            port, &tcpm_debug_fops);
585 }
586
587 static void tcpm_debugfs_exit(struct tcpm_port *port)
588 {
589         debugfs_remove(port->dentry);
590 }
591
592 #else
593
594 __printf(2, 3)
595 static void tcpm_log(const struct tcpm_port *port, const char *fmt, ...) { }
596 __printf(2, 3)
597 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...) { }
598 static void tcpm_log_source_caps(struct tcpm_port *port) { }
599 static void tcpm_debugfs_init(const struct tcpm_port *port) { }
600 static void tcpm_debugfs_exit(const struct tcpm_port *port) { }
601
602 #endif
603
604 static int tcpm_pd_transmit(struct tcpm_port *port,
605                             enum tcpm_transmit_type type,
606                             const struct pd_message *msg)
607 {
608         unsigned long timeout;
609         int ret;
610
611         if (msg)
612                 tcpm_log(port, "PD TX, header: %#x", le16_to_cpu(msg->header));
613         else
614                 tcpm_log(port, "PD TX, type: %#x", type);
615
616         reinit_completion(&port->tx_complete);
617         ret = port->tcpc->pd_transmit(port->tcpc, type, msg);
618         if (ret < 0)
619                 return ret;
620
621         mutex_unlock(&port->lock);
622         timeout = wait_for_completion_timeout(&port->tx_complete,
623                                 msecs_to_jiffies(PD_T_TCPC_TX_TIMEOUT));
624         mutex_lock(&port->lock);
625         if (!timeout)
626                 return -ETIMEDOUT;
627
628         switch (port->tx_status) {
629         case TCPC_TX_SUCCESS:
630                 port->message_id = (port->message_id + 1) & PD_HEADER_ID_MASK;
631                 return 0;
632         case TCPC_TX_DISCARDED:
633                 return -EAGAIN;
634         case TCPC_TX_FAILED:
635         default:
636                 return -EIO;
637         }
638 }
639
640 void tcpm_pd_transmit_complete(struct tcpm_port *port,
641                                enum tcpm_transmit_status status)
642 {
643         tcpm_log(port, "PD TX complete, status: %u", status);
644         port->tx_status = status;
645         complete(&port->tx_complete);
646 }
647 EXPORT_SYMBOL_GPL(tcpm_pd_transmit_complete);
648
649 static int tcpm_mux_set(struct tcpm_port *port, int state,
650                         enum usb_role usb_role,
651                         enum typec_orientation orientation)
652 {
653         int ret;
654
655         tcpm_log(port, "Requesting mux state %d, usb-role %d, orientation %d",
656                  state, usb_role, orientation);
657
658         ret = typec_set_orientation(port->typec_port, orientation);
659         if (ret)
660                 return ret;
661
662         if (port->role_sw) {
663                 ret = usb_role_switch_set_role(port->role_sw, usb_role);
664                 if (ret)
665                         return ret;
666         }
667
668         return typec_set_mode(port->typec_port, state);
669 }
670
671 static int tcpm_set_polarity(struct tcpm_port *port,
672                              enum typec_cc_polarity polarity)
673 {
674         int ret;
675
676         tcpm_log(port, "polarity %d", polarity);
677
678         ret = port->tcpc->set_polarity(port->tcpc, polarity);
679         if (ret < 0)
680                 return ret;
681
682         port->polarity = polarity;
683
684         return 0;
685 }
686
687 static int tcpm_set_vconn(struct tcpm_port *port, bool enable)
688 {
689         int ret;
690
691         tcpm_log(port, "vconn:=%d", enable);
692
693         ret = port->tcpc->set_vconn(port->tcpc, enable);
694         if (!ret) {
695                 port->vconn_role = enable ? TYPEC_SOURCE : TYPEC_SINK;
696                 typec_set_vconn_role(port->typec_port, port->vconn_role);
697         }
698
699         return ret;
700 }
701
702 static u32 tcpm_get_current_limit(struct tcpm_port *port)
703 {
704         enum typec_cc_status cc;
705         u32 limit;
706
707         cc = port->polarity ? port->cc2 : port->cc1;
708         switch (cc) {
709         case TYPEC_CC_RP_1_5:
710                 limit = 1500;
711                 break;
712         case TYPEC_CC_RP_3_0:
713                 limit = 3000;
714                 break;
715         case TYPEC_CC_RP_DEF:
716         default:
717                 if (port->tcpc->get_current_limit)
718                         limit = port->tcpc->get_current_limit(port->tcpc);
719                 else
720                         limit = 0;
721                 break;
722         }
723
724         return limit;
725 }
726
727 static int tcpm_set_current_limit(struct tcpm_port *port, u32 max_ma, u32 mv)
728 {
729         int ret = -EOPNOTSUPP;
730
731         tcpm_log(port, "Setting voltage/current limit %u mV %u mA", mv, max_ma);
732
733         port->supply_voltage = mv;
734         port->current_limit = max_ma;
735
736         if (port->tcpc->set_current_limit)
737                 ret = port->tcpc->set_current_limit(port->tcpc, max_ma, mv);
738
739         return ret;
740 }
741
742 /*
743  * Determine RP value to set based on maximum current supported
744  * by a port if configured as source.
745  * Returns CC value to report to link partner.
746  */
747 static enum typec_cc_status tcpm_rp_cc(struct tcpm_port *port)
748 {
749         const u32 *src_pdo = port->src_pdo;
750         int nr_pdo = port->nr_src_pdo;
751         int i;
752
753         /*
754          * Search for first entry with matching voltage.
755          * It should report the maximum supported current.
756          */
757         for (i = 0; i < nr_pdo; i++) {
758                 const u32 pdo = src_pdo[i];
759
760                 if (pdo_type(pdo) == PDO_TYPE_FIXED &&
761                     pdo_fixed_voltage(pdo) == 5000) {
762                         unsigned int curr = pdo_max_current(pdo);
763
764                         if (curr >= 3000)
765                                 return TYPEC_CC_RP_3_0;
766                         else if (curr >= 1500)
767                                 return TYPEC_CC_RP_1_5;
768                         return TYPEC_CC_RP_DEF;
769                 }
770         }
771
772         return TYPEC_CC_RP_DEF;
773 }
774
775 static int tcpm_set_attached_state(struct tcpm_port *port, bool attached)
776 {
777         return port->tcpc->set_roles(port->tcpc, attached, port->pwr_role,
778                                      port->data_role);
779 }
780
781 static int tcpm_set_roles(struct tcpm_port *port, bool attached,
782                           enum typec_role role, enum typec_data_role data)
783 {
784         enum typec_orientation orientation;
785         enum usb_role usb_role;
786         int ret;
787
788         if (port->polarity == TYPEC_POLARITY_CC1)
789                 orientation = TYPEC_ORIENTATION_NORMAL;
790         else
791                 orientation = TYPEC_ORIENTATION_REVERSE;
792
793         if (data == TYPEC_HOST)
794                 usb_role = USB_ROLE_HOST;
795         else
796                 usb_role = USB_ROLE_DEVICE;
797
798         ret = tcpm_mux_set(port, TYPEC_STATE_USB, usb_role, orientation);
799         if (ret < 0)
800                 return ret;
801
802         ret = port->tcpc->set_roles(port->tcpc, attached, role, data);
803         if (ret < 0)
804                 return ret;
805
806         port->pwr_role = role;
807         port->data_role = data;
808         typec_set_data_role(port->typec_port, data);
809         typec_set_pwr_role(port->typec_port, role);
810
811         return 0;
812 }
813
814 static int tcpm_set_pwr_role(struct tcpm_port *port, enum typec_role role)
815 {
816         int ret;
817
818         ret = port->tcpc->set_roles(port->tcpc, true, role,
819                                     port->data_role);
820         if (ret < 0)
821                 return ret;
822
823         port->pwr_role = role;
824         typec_set_pwr_role(port->typec_port, role);
825
826         return 0;
827 }
828
829 static int tcpm_pd_send_source_caps(struct tcpm_port *port)
830 {
831         struct pd_message msg;
832         int i;
833
834         memset(&msg, 0, sizeof(msg));
835         if (!port->nr_src_pdo) {
836                 /* No source capabilities defined, sink only */
837                 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
838                                           port->pwr_role,
839                                           port->data_role,
840                                           port->negotiated_rev,
841                                           port->message_id, 0);
842         } else {
843                 msg.header = PD_HEADER_LE(PD_DATA_SOURCE_CAP,
844                                           port->pwr_role,
845                                           port->data_role,
846                                           port->negotiated_rev,
847                                           port->message_id,
848                                           port->nr_src_pdo);
849         }
850         for (i = 0; i < port->nr_src_pdo; i++)
851                 msg.payload[i] = cpu_to_le32(port->src_pdo[i]);
852
853         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
854 }
855
856 static int tcpm_pd_send_sink_caps(struct tcpm_port *port)
857 {
858         struct pd_message msg;
859         int i;
860
861         memset(&msg, 0, sizeof(msg));
862         if (!port->nr_snk_pdo) {
863                 /* No sink capabilities defined, source only */
864                 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
865                                           port->pwr_role,
866                                           port->data_role,
867                                           port->negotiated_rev,
868                                           port->message_id, 0);
869         } else {
870                 msg.header = PD_HEADER_LE(PD_DATA_SINK_CAP,
871                                           port->pwr_role,
872                                           port->data_role,
873                                           port->negotiated_rev,
874                                           port->message_id,
875                                           port->nr_snk_pdo);
876         }
877         for (i = 0; i < port->nr_snk_pdo; i++)
878                 msg.payload[i] = cpu_to_le32(port->snk_pdo[i]);
879
880         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
881 }
882
883 static void tcpm_set_state(struct tcpm_port *port, enum tcpm_state state,
884                            unsigned int delay_ms)
885 {
886         if (delay_ms) {
887                 tcpm_log(port, "pending state change %s -> %s @ %u ms",
888                          tcpm_states[port->state], tcpm_states[state],
889                          delay_ms);
890                 port->delayed_state = state;
891                 mod_delayed_work(port->wq, &port->state_machine,
892                                  msecs_to_jiffies(delay_ms));
893                 port->delayed_runtime = jiffies + msecs_to_jiffies(delay_ms);
894                 port->delay_ms = delay_ms;
895         } else {
896                 tcpm_log(port, "state change %s -> %s",
897                          tcpm_states[port->state], tcpm_states[state]);
898                 port->delayed_state = INVALID_STATE;
899                 port->prev_state = port->state;
900                 port->state = state;
901                 /*
902                  * Don't re-queue the state machine work item if we're currently
903                  * in the state machine and we're immediately changing states.
904                  * tcpm_state_machine_work() will continue running the state
905                  * machine.
906                  */
907                 if (!port->state_machine_running)
908                         mod_delayed_work(port->wq, &port->state_machine, 0);
909         }
910 }
911
912 static void tcpm_set_state_cond(struct tcpm_port *port, enum tcpm_state state,
913                                 unsigned int delay_ms)
914 {
915         if (port->enter_state == port->state)
916                 tcpm_set_state(port, state, delay_ms);
917         else
918                 tcpm_log(port,
919                          "skipped %sstate change %s -> %s [%u ms], context state %s",
920                          delay_ms ? "delayed " : "",
921                          tcpm_states[port->state], tcpm_states[state],
922                          delay_ms, tcpm_states[port->enter_state]);
923 }
924
925 static void tcpm_queue_message(struct tcpm_port *port,
926                                enum pd_msg_request message)
927 {
928         port->queued_message = message;
929         mod_delayed_work(port->wq, &port->state_machine, 0);
930 }
931
932 /*
933  * VDM/VDO handling functions
934  */
935 static void tcpm_queue_vdm(struct tcpm_port *port, const u32 header,
936                            const u32 *data, int cnt)
937 {
938         port->vdo_count = cnt + 1;
939         port->vdo_data[0] = header;
940         memcpy(&port->vdo_data[1], data, sizeof(u32) * cnt);
941         /* Set ready, vdm state machine will actually send */
942         port->vdm_retries = 0;
943         port->vdm_state = VDM_STATE_READY;
944 }
945
946 static void svdm_consume_identity(struct tcpm_port *port, const __le32 *payload,
947                                   int cnt)
948 {
949         u32 vdo = le32_to_cpu(payload[VDO_INDEX_IDH]);
950         u32 product = le32_to_cpu(payload[VDO_INDEX_PRODUCT]);
951
952         memset(&port->mode_data, 0, sizeof(port->mode_data));
953
954         port->partner_ident.id_header = vdo;
955         port->partner_ident.cert_stat = le32_to_cpu(payload[VDO_INDEX_CSTAT]);
956         port->partner_ident.product = product;
957
958         typec_partner_set_identity(port->partner);
959
960         tcpm_log(port, "Identity: %04x:%04x.%04x",
961                  PD_IDH_VID(vdo),
962                  PD_PRODUCT_PID(product), product & 0xffff);
963 }
964
965 static bool svdm_consume_svids(struct tcpm_port *port, const __le32 *payload,
966                                int cnt)
967 {
968         struct pd_mode_data *pmdata = &port->mode_data;
969         int i;
970
971         for (i = 1; i < cnt; i++) {
972                 u32 p = le32_to_cpu(payload[i]);
973                 u16 svid;
974
975                 svid = (p >> 16) & 0xffff;
976                 if (!svid)
977                         return false;
978
979                 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
980                         goto abort;
981
982                 pmdata->svids[pmdata->nsvids++] = svid;
983                 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
984
985                 svid = p & 0xffff;
986                 if (!svid)
987                         return false;
988
989                 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
990                         goto abort;
991
992                 pmdata->svids[pmdata->nsvids++] = svid;
993                 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
994         }
995         return true;
996 abort:
997         tcpm_log(port, "SVID_DISCOVERY_MAX(%d) too low!", SVID_DISCOVERY_MAX);
998         return false;
999 }
1000
1001 static void svdm_consume_modes(struct tcpm_port *port, const __le32 *payload,
1002                                int cnt)
1003 {
1004         struct pd_mode_data *pmdata = &port->mode_data;
1005         struct typec_altmode_desc *paltmode;
1006         int i;
1007
1008         if (pmdata->altmodes >= ARRAY_SIZE(port->partner_altmode)) {
1009                 /* Already logged in svdm_consume_svids() */
1010                 return;
1011         }
1012
1013         for (i = 1; i < cnt; i++) {
1014                 paltmode = &pmdata->altmode_desc[pmdata->altmodes];
1015                 memset(paltmode, 0, sizeof(*paltmode));
1016
1017                 paltmode->svid = pmdata->svids[pmdata->svid_index];
1018                 paltmode->mode = i;
1019                 paltmode->vdo = le32_to_cpu(payload[i]);
1020
1021                 tcpm_log(port, " Alternate mode %d: SVID 0x%04x, VDO %d: 0x%08x",
1022                          pmdata->altmodes, paltmode->svid,
1023                          paltmode->mode, paltmode->vdo);
1024
1025                 pmdata->altmodes++;
1026         }
1027 }
1028
1029 static void tcpm_register_partner_altmodes(struct tcpm_port *port)
1030 {
1031         struct pd_mode_data *modep = &port->mode_data;
1032         struct typec_altmode *altmode;
1033         int i;
1034
1035         for (i = 0; i < modep->altmodes; i++) {
1036                 altmode = typec_partner_register_altmode(port->partner,
1037                                                 &modep->altmode_desc[i]);
1038                 if (!altmode)
1039                         tcpm_log(port, "Failed to register partner SVID 0x%04x",
1040                                  modep->altmode_desc[i].svid);
1041                 port->partner_altmode[i] = altmode;
1042         }
1043 }
1044
1045 #define supports_modal(port)    PD_IDH_MODAL_SUPP((port)->partner_ident.id_header)
1046
1047 static int tcpm_pd_svdm(struct tcpm_port *port, const __le32 *payload, int cnt,
1048                         u32 *response)
1049 {
1050         struct typec_altmode *adev;
1051         struct typec_altmode *pdev;
1052         struct pd_mode_data *modep;
1053         u32 p[PD_MAX_PAYLOAD];
1054         int rlen = 0;
1055         int cmd_type;
1056         int cmd;
1057         int i;
1058
1059         for (i = 0; i < cnt; i++)
1060                 p[i] = le32_to_cpu(payload[i]);
1061
1062         cmd_type = PD_VDO_CMDT(p[0]);
1063         cmd = PD_VDO_CMD(p[0]);
1064
1065         tcpm_log(port, "Rx VDM cmd 0x%x type %d cmd %d len %d",
1066                  p[0], cmd_type, cmd, cnt);
1067
1068         modep = &port->mode_data;
1069
1070         adev = typec_match_altmode(port->port_altmode, ALTMODE_DISCOVERY_MAX,
1071                                    PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1072
1073         pdev = typec_match_altmode(port->partner_altmode, ALTMODE_DISCOVERY_MAX,
1074                                    PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1075
1076         switch (cmd_type) {
1077         case CMDT_INIT:
1078                 switch (cmd) {
1079                 case CMD_DISCOVER_IDENT:
1080                         /* 6.4.4.3.1: Only respond as UFP (device) */
1081                         if (port->data_role == TYPEC_DEVICE &&
1082                             port->nr_snk_vdo) {
1083                                 for (i = 0; i <  port->nr_snk_vdo; i++)
1084                                         response[i + 1] = port->snk_vdo[i];
1085                                 rlen = port->nr_snk_vdo + 1;
1086                         }
1087                         break;
1088                 case CMD_DISCOVER_SVID:
1089                         break;
1090                 case CMD_DISCOVER_MODES:
1091                         break;
1092                 case CMD_ENTER_MODE:
1093                         break;
1094                 case CMD_EXIT_MODE:
1095                         break;
1096                 case CMD_ATTENTION:
1097                         /* Attention command does not have response */
1098                         typec_altmode_attention(adev, p[1]);
1099                         return 0;
1100                 default:
1101                         break;
1102                 }
1103                 if (rlen >= 1) {
1104                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_ACK);
1105                 } else if (rlen == 0) {
1106                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1107                         rlen = 1;
1108                 } else {
1109                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_BUSY);
1110                         rlen = 1;
1111                 }
1112                 break;
1113         case CMDT_RSP_ACK:
1114                 /* silently drop message if we are not connected */
1115                 if (IS_ERR_OR_NULL(port->partner))
1116                         break;
1117
1118                 switch (cmd) {
1119                 case CMD_DISCOVER_IDENT:
1120                         /* 6.4.4.3.1 */
1121                         svdm_consume_identity(port, payload, cnt);
1122                         response[0] = VDO(USB_SID_PD, 1, CMD_DISCOVER_SVID);
1123                         rlen = 1;
1124                         break;
1125                 case CMD_DISCOVER_SVID:
1126                         /* 6.4.4.3.2 */
1127                         if (svdm_consume_svids(port, payload, cnt)) {
1128                                 response[0] = VDO(USB_SID_PD, 1,
1129                                                   CMD_DISCOVER_SVID);
1130                                 rlen = 1;
1131                         } else if (modep->nsvids && supports_modal(port)) {
1132                                 response[0] = VDO(modep->svids[0], 1,
1133                                                   CMD_DISCOVER_MODES);
1134                                 rlen = 1;
1135                         }
1136                         break;
1137                 case CMD_DISCOVER_MODES:
1138                         /* 6.4.4.3.3 */
1139                         svdm_consume_modes(port, payload, cnt);
1140                         modep->svid_index++;
1141                         if (modep->svid_index < modep->nsvids) {
1142                                 u16 svid = modep->svids[modep->svid_index];
1143                                 response[0] = VDO(svid, 1, CMD_DISCOVER_MODES);
1144                                 rlen = 1;
1145                         } else {
1146                                 tcpm_register_partner_altmodes(port);
1147                         }
1148                         break;
1149                 case CMD_ENTER_MODE:
1150                         typec_altmode_update_active(pdev, true);
1151
1152                         if (typec_altmode_vdm(adev, p[0], &p[1], cnt)) {
1153                                 response[0] = VDO(adev->svid, 1, CMD_EXIT_MODE);
1154                                 response[0] |= VDO_OPOS(adev->mode);
1155                                 return 1;
1156                         }
1157                         return 0;
1158                 case CMD_EXIT_MODE:
1159                         typec_altmode_update_active(pdev, false);
1160
1161                         /* Back to USB Operation */
1162                         WARN_ON(typec_altmode_notify(adev, TYPEC_STATE_USB,
1163                                                      NULL));
1164                         break;
1165                 default:
1166                         break;
1167                 }
1168                 break;
1169         case CMDT_RSP_NAK:
1170                 switch (cmd) {
1171                 case CMD_ENTER_MODE:
1172                         /* Back to USB Operation */
1173                         WARN_ON(typec_altmode_notify(adev, TYPEC_STATE_USB,
1174                                                      NULL));
1175                         break;
1176                 default:
1177                         break;
1178                 }
1179                 break;
1180         default:
1181                 break;
1182         }
1183
1184         /* Informing the alternate mode drivers about everything */
1185         typec_altmode_vdm(adev, p[0], &p[1], cnt);
1186
1187         return rlen;
1188 }
1189
1190 static void tcpm_handle_vdm_request(struct tcpm_port *port,
1191                                     const __le32 *payload, int cnt)
1192 {
1193         int rlen = 0;
1194         u32 response[8] = { };
1195         u32 p0 = le32_to_cpu(payload[0]);
1196
1197         if (port->vdm_state == VDM_STATE_BUSY) {
1198                 /* If UFP responded busy retry after timeout */
1199                 if (PD_VDO_CMDT(p0) == CMDT_RSP_BUSY) {
1200                         port->vdm_state = VDM_STATE_WAIT_RSP_BUSY;
1201                         port->vdo_retry = (p0 & ~VDO_CMDT_MASK) |
1202                                 CMDT_INIT;
1203                         mod_delayed_work(port->wq, &port->vdm_state_machine,
1204                                          msecs_to_jiffies(PD_T_VDM_BUSY));
1205                         return;
1206                 }
1207                 port->vdm_state = VDM_STATE_DONE;
1208         }
1209
1210         if (PD_VDO_SVDM(p0))
1211                 rlen = tcpm_pd_svdm(port, payload, cnt, response);
1212
1213         if (rlen > 0) {
1214                 tcpm_queue_vdm(port, response[0], &response[1], rlen - 1);
1215                 mod_delayed_work(port->wq, &port->vdm_state_machine, 0);
1216         }
1217 }
1218
1219 static void tcpm_send_vdm(struct tcpm_port *port, u32 vid, int cmd,
1220                           const u32 *data, int count)
1221 {
1222         u32 header;
1223
1224         if (WARN_ON(count > VDO_MAX_SIZE - 1))
1225                 count = VDO_MAX_SIZE - 1;
1226
1227         /* set VDM header with VID & CMD */
1228         header = VDO(vid, ((vid & USB_SID_PD) == USB_SID_PD) ?
1229                         1 : (PD_VDO_CMD(cmd) <= CMD_ATTENTION), cmd);
1230         tcpm_queue_vdm(port, header, data, count);
1231
1232         mod_delayed_work(port->wq, &port->vdm_state_machine, 0);
1233 }
1234
1235 static unsigned int vdm_ready_timeout(u32 vdm_hdr)
1236 {
1237         unsigned int timeout;
1238         int cmd = PD_VDO_CMD(vdm_hdr);
1239
1240         /* its not a structured VDM command */
1241         if (!PD_VDO_SVDM(vdm_hdr))
1242                 return PD_T_VDM_UNSTRUCTURED;
1243
1244         switch (PD_VDO_CMDT(vdm_hdr)) {
1245         case CMDT_INIT:
1246                 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1247                         timeout = PD_T_VDM_WAIT_MODE_E;
1248                 else
1249                         timeout = PD_T_VDM_SNDR_RSP;
1250                 break;
1251         default:
1252                 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1253                         timeout = PD_T_VDM_E_MODE;
1254                 else
1255                         timeout = PD_T_VDM_RCVR_RSP;
1256                 break;
1257         }
1258         return timeout;
1259 }
1260
1261 static void vdm_run_state_machine(struct tcpm_port *port)
1262 {
1263         struct pd_message msg;
1264         int i, res;
1265
1266         switch (port->vdm_state) {
1267         case VDM_STATE_READY:
1268                 /* Only transmit VDM if attached */
1269                 if (!port->attached) {
1270                         port->vdm_state = VDM_STATE_ERR_BUSY;
1271                         break;
1272                 }
1273
1274                 /*
1275                  * if there's traffic or we're not in PDO ready state don't send
1276                  * a VDM.
1277                  */
1278                 if (port->state != SRC_READY && port->state != SNK_READY)
1279                         break;
1280
1281                 /* Prepare and send VDM */
1282                 memset(&msg, 0, sizeof(msg));
1283                 msg.header = PD_HEADER_LE(PD_DATA_VENDOR_DEF,
1284                                           port->pwr_role,
1285                                           port->data_role,
1286                                           port->negotiated_rev,
1287                                           port->message_id, port->vdo_count);
1288                 for (i = 0; i < port->vdo_count; i++)
1289                         msg.payload[i] = cpu_to_le32(port->vdo_data[i]);
1290                 res = tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1291                 if (res < 0) {
1292                         port->vdm_state = VDM_STATE_ERR_SEND;
1293                 } else {
1294                         unsigned long timeout;
1295
1296                         port->vdm_retries = 0;
1297                         port->vdm_state = VDM_STATE_BUSY;
1298                         timeout = vdm_ready_timeout(port->vdo_data[0]);
1299                         mod_delayed_work(port->wq, &port->vdm_state_machine,
1300                                          timeout);
1301                 }
1302                 break;
1303         case VDM_STATE_WAIT_RSP_BUSY:
1304                 port->vdo_data[0] = port->vdo_retry;
1305                 port->vdo_count = 1;
1306                 port->vdm_state = VDM_STATE_READY;
1307                 break;
1308         case VDM_STATE_BUSY:
1309                 port->vdm_state = VDM_STATE_ERR_TMOUT;
1310                 break;
1311         case VDM_STATE_ERR_SEND:
1312                 /*
1313                  * A partner which does not support USB PD will not reply,
1314                  * so this is not a fatal error. At the same time, some
1315                  * devices may not return GoodCRC under some circumstances,
1316                  * so we need to retry.
1317                  */
1318                 if (port->vdm_retries < 3) {
1319                         tcpm_log(port, "VDM Tx error, retry");
1320                         port->vdm_retries++;
1321                         port->vdm_state = VDM_STATE_READY;
1322                 }
1323                 break;
1324         default:
1325                 break;
1326         }
1327 }
1328
1329 static void vdm_state_machine_work(struct work_struct *work)
1330 {
1331         struct tcpm_port *port = container_of(work, struct tcpm_port,
1332                                               vdm_state_machine.work);
1333         enum vdm_states prev_state;
1334
1335         mutex_lock(&port->lock);
1336
1337         /*
1338          * Continue running as long as the port is not busy and there was
1339          * a state change.
1340          */
1341         do {
1342                 prev_state = port->vdm_state;
1343                 vdm_run_state_machine(port);
1344         } while (port->vdm_state != prev_state &&
1345                  port->vdm_state != VDM_STATE_BUSY);
1346
1347         mutex_unlock(&port->lock);
1348 }
1349
1350 enum pdo_err {
1351         PDO_NO_ERR,
1352         PDO_ERR_NO_VSAFE5V,
1353         PDO_ERR_VSAFE5V_NOT_FIRST,
1354         PDO_ERR_PDO_TYPE_NOT_IN_ORDER,
1355         PDO_ERR_FIXED_NOT_SORTED,
1356         PDO_ERR_VARIABLE_BATT_NOT_SORTED,
1357         PDO_ERR_DUPE_PDO,
1358         PDO_ERR_PPS_APDO_NOT_SORTED,
1359         PDO_ERR_DUPE_PPS_APDO,
1360 };
1361
1362 static const char * const pdo_err_msg[] = {
1363         [PDO_ERR_NO_VSAFE5V] =
1364         " err: source/sink caps should atleast have vSafe5V",
1365         [PDO_ERR_VSAFE5V_NOT_FIRST] =
1366         " err: vSafe5V Fixed Supply Object Shall always be the first object",
1367         [PDO_ERR_PDO_TYPE_NOT_IN_ORDER] =
1368         " err: PDOs should be in the following order: Fixed; Battery; Variable",
1369         [PDO_ERR_FIXED_NOT_SORTED] =
1370         " err: Fixed supply pdos should be in increasing order of their fixed voltage",
1371         [PDO_ERR_VARIABLE_BATT_NOT_SORTED] =
1372         " err: Variable/Battery supply pdos should be in increasing order of their minimum voltage",
1373         [PDO_ERR_DUPE_PDO] =
1374         " err: Variable/Batt supply pdos cannot have same min/max voltage",
1375         [PDO_ERR_PPS_APDO_NOT_SORTED] =
1376         " err: Programmable power supply apdos should be in increasing order of their maximum voltage",
1377         [PDO_ERR_DUPE_PPS_APDO] =
1378         " err: Programmable power supply apdos cannot have same min/max voltage and max current",
1379 };
1380
1381 static enum pdo_err tcpm_caps_err(struct tcpm_port *port, const u32 *pdo,
1382                                   unsigned int nr_pdo)
1383 {
1384         unsigned int i;
1385
1386         /* Should at least contain vSafe5v */
1387         if (nr_pdo < 1)
1388                 return PDO_ERR_NO_VSAFE5V;
1389
1390         /* The vSafe5V Fixed Supply Object Shall always be the first object */
1391         if (pdo_type(pdo[0]) != PDO_TYPE_FIXED ||
1392             pdo_fixed_voltage(pdo[0]) != VSAFE5V)
1393                 return PDO_ERR_VSAFE5V_NOT_FIRST;
1394
1395         for (i = 1; i < nr_pdo; i++) {
1396                 if (pdo_type(pdo[i]) < pdo_type(pdo[i - 1])) {
1397                         return PDO_ERR_PDO_TYPE_NOT_IN_ORDER;
1398                 } else if (pdo_type(pdo[i]) == pdo_type(pdo[i - 1])) {
1399                         enum pd_pdo_type type = pdo_type(pdo[i]);
1400
1401                         switch (type) {
1402                         /*
1403                          * The remaining Fixed Supply Objects, if
1404                          * present, shall be sent in voltage order;
1405                          * lowest to highest.
1406                          */
1407                         case PDO_TYPE_FIXED:
1408                                 if (pdo_fixed_voltage(pdo[i]) <=
1409                                     pdo_fixed_voltage(pdo[i - 1]))
1410                                         return PDO_ERR_FIXED_NOT_SORTED;
1411                                 break;
1412                         /*
1413                          * The Battery Supply Objects and Variable
1414                          * supply, if present shall be sent in Minimum
1415                          * Voltage order; lowest to highest.
1416                          */
1417                         case PDO_TYPE_VAR:
1418                         case PDO_TYPE_BATT:
1419                                 if (pdo_min_voltage(pdo[i]) <
1420                                     pdo_min_voltage(pdo[i - 1]))
1421                                         return PDO_ERR_VARIABLE_BATT_NOT_SORTED;
1422                                 else if ((pdo_min_voltage(pdo[i]) ==
1423                                           pdo_min_voltage(pdo[i - 1])) &&
1424                                          (pdo_max_voltage(pdo[i]) ==
1425                                           pdo_min_voltage(pdo[i - 1])))
1426                                         return PDO_ERR_DUPE_PDO;
1427                                 break;
1428                         /*
1429                          * The Programmable Power Supply APDOs, if present,
1430                          * shall be sent in Maximum Voltage order;
1431                          * lowest to highest.
1432                          */
1433                         case PDO_TYPE_APDO:
1434                                 if (pdo_apdo_type(pdo[i]) != APDO_TYPE_PPS)
1435                                         break;
1436
1437                                 if (pdo_pps_apdo_max_voltage(pdo[i]) <
1438                                     pdo_pps_apdo_max_voltage(pdo[i - 1]))
1439                                         return PDO_ERR_PPS_APDO_NOT_SORTED;
1440                                 else if (pdo_pps_apdo_min_voltage(pdo[i]) ==
1441                                           pdo_pps_apdo_min_voltage(pdo[i - 1]) &&
1442                                          pdo_pps_apdo_max_voltage(pdo[i]) ==
1443                                           pdo_pps_apdo_max_voltage(pdo[i - 1]) &&
1444                                          pdo_pps_apdo_max_current(pdo[i]) ==
1445                                           pdo_pps_apdo_max_current(pdo[i - 1]))
1446                                         return PDO_ERR_DUPE_PPS_APDO;
1447                                 break;
1448                         default:
1449                                 tcpm_log_force(port, " Unknown pdo type");
1450                         }
1451                 }
1452         }
1453
1454         return PDO_NO_ERR;
1455 }
1456
1457 static int tcpm_validate_caps(struct tcpm_port *port, const u32 *pdo,
1458                               unsigned int nr_pdo)
1459 {
1460         enum pdo_err err_index = tcpm_caps_err(port, pdo, nr_pdo);
1461
1462         if (err_index != PDO_NO_ERR) {
1463                 tcpm_log_force(port, " %s", pdo_err_msg[err_index]);
1464                 return -EINVAL;
1465         }
1466
1467         return 0;
1468 }
1469
1470 static int tcpm_altmode_enter(struct typec_altmode *altmode)
1471 {
1472         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
1473         u32 header;
1474
1475         mutex_lock(&port->lock);
1476         header = VDO(altmode->svid, 1, CMD_ENTER_MODE);
1477         header |= VDO_OPOS(altmode->mode);
1478
1479         tcpm_queue_vdm(port, header, NULL, 0);
1480         mod_delayed_work(port->wq, &port->vdm_state_machine, 0);
1481         mutex_unlock(&port->lock);
1482
1483         return 0;
1484 }
1485
1486 static int tcpm_altmode_exit(struct typec_altmode *altmode)
1487 {
1488         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
1489         u32 header;
1490
1491         mutex_lock(&port->lock);
1492         header = VDO(altmode->svid, 1, CMD_EXIT_MODE);
1493         header |= VDO_OPOS(altmode->mode);
1494
1495         tcpm_queue_vdm(port, header, NULL, 0);
1496         mod_delayed_work(port->wq, &port->vdm_state_machine, 0);
1497         mutex_unlock(&port->lock);
1498
1499         return 0;
1500 }
1501
1502 static int tcpm_altmode_vdm(struct typec_altmode *altmode,
1503                             u32 header, const u32 *data, int count)
1504 {
1505         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
1506
1507         mutex_lock(&port->lock);
1508         tcpm_queue_vdm(port, header, data, count - 1);
1509         mod_delayed_work(port->wq, &port->vdm_state_machine, 0);
1510         mutex_unlock(&port->lock);
1511
1512         return 0;
1513 }
1514
1515 static const struct typec_altmode_ops tcpm_altmode_ops = {
1516         .enter = tcpm_altmode_enter,
1517         .exit = tcpm_altmode_exit,
1518         .vdm = tcpm_altmode_vdm,
1519 };
1520
1521 /*
1522  * PD (data, control) command handling functions
1523  */
1524 static inline enum tcpm_state ready_state(struct tcpm_port *port)
1525 {
1526         if (port->pwr_role == TYPEC_SOURCE)
1527                 return SRC_READY;
1528         else
1529                 return SNK_READY;
1530 }
1531
1532 static int tcpm_pd_send_control(struct tcpm_port *port,
1533                                 enum pd_ctrl_msg_type type);
1534
1535 static void tcpm_handle_alert(struct tcpm_port *port, const __le32 *payload,
1536                               int cnt)
1537 {
1538         u32 p0 = le32_to_cpu(payload[0]);
1539         unsigned int type = usb_pd_ado_type(p0);
1540
1541         if (!type) {
1542                 tcpm_log(port, "Alert message received with no type");
1543                 return;
1544         }
1545
1546         /* Just handling non-battery alerts for now */
1547         if (!(type & USB_PD_ADO_TYPE_BATT_STATUS_CHANGE)) {
1548                 switch (port->state) {
1549                 case SRC_READY:
1550                 case SNK_READY:
1551                         tcpm_set_state(port, GET_STATUS_SEND, 0);
1552                         break;
1553                 default:
1554                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
1555                         break;
1556                 }
1557         }
1558 }
1559
1560 static void tcpm_pd_data_request(struct tcpm_port *port,
1561                                  const struct pd_message *msg)
1562 {
1563         enum pd_data_msg_type type = pd_header_type_le(msg->header);
1564         unsigned int cnt = pd_header_cnt_le(msg->header);
1565         unsigned int rev = pd_header_rev_le(msg->header);
1566         unsigned int i;
1567
1568         switch (type) {
1569         case PD_DATA_SOURCE_CAP:
1570                 if (port->pwr_role != TYPEC_SINK)
1571                         break;
1572
1573                 for (i = 0; i < cnt; i++)
1574                         port->source_caps[i] = le32_to_cpu(msg->payload[i]);
1575
1576                 port->nr_source_caps = cnt;
1577
1578                 tcpm_log_source_caps(port);
1579
1580                 tcpm_validate_caps(port, port->source_caps,
1581                                    port->nr_source_caps);
1582
1583                 /*
1584                  * Adjust revision in subsequent message headers, as required,
1585                  * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
1586                  * support Rev 1.0 so just do nothing in that scenario.
1587                  */
1588                 if (rev == PD_REV10)
1589                         break;
1590
1591                 if (rev < PD_MAX_REV)
1592                         port->negotiated_rev = rev;
1593
1594                 /*
1595                  * This message may be received even if VBUS is not
1596                  * present. This is quite unexpected; see USB PD
1597                  * specification, sections 8.3.3.6.3.1 and 8.3.3.6.3.2.
1598                  * However, at the same time, we must be ready to
1599                  * receive this message and respond to it 15ms after
1600                  * receiving PS_RDY during power swap operations, no matter
1601                  * if VBUS is available or not (USB PD specification,
1602                  * section 6.5.9.2).
1603                  * So we need to accept the message either way,
1604                  * but be prepared to keep waiting for VBUS after it was
1605                  * handled.
1606                  */
1607                 tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
1608                 break;
1609         case PD_DATA_REQUEST:
1610                 if (port->pwr_role != TYPEC_SOURCE ||
1611                     cnt != 1) {
1612                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1613                         break;
1614                 }
1615
1616                 /*
1617                  * Adjust revision in subsequent message headers, as required,
1618                  * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
1619                  * support Rev 1.0 so just reject in that scenario.
1620                  */
1621                 if (rev == PD_REV10) {
1622                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1623                         break;
1624                 }
1625
1626                 if (rev < PD_MAX_REV)
1627                         port->negotiated_rev = rev;
1628
1629                 port->sink_request = le32_to_cpu(msg->payload[0]);
1630                 tcpm_set_state(port, SRC_NEGOTIATE_CAPABILITIES, 0);
1631                 break;
1632         case PD_DATA_SINK_CAP:
1633                 /* We don't do anything with this at the moment... */
1634                 for (i = 0; i < cnt; i++)
1635                         port->sink_caps[i] = le32_to_cpu(msg->payload[i]);
1636                 port->nr_sink_caps = cnt;
1637                 break;
1638         case PD_DATA_VENDOR_DEF:
1639                 tcpm_handle_vdm_request(port, msg->payload, cnt);
1640                 break;
1641         case PD_DATA_BIST:
1642                 if (port->state == SRC_READY || port->state == SNK_READY) {
1643                         port->bist_request = le32_to_cpu(msg->payload[0]);
1644                         tcpm_set_state(port, BIST_RX, 0);
1645                 }
1646                 break;
1647         case PD_DATA_ALERT:
1648                 tcpm_handle_alert(port, msg->payload, cnt);
1649                 break;
1650         case PD_DATA_BATT_STATUS:
1651         case PD_DATA_GET_COUNTRY_INFO:
1652                 /* Currently unsupported */
1653                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
1654                 break;
1655         default:
1656                 tcpm_log(port, "Unhandled data message type %#x", type);
1657                 break;
1658         }
1659 }
1660
1661 static void tcpm_pps_complete(struct tcpm_port *port, int result)
1662 {
1663         if (port->pps_pending) {
1664                 port->pps_status = result;
1665                 port->pps_pending = false;
1666                 complete(&port->pps_complete);
1667         }
1668 }
1669
1670 static void tcpm_pd_ctrl_request(struct tcpm_port *port,
1671                                  const struct pd_message *msg)
1672 {
1673         enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
1674         enum tcpm_state next_state;
1675
1676         switch (type) {
1677         case PD_CTRL_GOOD_CRC:
1678         case PD_CTRL_PING:
1679                 break;
1680         case PD_CTRL_GET_SOURCE_CAP:
1681                 switch (port->state) {
1682                 case SRC_READY:
1683                 case SNK_READY:
1684                         tcpm_queue_message(port, PD_MSG_DATA_SOURCE_CAP);
1685                         break;
1686                 default:
1687                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1688                         break;
1689                 }
1690                 break;
1691         case PD_CTRL_GET_SINK_CAP:
1692                 switch (port->state) {
1693                 case SRC_READY:
1694                 case SNK_READY:
1695                         tcpm_queue_message(port, PD_MSG_DATA_SINK_CAP);
1696                         break;
1697                 default:
1698                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1699                         break;
1700                 }
1701                 break;
1702         case PD_CTRL_GOTO_MIN:
1703                 break;
1704         case PD_CTRL_PS_RDY:
1705                 switch (port->state) {
1706                 case SNK_TRANSITION_SINK:
1707                         if (port->vbus_present) {
1708                                 tcpm_set_current_limit(port,
1709                                                        port->current_limit,
1710                                                        port->supply_voltage);
1711                                 port->explicit_contract = true;
1712                                 tcpm_set_state(port, SNK_READY, 0);
1713                         } else {
1714                                 /*
1715                                  * Seen after power swap. Keep waiting for VBUS
1716                                  * in a transitional state.
1717                                  */
1718                                 tcpm_set_state(port,
1719                                                SNK_TRANSITION_SINK_VBUS, 0);
1720                         }
1721                         break;
1722                 case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
1723                         tcpm_set_state(port, PR_SWAP_SRC_SNK_SINK_ON, 0);
1724                         break;
1725                 case PR_SWAP_SNK_SRC_SINK_OFF:
1726                         tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON, 0);
1727                         break;
1728                 case VCONN_SWAP_WAIT_FOR_VCONN:
1729                         tcpm_set_state(port, VCONN_SWAP_TURN_OFF_VCONN, 0);
1730                         break;
1731                 default:
1732                         break;
1733                 }
1734                 break;
1735         case PD_CTRL_REJECT:
1736         case PD_CTRL_WAIT:
1737         case PD_CTRL_NOT_SUPP:
1738                 switch (port->state) {
1739                 case SNK_NEGOTIATE_CAPABILITIES:
1740                         /* USB PD specification, Figure 8-43 */
1741                         if (port->explicit_contract)
1742                                 next_state = SNK_READY;
1743                         else
1744                                 next_state = SNK_WAIT_CAPABILITIES;
1745                         tcpm_set_state(port, next_state, 0);
1746                         break;
1747                 case SNK_NEGOTIATE_PPS_CAPABILITIES:
1748                         /* Revert data back from any requested PPS updates */
1749                         port->pps_data.out_volt = port->supply_voltage;
1750                         port->pps_data.op_curr = port->current_limit;
1751                         port->pps_status = (type == PD_CTRL_WAIT ?
1752                                             -EAGAIN : -EOPNOTSUPP);
1753                         tcpm_set_state(port, SNK_READY, 0);
1754                         break;
1755                 case DR_SWAP_SEND:
1756                         port->swap_status = (type == PD_CTRL_WAIT ?
1757                                              -EAGAIN : -EOPNOTSUPP);
1758                         tcpm_set_state(port, DR_SWAP_CANCEL, 0);
1759                         break;
1760                 case PR_SWAP_SEND:
1761                         port->swap_status = (type == PD_CTRL_WAIT ?
1762                                              -EAGAIN : -EOPNOTSUPP);
1763                         tcpm_set_state(port, PR_SWAP_CANCEL, 0);
1764                         break;
1765                 case VCONN_SWAP_SEND:
1766                         port->swap_status = (type == PD_CTRL_WAIT ?
1767                                              -EAGAIN : -EOPNOTSUPP);
1768                         tcpm_set_state(port, VCONN_SWAP_CANCEL, 0);
1769                         break;
1770                 default:
1771                         break;
1772                 }
1773                 break;
1774         case PD_CTRL_ACCEPT:
1775                 switch (port->state) {
1776                 case SNK_NEGOTIATE_CAPABILITIES:
1777                         port->pps_data.active = false;
1778                         tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
1779                         break;
1780                 case SNK_NEGOTIATE_PPS_CAPABILITIES:
1781                         port->pps_data.active = true;
1782                         port->supply_voltage = port->pps_data.out_volt;
1783                         port->current_limit = port->pps_data.op_curr;
1784                         tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
1785                         break;
1786                 case SOFT_RESET_SEND:
1787                         port->message_id = 0;
1788                         port->rx_msgid = -1;
1789                         if (port->pwr_role == TYPEC_SOURCE)
1790                                 next_state = SRC_SEND_CAPABILITIES;
1791                         else
1792                                 next_state = SNK_WAIT_CAPABILITIES;
1793                         tcpm_set_state(port, next_state, 0);
1794                         break;
1795                 case DR_SWAP_SEND:
1796                         tcpm_set_state(port, DR_SWAP_CHANGE_DR, 0);
1797                         break;
1798                 case PR_SWAP_SEND:
1799                         tcpm_set_state(port, PR_SWAP_START, 0);
1800                         break;
1801                 case VCONN_SWAP_SEND:
1802                         tcpm_set_state(port, VCONN_SWAP_START, 0);
1803                         break;
1804                 default:
1805                         break;
1806                 }
1807                 break;
1808         case PD_CTRL_SOFT_RESET:
1809                 tcpm_set_state(port, SOFT_RESET, 0);
1810                 break;
1811         case PD_CTRL_DR_SWAP:
1812                 if (port->port_type != TYPEC_PORT_DRP) {
1813                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1814                         break;
1815                 }
1816                 /*
1817                  * XXX
1818                  * 6.3.9: If an alternate mode is active, a request to swap
1819                  * alternate modes shall trigger a port reset.
1820                  */
1821                 switch (port->state) {
1822                 case SRC_READY:
1823                 case SNK_READY:
1824                         tcpm_set_state(port, DR_SWAP_ACCEPT, 0);
1825                         break;
1826                 default:
1827                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
1828                         break;
1829                 }
1830                 break;
1831         case PD_CTRL_PR_SWAP:
1832                 if (port->port_type != TYPEC_PORT_DRP) {
1833                         tcpm_queue_message(port, PD_MSG_CTRL_REJECT);
1834                         break;
1835                 }
1836                 switch (port->state) {
1837                 case SRC_READY:
1838                 case SNK_READY:
1839                         tcpm_set_state(port, PR_SWAP_ACCEPT, 0);
1840                         break;
1841                 default:
1842                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
1843                         break;
1844                 }
1845                 break;
1846         case PD_CTRL_VCONN_SWAP:
1847                 switch (port->state) {
1848                 case SRC_READY:
1849                 case SNK_READY:
1850                         tcpm_set_state(port, VCONN_SWAP_ACCEPT, 0);
1851                         break;
1852                 default:
1853                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
1854                         break;
1855                 }
1856                 break;
1857         case PD_CTRL_GET_SOURCE_CAP_EXT:
1858         case PD_CTRL_GET_STATUS:
1859         case PD_CTRL_FR_SWAP:
1860         case PD_CTRL_GET_PPS_STATUS:
1861         case PD_CTRL_GET_COUNTRY_CODES:
1862                 /* Currently not supported */
1863                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
1864                 break;
1865         default:
1866                 tcpm_log(port, "Unhandled ctrl message type %#x", type);
1867                 break;
1868         }
1869 }
1870
1871 static void tcpm_pd_ext_msg_request(struct tcpm_port *port,
1872                                     const struct pd_message *msg)
1873 {
1874         enum pd_ext_msg_type type = pd_header_type_le(msg->header);
1875         unsigned int data_size = pd_ext_header_data_size_le(msg->ext_msg.header);
1876
1877         if (!(msg->ext_msg.header & PD_EXT_HDR_CHUNKED)) {
1878                 tcpm_log(port, "Unchunked extended messages unsupported");
1879                 return;
1880         }
1881
1882         if (data_size > PD_EXT_MAX_CHUNK_DATA) {
1883                 tcpm_log(port, "Chunk handling not yet supported");
1884                 return;
1885         }
1886
1887         switch (type) {
1888         case PD_EXT_STATUS:
1889                 /*
1890                  * If PPS related events raised then get PPS status to clear
1891                  * (see USB PD 3.0 Spec, 6.5.2.4)
1892                  */
1893                 if (msg->ext_msg.data[USB_PD_EXT_SDB_EVENT_FLAGS] &
1894                     USB_PD_EXT_SDB_PPS_EVENTS)
1895                         tcpm_set_state(port, GET_PPS_STATUS_SEND, 0);
1896                 else
1897                         tcpm_set_state(port, ready_state(port), 0);
1898                 break;
1899         case PD_EXT_PPS_STATUS:
1900                 /*
1901                  * For now the PPS status message is used to clear events
1902                  * and nothing more.
1903                  */
1904                 tcpm_set_state(port, ready_state(port), 0);
1905                 break;
1906         case PD_EXT_SOURCE_CAP_EXT:
1907         case PD_EXT_GET_BATT_CAP:
1908         case PD_EXT_GET_BATT_STATUS:
1909         case PD_EXT_BATT_CAP:
1910         case PD_EXT_GET_MANUFACTURER_INFO:
1911         case PD_EXT_MANUFACTURER_INFO:
1912         case PD_EXT_SECURITY_REQUEST:
1913         case PD_EXT_SECURITY_RESPONSE:
1914         case PD_EXT_FW_UPDATE_REQUEST:
1915         case PD_EXT_FW_UPDATE_RESPONSE:
1916         case PD_EXT_COUNTRY_INFO:
1917         case PD_EXT_COUNTRY_CODES:
1918                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
1919                 break;
1920         default:
1921                 tcpm_log(port, "Unhandled extended message type %#x", type);
1922                 break;
1923         }
1924 }
1925
1926 static void tcpm_pd_rx_handler(struct work_struct *work)
1927 {
1928         struct pd_rx_event *event = container_of(work,
1929                                                  struct pd_rx_event, work);
1930         const struct pd_message *msg = &event->msg;
1931         unsigned int cnt = pd_header_cnt_le(msg->header);
1932         struct tcpm_port *port = event->port;
1933
1934         mutex_lock(&port->lock);
1935
1936         tcpm_log(port, "PD RX, header: %#x [%d]", le16_to_cpu(msg->header),
1937                  port->attached);
1938
1939         if (port->attached) {
1940                 enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
1941                 unsigned int msgid = pd_header_msgid_le(msg->header);
1942
1943                 /*
1944                  * USB PD standard, 6.6.1.2:
1945                  * "... if MessageID value in a received Message is the
1946                  * same as the stored value, the receiver shall return a
1947                  * GoodCRC Message with that MessageID value and drop
1948                  * the Message (this is a retry of an already received
1949                  * Message). Note: this shall not apply to the Soft_Reset
1950                  * Message which always has a MessageID value of zero."
1951                  */
1952                 if (msgid == port->rx_msgid && type != PD_CTRL_SOFT_RESET)
1953                         goto done;
1954                 port->rx_msgid = msgid;
1955
1956                 /*
1957                  * If both ends believe to be DFP/host, we have a data role
1958                  * mismatch.
1959                  */
1960                 if (!!(le16_to_cpu(msg->header) & PD_HEADER_DATA_ROLE) ==
1961                     (port->data_role == TYPEC_HOST)) {
1962                         tcpm_log(port,
1963                                  "Data role mismatch, initiating error recovery");
1964                         tcpm_set_state(port, ERROR_RECOVERY, 0);
1965                 } else {
1966                         if (msg->header & PD_HEADER_EXT_HDR)
1967                                 tcpm_pd_ext_msg_request(port, msg);
1968                         else if (cnt)
1969                                 tcpm_pd_data_request(port, msg);
1970                         else
1971                                 tcpm_pd_ctrl_request(port, msg);
1972                 }
1973         }
1974
1975 done:
1976         mutex_unlock(&port->lock);
1977         kfree(event);
1978 }
1979
1980 void tcpm_pd_receive(struct tcpm_port *port, const struct pd_message *msg)
1981 {
1982         struct pd_rx_event *event;
1983
1984         event = kzalloc(sizeof(*event), GFP_ATOMIC);
1985         if (!event)
1986                 return;
1987
1988         INIT_WORK(&event->work, tcpm_pd_rx_handler);
1989         event->port = port;
1990         memcpy(&event->msg, msg, sizeof(*msg));
1991         queue_work(port->wq, &event->work);
1992 }
1993 EXPORT_SYMBOL_GPL(tcpm_pd_receive);
1994
1995 static int tcpm_pd_send_control(struct tcpm_port *port,
1996                                 enum pd_ctrl_msg_type type)
1997 {
1998         struct pd_message msg;
1999
2000         memset(&msg, 0, sizeof(msg));
2001         msg.header = PD_HEADER_LE(type, port->pwr_role,
2002                                   port->data_role,
2003                                   port->negotiated_rev,
2004                                   port->message_id, 0);
2005
2006         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2007 }
2008
2009 /*
2010  * Send queued message without affecting state.
2011  * Return true if state machine should go back to sleep,
2012  * false otherwise.
2013  */
2014 static bool tcpm_send_queued_message(struct tcpm_port *port)
2015 {
2016         enum pd_msg_request queued_message;
2017
2018         do {
2019                 queued_message = port->queued_message;
2020                 port->queued_message = PD_MSG_NONE;
2021
2022                 switch (queued_message) {
2023                 case PD_MSG_CTRL_WAIT:
2024                         tcpm_pd_send_control(port, PD_CTRL_WAIT);
2025                         break;
2026                 case PD_MSG_CTRL_REJECT:
2027                         tcpm_pd_send_control(port, PD_CTRL_REJECT);
2028                         break;
2029                 case PD_MSG_CTRL_NOT_SUPP:
2030                         tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP);
2031                         break;
2032                 case PD_MSG_DATA_SINK_CAP:
2033                         tcpm_pd_send_sink_caps(port);
2034                         break;
2035                 case PD_MSG_DATA_SOURCE_CAP:
2036                         tcpm_pd_send_source_caps(port);
2037                         break;
2038                 default:
2039                         break;
2040                 }
2041         } while (port->queued_message != PD_MSG_NONE);
2042
2043         if (port->delayed_state != INVALID_STATE) {
2044                 if (time_is_after_jiffies(port->delayed_runtime)) {
2045                         mod_delayed_work(port->wq, &port->state_machine,
2046                                          port->delayed_runtime - jiffies);
2047                         return true;
2048                 }
2049                 port->delayed_state = INVALID_STATE;
2050         }
2051         return false;
2052 }
2053
2054 static int tcpm_pd_check_request(struct tcpm_port *port)
2055 {
2056         u32 pdo, rdo = port->sink_request;
2057         unsigned int max, op, pdo_max, index;
2058         enum pd_pdo_type type;
2059
2060         index = rdo_index(rdo);
2061         if (!index || index > port->nr_src_pdo)
2062                 return -EINVAL;
2063
2064         pdo = port->src_pdo[index - 1];
2065         type = pdo_type(pdo);
2066         switch (type) {
2067         case PDO_TYPE_FIXED:
2068         case PDO_TYPE_VAR:
2069                 max = rdo_max_current(rdo);
2070                 op = rdo_op_current(rdo);
2071                 pdo_max = pdo_max_current(pdo);
2072
2073                 if (op > pdo_max)
2074                         return -EINVAL;
2075                 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
2076                         return -EINVAL;
2077
2078                 if (type == PDO_TYPE_FIXED)
2079                         tcpm_log(port,
2080                                  "Requested %u mV, %u mA for %u / %u mA",
2081                                  pdo_fixed_voltage(pdo), pdo_max, op, max);
2082                 else
2083                         tcpm_log(port,
2084                                  "Requested %u -> %u mV, %u mA for %u / %u mA",
2085                                  pdo_min_voltage(pdo), pdo_max_voltage(pdo),
2086                                  pdo_max, op, max);
2087                 break;
2088         case PDO_TYPE_BATT:
2089                 max = rdo_max_power(rdo);
2090                 op = rdo_op_power(rdo);
2091                 pdo_max = pdo_max_power(pdo);
2092
2093                 if (op > pdo_max)
2094                         return -EINVAL;
2095                 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
2096                         return -EINVAL;
2097                 tcpm_log(port,
2098                          "Requested %u -> %u mV, %u mW for %u / %u mW",
2099                          pdo_min_voltage(pdo), pdo_max_voltage(pdo),
2100                          pdo_max, op, max);
2101                 break;
2102         default:
2103                 return -EINVAL;
2104         }
2105
2106         port->op_vsafe5v = index == 1;
2107
2108         return 0;
2109 }
2110
2111 #define min_power(x, y) min(pdo_max_power(x), pdo_max_power(y))
2112 #define min_current(x, y) min(pdo_max_current(x), pdo_max_current(y))
2113
2114 static int tcpm_pd_select_pdo(struct tcpm_port *port, int *sink_pdo,
2115                               int *src_pdo)
2116 {
2117         unsigned int i, j, max_src_mv = 0, min_src_mv = 0, max_mw = 0,
2118                      max_mv = 0, src_mw = 0, src_ma = 0, max_snk_mv = 0,
2119                      min_snk_mv = 0;
2120         int ret = -EINVAL;
2121
2122         port->pps_data.supported = false;
2123         port->usb_type = POWER_SUPPLY_USB_TYPE_PD;
2124
2125         /*
2126          * Select the source PDO providing the most power which has a
2127          * matchig sink cap.
2128          */
2129         for (i = 0; i < port->nr_source_caps; i++) {
2130                 u32 pdo = port->source_caps[i];
2131                 enum pd_pdo_type type = pdo_type(pdo);
2132
2133                 switch (type) {
2134                 case PDO_TYPE_FIXED:
2135                         max_src_mv = pdo_fixed_voltage(pdo);
2136                         min_src_mv = max_src_mv;
2137                         break;
2138                 case PDO_TYPE_BATT:
2139                 case PDO_TYPE_VAR:
2140                         max_src_mv = pdo_max_voltage(pdo);
2141                         min_src_mv = pdo_min_voltage(pdo);
2142                         break;
2143                 case PDO_TYPE_APDO:
2144                         if (pdo_apdo_type(pdo) == APDO_TYPE_PPS) {
2145                                 port->pps_data.supported = true;
2146                                 port->usb_type =
2147                                         POWER_SUPPLY_USB_TYPE_PD_PPS;
2148                         }
2149                         continue;
2150                 default:
2151                         tcpm_log(port, "Invalid source PDO type, ignoring");
2152                         continue;
2153                 }
2154
2155                 switch (type) {
2156                 case PDO_TYPE_FIXED:
2157                 case PDO_TYPE_VAR:
2158                         src_ma = pdo_max_current(pdo);
2159                         src_mw = src_ma * min_src_mv / 1000;
2160                         break;
2161                 case PDO_TYPE_BATT:
2162                         src_mw = pdo_max_power(pdo);
2163                         break;
2164                 case PDO_TYPE_APDO:
2165                         continue;
2166                 default:
2167                         tcpm_log(port, "Invalid source PDO type, ignoring");
2168                         continue;
2169                 }
2170
2171                 for (j = 0; j < port->nr_snk_pdo; j++) {
2172                         pdo = port->snk_pdo[j];
2173
2174                         switch (pdo_type(pdo)) {
2175                         case PDO_TYPE_FIXED:
2176                                 max_snk_mv = pdo_fixed_voltage(pdo);
2177                                 min_snk_mv = max_snk_mv;
2178                                 break;
2179                         case PDO_TYPE_BATT:
2180                         case PDO_TYPE_VAR:
2181                                 max_snk_mv = pdo_max_voltage(pdo);
2182                                 min_snk_mv = pdo_min_voltage(pdo);
2183                                 break;
2184                         case PDO_TYPE_APDO:
2185                                 continue;
2186                         default:
2187                                 tcpm_log(port, "Invalid sink PDO type, ignoring");
2188                                 continue;
2189                         }
2190
2191                         if (max_src_mv <= max_snk_mv &&
2192                                 min_src_mv >= min_snk_mv) {
2193                                 /* Prefer higher voltages if available */
2194                                 if ((src_mw == max_mw && min_src_mv > max_mv) ||
2195                                                         src_mw > max_mw) {
2196                                         *src_pdo = i;
2197                                         *sink_pdo = j;
2198                                         max_mw = src_mw;
2199                                         max_mv = min_src_mv;
2200                                         ret = 0;
2201                                 }
2202                         }
2203                 }
2204         }
2205
2206         return ret;
2207 }
2208
2209 #define min_pps_apdo_current(x, y)      \
2210         min(pdo_pps_apdo_max_current(x), pdo_pps_apdo_max_current(y))
2211
2212 static unsigned int tcpm_pd_select_pps_apdo(struct tcpm_port *port)
2213 {
2214         unsigned int i, j, max_mw = 0, max_mv = 0;
2215         unsigned int min_src_mv, max_src_mv, src_ma, src_mw;
2216         unsigned int min_snk_mv, max_snk_mv;
2217         unsigned int max_op_mv;
2218         u32 pdo, src, snk;
2219         unsigned int src_pdo = 0, snk_pdo = 0;
2220
2221         /*
2222          * Select the source PPS APDO providing the most power while staying
2223          * within the board's limits. We skip the first PDO as this is always
2224          * 5V 3A.
2225          */
2226         for (i = 1; i < port->nr_source_caps; ++i) {
2227                 pdo = port->source_caps[i];
2228
2229                 switch (pdo_type(pdo)) {
2230                 case PDO_TYPE_APDO:
2231                         if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
2232                                 tcpm_log(port, "Not PPS APDO (source), ignoring");
2233                                 continue;
2234                         }
2235
2236                         min_src_mv = pdo_pps_apdo_min_voltage(pdo);
2237                         max_src_mv = pdo_pps_apdo_max_voltage(pdo);
2238                         src_ma = pdo_pps_apdo_max_current(pdo);
2239                         src_mw = (src_ma * max_src_mv) / 1000;
2240
2241                         /*
2242                          * Now search through the sink PDOs to find a matching
2243                          * PPS APDO. Again skip the first sink PDO as this will
2244                          * always be 5V 3A.
2245                          */
2246                         for (j = 1; j < port->nr_snk_pdo; j++) {
2247                                 pdo = port->snk_pdo[j];
2248
2249                                 switch (pdo_type(pdo)) {
2250                                 case PDO_TYPE_APDO:
2251                                         if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
2252                                                 tcpm_log(port,
2253                                                          "Not PPS APDO (sink), ignoring");
2254                                                 continue;
2255                                         }
2256
2257                                         min_snk_mv =
2258                                                 pdo_pps_apdo_min_voltage(pdo);
2259                                         max_snk_mv =
2260                                                 pdo_pps_apdo_max_voltage(pdo);
2261                                         break;
2262                                 default:
2263                                         tcpm_log(port,
2264                                                  "Not APDO type (sink), ignoring");
2265                                         continue;
2266                                 }
2267
2268                                 if (min_src_mv <= max_snk_mv &&
2269                                     max_src_mv >= min_snk_mv) {
2270                                         max_op_mv = min(max_src_mv, max_snk_mv);
2271                                         src_mw = (max_op_mv * src_ma) / 1000;
2272                                         /* Prefer higher voltages if available */
2273                                         if ((src_mw == max_mw &&
2274                                              max_op_mv > max_mv) ||
2275                                             src_mw > max_mw) {
2276                                                 src_pdo = i;
2277                                                 snk_pdo = j;
2278                                                 max_mw = src_mw;
2279                                                 max_mv = max_op_mv;
2280                                         }
2281                                 }
2282                         }
2283
2284                         break;
2285                 default:
2286                         tcpm_log(port, "Not APDO type (source), ignoring");
2287                         continue;
2288                 }
2289         }
2290
2291         if (src_pdo) {
2292                 src = port->source_caps[src_pdo];
2293                 snk = port->snk_pdo[snk_pdo];
2294
2295                 port->pps_data.min_volt = max(pdo_pps_apdo_min_voltage(src),
2296                                               pdo_pps_apdo_min_voltage(snk));
2297                 port->pps_data.max_volt = min(pdo_pps_apdo_max_voltage(src),
2298                                               pdo_pps_apdo_max_voltage(snk));
2299                 port->pps_data.max_curr = min_pps_apdo_current(src, snk);
2300                 port->pps_data.out_volt = min(port->pps_data.max_volt,
2301                                               max(port->pps_data.min_volt,
2302                                                   port->pps_data.out_volt));
2303                 port->pps_data.op_curr = min(port->pps_data.max_curr,
2304                                              port->pps_data.op_curr);
2305         }
2306
2307         return src_pdo;
2308 }
2309
2310 static int tcpm_pd_build_request(struct tcpm_port *port, u32 *rdo)
2311 {
2312         unsigned int mv, ma, mw, flags;
2313         unsigned int max_ma, max_mw;
2314         enum pd_pdo_type type;
2315         u32 pdo, matching_snk_pdo;
2316         int src_pdo_index = 0;
2317         int snk_pdo_index = 0;
2318         int ret;
2319
2320         ret = tcpm_pd_select_pdo(port, &snk_pdo_index, &src_pdo_index);
2321         if (ret < 0)
2322                 return ret;
2323
2324         pdo = port->source_caps[src_pdo_index];
2325         matching_snk_pdo = port->snk_pdo[snk_pdo_index];
2326         type = pdo_type(pdo);
2327
2328         switch (type) {
2329         case PDO_TYPE_FIXED:
2330                 mv = pdo_fixed_voltage(pdo);
2331                 break;
2332         case PDO_TYPE_BATT:
2333         case PDO_TYPE_VAR:
2334                 mv = pdo_min_voltage(pdo);
2335                 break;
2336         default:
2337                 tcpm_log(port, "Invalid PDO selected!");
2338                 return -EINVAL;
2339         }
2340
2341         /* Select maximum available current within the sink pdo's limit */
2342         if (type == PDO_TYPE_BATT) {
2343                 mw = min_power(pdo, matching_snk_pdo);
2344                 ma = 1000 * mw / mv;
2345         } else {
2346                 ma = min_current(pdo, matching_snk_pdo);
2347                 mw = ma * mv / 1000;
2348         }
2349
2350         flags = RDO_USB_COMM | RDO_NO_SUSPEND;
2351
2352         /* Set mismatch bit if offered power is less than operating power */
2353         max_ma = ma;
2354         max_mw = mw;
2355         if (mw < port->operating_snk_mw) {
2356                 flags |= RDO_CAP_MISMATCH;
2357                 if (type == PDO_TYPE_BATT &&
2358                     (pdo_max_power(matching_snk_pdo) > pdo_max_power(pdo)))
2359                         max_mw = pdo_max_power(matching_snk_pdo);
2360                 else if (pdo_max_current(matching_snk_pdo) >
2361                          pdo_max_current(pdo))
2362                         max_ma = pdo_max_current(matching_snk_pdo);
2363         }
2364
2365         tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
2366                  port->cc_req, port->cc1, port->cc2, port->vbus_source,
2367                  port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
2368                  port->polarity);
2369
2370         if (type == PDO_TYPE_BATT) {
2371                 *rdo = RDO_BATT(src_pdo_index + 1, mw, max_mw, flags);
2372
2373                 tcpm_log(port, "Requesting PDO %d: %u mV, %u mW%s",
2374                          src_pdo_index, mv, mw,
2375                          flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
2376         } else {
2377                 *rdo = RDO_FIXED(src_pdo_index + 1, ma, max_ma, flags);
2378
2379                 tcpm_log(port, "Requesting PDO %d: %u mV, %u mA%s",
2380                          src_pdo_index, mv, ma,
2381                          flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
2382         }
2383
2384         port->current_limit = ma;
2385         port->supply_voltage = mv;
2386
2387         return 0;
2388 }
2389
2390 static int tcpm_pd_send_request(struct tcpm_port *port)
2391 {
2392         struct pd_message msg;
2393         int ret;
2394         u32 rdo;
2395
2396         ret = tcpm_pd_build_request(port, &rdo);
2397         if (ret < 0)
2398                 return ret;
2399
2400         memset(&msg, 0, sizeof(msg));
2401         msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
2402                                   port->pwr_role,
2403                                   port->data_role,
2404                                   port->negotiated_rev,
2405                                   port->message_id, 1);
2406         msg.payload[0] = cpu_to_le32(rdo);
2407
2408         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2409 }
2410
2411 static int tcpm_pd_build_pps_request(struct tcpm_port *port, u32 *rdo)
2412 {
2413         unsigned int out_mv, op_ma, op_mw, max_mv, max_ma, flags;
2414         enum pd_pdo_type type;
2415         unsigned int src_pdo_index;
2416         u32 pdo;
2417
2418         src_pdo_index = tcpm_pd_select_pps_apdo(port);
2419         if (!src_pdo_index)
2420                 return -EOPNOTSUPP;
2421
2422         pdo = port->source_caps[src_pdo_index];
2423         type = pdo_type(pdo);
2424
2425         switch (type) {
2426         case PDO_TYPE_APDO:
2427                 if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
2428                         tcpm_log(port, "Invalid APDO selected!");
2429                         return -EINVAL;
2430                 }
2431                 max_mv = port->pps_data.max_volt;
2432                 max_ma = port->pps_data.max_curr;
2433                 out_mv = port->pps_data.out_volt;
2434                 op_ma = port->pps_data.op_curr;
2435                 break;
2436         default:
2437                 tcpm_log(port, "Invalid PDO selected!");
2438                 return -EINVAL;
2439         }
2440
2441         flags = RDO_USB_COMM | RDO_NO_SUSPEND;
2442
2443         op_mw = (op_ma * out_mv) / 1000;
2444         if (op_mw < port->operating_snk_mw) {
2445                 /*
2446                  * Try raising current to meet power needs. If that's not enough
2447                  * then try upping the voltage. If that's still not enough
2448                  * then we've obviously chosen a PPS APDO which really isn't
2449                  * suitable so abandon ship.
2450                  */
2451                 op_ma = (port->operating_snk_mw * 1000) / out_mv;
2452                 if ((port->operating_snk_mw * 1000) % out_mv)
2453                         ++op_ma;
2454                 op_ma += RDO_PROG_CURR_MA_STEP - (op_ma % RDO_PROG_CURR_MA_STEP);
2455
2456                 if (op_ma > max_ma) {
2457                         op_ma = max_ma;
2458                         out_mv = (port->operating_snk_mw * 1000) / op_ma;
2459                         if ((port->operating_snk_mw * 1000) % op_ma)
2460                                 ++out_mv;
2461                         out_mv += RDO_PROG_VOLT_MV_STEP -
2462                                   (out_mv % RDO_PROG_VOLT_MV_STEP);
2463
2464                         if (out_mv > max_mv) {
2465                                 tcpm_log(port, "Invalid PPS APDO selected!");
2466                                 return -EINVAL;
2467                         }
2468                 }
2469         }
2470
2471         tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
2472                  port->cc_req, port->cc1, port->cc2, port->vbus_source,
2473                  port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
2474                  port->polarity);
2475
2476         *rdo = RDO_PROG(src_pdo_index + 1, out_mv, op_ma, flags);
2477
2478         tcpm_log(port, "Requesting APDO %d: %u mV, %u mA",
2479                  src_pdo_index, out_mv, op_ma);
2480
2481         port->pps_data.op_curr = op_ma;
2482         port->pps_data.out_volt = out_mv;
2483
2484         return 0;
2485 }
2486
2487 static int tcpm_pd_send_pps_request(struct tcpm_port *port)
2488 {
2489         struct pd_message msg;
2490         int ret;
2491         u32 rdo;
2492
2493         ret = tcpm_pd_build_pps_request(port, &rdo);
2494         if (ret < 0)
2495                 return ret;
2496
2497         memset(&msg, 0, sizeof(msg));
2498         msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
2499                                   port->pwr_role,
2500                                   port->data_role,
2501                                   port->negotiated_rev,
2502                                   port->message_id, 1);
2503         msg.payload[0] = cpu_to_le32(rdo);
2504
2505         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2506 }
2507
2508 static int tcpm_set_vbus(struct tcpm_port *port, bool enable)
2509 {
2510         int ret;
2511
2512         if (enable && port->vbus_charge)
2513                 return -EINVAL;
2514
2515         tcpm_log(port, "vbus:=%d charge=%d", enable, port->vbus_charge);
2516
2517         ret = port->tcpc->set_vbus(port->tcpc, enable, port->vbus_charge);
2518         if (ret < 0)
2519                 return ret;
2520
2521         port->vbus_source = enable;
2522         return 0;
2523 }
2524
2525 static int tcpm_set_charge(struct tcpm_port *port, bool charge)
2526 {
2527         int ret;
2528
2529         if (charge && port->vbus_source)
2530                 return -EINVAL;
2531
2532         if (charge != port->vbus_charge) {
2533                 tcpm_log(port, "vbus=%d charge:=%d", port->vbus_source, charge);
2534                 ret = port->tcpc->set_vbus(port->tcpc, port->vbus_source,
2535                                            charge);
2536                 if (ret < 0)
2537                         return ret;
2538         }
2539         port->vbus_charge = charge;
2540         return 0;
2541 }
2542
2543 static bool tcpm_start_drp_toggling(struct tcpm_port *port,
2544                                     enum typec_cc_status cc)
2545 {
2546         int ret;
2547
2548         if (port->tcpc->start_drp_toggling &&
2549             port->port_type == TYPEC_PORT_DRP) {
2550                 tcpm_log_force(port, "Start DRP toggling");
2551                 ret = port->tcpc->start_drp_toggling(port->tcpc, cc);
2552                 if (!ret)
2553                         return true;
2554         }
2555
2556         return false;
2557 }
2558
2559 static void tcpm_set_cc(struct tcpm_port *port, enum typec_cc_status cc)
2560 {
2561         tcpm_log(port, "cc:=%d", cc);
2562         port->cc_req = cc;
2563         port->tcpc->set_cc(port->tcpc, cc);
2564 }
2565
2566 static int tcpm_init_vbus(struct tcpm_port *port)
2567 {
2568         int ret;
2569
2570         ret = port->tcpc->set_vbus(port->tcpc, false, false);
2571         port->vbus_source = false;
2572         port->vbus_charge = false;
2573         return ret;
2574 }
2575
2576 static int tcpm_init_vconn(struct tcpm_port *port)
2577 {
2578         int ret;
2579
2580         ret = port->tcpc->set_vconn(port->tcpc, false);
2581         port->vconn_role = TYPEC_SINK;
2582         return ret;
2583 }
2584
2585 static void tcpm_typec_connect(struct tcpm_port *port)
2586 {
2587         if (!port->connected) {
2588                 /* Make sure we don't report stale identity information */
2589                 memset(&port->partner_ident, 0, sizeof(port->partner_ident));
2590                 port->partner_desc.usb_pd = port->pd_capable;
2591                 if (tcpm_port_is_debug(port))
2592                         port->partner_desc.accessory = TYPEC_ACCESSORY_DEBUG;
2593                 else if (tcpm_port_is_audio(port))
2594                         port->partner_desc.accessory = TYPEC_ACCESSORY_AUDIO;
2595                 else
2596                         port->partner_desc.accessory = TYPEC_ACCESSORY_NONE;
2597                 port->partner = typec_register_partner(port->typec_port,
2598                                                        &port->partner_desc);
2599                 port->connected = true;
2600         }
2601 }
2602
2603 static int tcpm_src_attach(struct tcpm_port *port)
2604 {
2605         enum typec_cc_polarity polarity =
2606                                 port->cc2 == TYPEC_CC_RD ? TYPEC_POLARITY_CC2
2607                                                          : TYPEC_POLARITY_CC1;
2608         int ret;
2609
2610         if (port->attached)
2611                 return 0;
2612
2613         ret = tcpm_set_polarity(port, polarity);
2614         if (ret < 0)
2615                 return ret;
2616
2617         ret = tcpm_set_roles(port, true, TYPEC_SOURCE, TYPEC_HOST);
2618         if (ret < 0)
2619                 return ret;
2620
2621         ret = port->tcpc->set_pd_rx(port->tcpc, true);
2622         if (ret < 0)
2623                 goto out_disable_mux;
2624
2625         /*
2626          * USB Type-C specification, version 1.2,
2627          * chapter 4.5.2.2.8.1 (Attached.SRC Requirements)
2628          * Enable VCONN only if the non-RD port is set to RA.
2629          */
2630         if ((polarity == TYPEC_POLARITY_CC1 && port->cc2 == TYPEC_CC_RA) ||
2631             (polarity == TYPEC_POLARITY_CC2 && port->cc1 == TYPEC_CC_RA)) {
2632                 ret = tcpm_set_vconn(port, true);
2633                 if (ret < 0)
2634                         goto out_disable_pd;
2635         }
2636
2637         ret = tcpm_set_vbus(port, true);
2638         if (ret < 0)
2639                 goto out_disable_vconn;
2640
2641         port->pd_capable = false;
2642
2643         port->partner = NULL;
2644
2645         port->attached = true;
2646         port->send_discover = true;
2647
2648         return 0;
2649
2650 out_disable_vconn:
2651         tcpm_set_vconn(port, false);
2652 out_disable_pd:
2653         port->tcpc->set_pd_rx(port->tcpc, false);
2654 out_disable_mux:
2655         tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
2656                      TYPEC_ORIENTATION_NONE);
2657         return ret;
2658 }
2659
2660 static void tcpm_typec_disconnect(struct tcpm_port *port)
2661 {
2662         if (port->connected) {
2663                 typec_unregister_partner(port->partner);
2664                 port->partner = NULL;
2665                 port->connected = false;
2666         }
2667 }
2668
2669 static void tcpm_unregister_altmodes(struct tcpm_port *port)
2670 {
2671         struct pd_mode_data *modep = &port->mode_data;
2672         int i;
2673
2674         for (i = 0; i < modep->altmodes; i++) {
2675                 typec_unregister_altmode(port->partner_altmode[i]);
2676                 port->partner_altmode[i] = NULL;
2677         }
2678
2679         memset(modep, 0, sizeof(*modep));
2680 }
2681
2682 static void tcpm_reset_port(struct tcpm_port *port)
2683 {
2684         tcpm_unregister_altmodes(port);
2685         tcpm_typec_disconnect(port);
2686         port->attached = false;
2687         port->pd_capable = false;
2688         port->pps_data.supported = false;
2689
2690         /*
2691          * First Rx ID should be 0; set this to a sentinel of -1 so that
2692          * we can check tcpm_pd_rx_handler() if we had seen it before.
2693          */
2694         port->rx_msgid = -1;
2695
2696         port->tcpc->set_pd_rx(port->tcpc, false);
2697         tcpm_init_vbus(port);   /* also disables charging */
2698         tcpm_init_vconn(port);
2699         tcpm_set_current_limit(port, 0, 0);
2700         tcpm_set_polarity(port, TYPEC_POLARITY_CC1);
2701         tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
2702                      TYPEC_ORIENTATION_NONE);
2703         tcpm_set_attached_state(port, false);
2704         port->try_src_count = 0;
2705         port->try_snk_count = 0;
2706         port->usb_type = POWER_SUPPLY_USB_TYPE_C;
2707
2708         power_supply_changed(port->psy);
2709 }
2710
2711 static void tcpm_detach(struct tcpm_port *port)
2712 {
2713         if (!port->attached)
2714                 return;
2715
2716         if (tcpm_port_is_disconnected(port))
2717                 port->hard_reset_count = 0;
2718
2719         tcpm_reset_port(port);
2720 }
2721
2722 static void tcpm_src_detach(struct tcpm_port *port)
2723 {
2724         tcpm_detach(port);
2725 }
2726
2727 static int tcpm_snk_attach(struct tcpm_port *port)
2728 {
2729         int ret;
2730
2731         if (port->attached)
2732                 return 0;
2733
2734         ret = tcpm_set_polarity(port, port->cc2 != TYPEC_CC_OPEN ?
2735                                 TYPEC_POLARITY_CC2 : TYPEC_POLARITY_CC1);
2736         if (ret < 0)
2737                 return ret;
2738
2739         ret = tcpm_set_roles(port, true, TYPEC_SINK, TYPEC_DEVICE);
2740         if (ret < 0)
2741                 return ret;
2742
2743         port->pd_capable = false;
2744
2745         port->partner = NULL;
2746
2747         port->attached = true;
2748         port->send_discover = true;
2749
2750         return 0;
2751 }
2752
2753 static void tcpm_snk_detach(struct tcpm_port *port)
2754 {
2755         tcpm_detach(port);
2756 }
2757
2758 static int tcpm_acc_attach(struct tcpm_port *port)
2759 {
2760         int ret;
2761
2762         if (port->attached)
2763                 return 0;
2764
2765         ret = tcpm_set_roles(port, true, TYPEC_SOURCE, TYPEC_HOST);
2766         if (ret < 0)
2767                 return ret;
2768
2769         port->partner = NULL;
2770
2771         tcpm_typec_connect(port);
2772
2773         port->attached = true;
2774
2775         return 0;
2776 }
2777
2778 static void tcpm_acc_detach(struct tcpm_port *port)
2779 {
2780         tcpm_detach(port);
2781 }
2782
2783 static inline enum tcpm_state hard_reset_state(struct tcpm_port *port)
2784 {
2785         if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
2786                 return HARD_RESET_SEND;
2787         if (port->pd_capable)
2788                 return ERROR_RECOVERY;
2789         if (port->pwr_role == TYPEC_SOURCE)
2790                 return SRC_UNATTACHED;
2791         if (port->state == SNK_WAIT_CAPABILITIES)
2792                 return SNK_READY;
2793         return SNK_UNATTACHED;
2794 }
2795
2796 static inline enum tcpm_state unattached_state(struct tcpm_port *port)
2797 {
2798         if (port->port_type == TYPEC_PORT_DRP) {
2799                 if (port->pwr_role == TYPEC_SOURCE)
2800                         return SRC_UNATTACHED;
2801                 else
2802                         return SNK_UNATTACHED;
2803         } else if (port->port_type == TYPEC_PORT_SRC) {
2804                 return SRC_UNATTACHED;
2805         }
2806
2807         return SNK_UNATTACHED;
2808 }
2809
2810 static void tcpm_check_send_discover(struct tcpm_port *port)
2811 {
2812         if (port->data_role == TYPEC_HOST && port->send_discover &&
2813             port->pd_capable) {
2814                 tcpm_send_vdm(port, USB_SID_PD, CMD_DISCOVER_IDENT, NULL, 0);
2815                 port->send_discover = false;
2816         }
2817 }
2818
2819 static void tcpm_swap_complete(struct tcpm_port *port, int result)
2820 {
2821         if (port->swap_pending) {
2822                 port->swap_status = result;
2823                 port->swap_pending = false;
2824                 port->non_pd_role_swap = false;
2825                 complete(&port->swap_complete);
2826         }
2827 }
2828
2829 static enum typec_pwr_opmode tcpm_get_pwr_opmode(enum typec_cc_status cc)
2830 {
2831         switch (cc) {
2832         case TYPEC_CC_RP_1_5:
2833                 return TYPEC_PWR_MODE_1_5A;
2834         case TYPEC_CC_RP_3_0:
2835                 return TYPEC_PWR_MODE_3_0A;
2836         case TYPEC_CC_RP_DEF:
2837         default:
2838                 return TYPEC_PWR_MODE_USB;
2839         }
2840 }
2841
2842 static void run_state_machine(struct tcpm_port *port)
2843 {
2844         int ret;
2845         enum typec_pwr_opmode opmode;
2846         unsigned int msecs;
2847
2848         port->enter_state = port->state;
2849         switch (port->state) {
2850         case DRP_TOGGLING:
2851                 break;
2852         /* SRC states */
2853         case SRC_UNATTACHED:
2854                 if (!port->non_pd_role_swap)
2855                         tcpm_swap_complete(port, -ENOTCONN);
2856                 tcpm_src_detach(port);
2857                 if (tcpm_start_drp_toggling(port, tcpm_rp_cc(port))) {
2858                         tcpm_set_state(port, DRP_TOGGLING, 0);
2859                         break;
2860                 }
2861                 tcpm_set_cc(port, tcpm_rp_cc(port));
2862                 if (port->port_type == TYPEC_PORT_DRP)
2863                         tcpm_set_state(port, SNK_UNATTACHED, PD_T_DRP_SNK);
2864                 break;
2865         case SRC_ATTACH_WAIT:
2866                 if (tcpm_port_is_debug(port))
2867                         tcpm_set_state(port, DEBUG_ACC_ATTACHED,
2868                                        PD_T_CC_DEBOUNCE);
2869                 else if (tcpm_port_is_audio(port))
2870                         tcpm_set_state(port, AUDIO_ACC_ATTACHED,
2871                                        PD_T_CC_DEBOUNCE);
2872                 else if (tcpm_port_is_source(port))
2873                         tcpm_set_state(port,
2874                                        tcpm_try_snk(port) ? SNK_TRY
2875                                                           : SRC_ATTACHED,
2876                                        PD_T_CC_DEBOUNCE);
2877                 break;
2878
2879         case SNK_TRY:
2880                 port->try_snk_count++;
2881                 /*
2882                  * Requirements:
2883                  * - Do not drive vconn or vbus
2884                  * - Terminate CC pins (both) to Rd
2885                  * Action:
2886                  * - Wait for tDRPTry (PD_T_DRP_TRY).
2887                  *   Until then, ignore any state changes.
2888                  */
2889                 tcpm_set_cc(port, TYPEC_CC_RD);
2890                 tcpm_set_state(port, SNK_TRY_WAIT, PD_T_DRP_TRY);
2891                 break;
2892         case SNK_TRY_WAIT:
2893                 if (tcpm_port_is_sink(port)) {
2894                         tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE, 0);
2895                 } else {
2896                         tcpm_set_state(port, SRC_TRYWAIT, 0);
2897                         port->max_wait = 0;
2898                 }
2899                 break;
2900         case SNK_TRY_WAIT_DEBOUNCE:
2901                 tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS,
2902                                PD_T_PD_DEBOUNCE);
2903                 break;
2904         case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
2905                 if (port->vbus_present && tcpm_port_is_sink(port)) {
2906                         tcpm_set_state(port, SNK_ATTACHED, 0);
2907                 } else {
2908                         tcpm_set_state(port, SRC_TRYWAIT, 0);
2909                         port->max_wait = 0;
2910                 }
2911                 break;
2912         case SRC_TRYWAIT:
2913                 tcpm_set_cc(port, tcpm_rp_cc(port));
2914                 if (port->max_wait == 0) {
2915                         port->max_wait = jiffies +
2916                                          msecs_to_jiffies(PD_T_DRP_TRY);
2917                         tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
2918                                        PD_T_DRP_TRY);
2919                 } else {
2920                         if (time_is_after_jiffies(port->max_wait))
2921                                 tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
2922                                                jiffies_to_msecs(port->max_wait -
2923                                                                 jiffies));
2924                         else
2925                                 tcpm_set_state(port, SNK_UNATTACHED, 0);
2926                 }
2927                 break;
2928         case SRC_TRYWAIT_DEBOUNCE:
2929                 tcpm_set_state(port, SRC_ATTACHED, PD_T_CC_DEBOUNCE);
2930                 break;
2931         case SRC_TRYWAIT_UNATTACHED:
2932                 tcpm_set_state(port, SNK_UNATTACHED, 0);
2933                 break;
2934
2935         case SRC_ATTACHED:
2936                 ret = tcpm_src_attach(port);
2937                 tcpm_set_state(port, SRC_UNATTACHED,
2938                                ret < 0 ? 0 : PD_T_PS_SOURCE_ON);
2939                 break;
2940         case SRC_STARTUP:
2941                 opmode =  tcpm_get_pwr_opmode(tcpm_rp_cc(port));
2942                 typec_set_pwr_opmode(port->typec_port, opmode);
2943                 port->pwr_opmode = TYPEC_PWR_MODE_USB;
2944                 port->caps_count = 0;
2945                 port->negotiated_rev = PD_MAX_REV;
2946                 port->message_id = 0;
2947                 port->rx_msgid = -1;
2948                 port->explicit_contract = false;
2949                 tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
2950                 break;
2951         case SRC_SEND_CAPABILITIES:
2952                 port->caps_count++;
2953                 if (port->caps_count > PD_N_CAPS_COUNT) {
2954                         tcpm_set_state(port, SRC_READY, 0);
2955                         break;
2956                 }
2957                 ret = tcpm_pd_send_source_caps(port);
2958                 if (ret < 0) {
2959                         tcpm_set_state(port, SRC_SEND_CAPABILITIES,
2960                                        PD_T_SEND_SOURCE_CAP);
2961                 } else {
2962                         /*
2963                          * Per standard, we should clear the reset counter here.
2964                          * However, that can result in state machine hang-ups.
2965                          * Reset it only in READY state to improve stability.
2966                          */
2967                         /* port->hard_reset_count = 0; */
2968                         port->caps_count = 0;
2969                         port->pd_capable = true;
2970                         tcpm_set_state_cond(port, SRC_SEND_CAPABILITIES_TIMEOUT,
2971                                             PD_T_SEND_SOURCE_CAP);
2972                 }
2973                 break;
2974         case SRC_SEND_CAPABILITIES_TIMEOUT:
2975                 /*
2976                  * Error recovery for a PD_DATA_SOURCE_CAP reply timeout.
2977                  *
2978                  * PD 2.0 sinks are supposed to accept src-capabilities with a
2979                  * 3.0 header and simply ignore any src PDOs which the sink does
2980                  * not understand such as PPS but some 2.0 sinks instead ignore
2981                  * the entire PD_DATA_SOURCE_CAP message, causing contract
2982                  * negotiation to fail.
2983                  *
2984                  * After PD_N_HARD_RESET_COUNT hard-reset attempts, we try
2985                  * sending src-capabilities with a lower PD revision to
2986                  * make these broken sinks work.
2987                  */
2988                 if (port->hard_reset_count < PD_N_HARD_RESET_COUNT) {
2989                         tcpm_set_state(port, HARD_RESET_SEND, 0);
2990                 } else if (port->negotiated_rev > PD_REV20) {
2991                         port->negotiated_rev--;
2992                         port->hard_reset_count = 0;
2993                         tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
2994                 } else {
2995                         tcpm_set_state(port, hard_reset_state(port), 0);
2996                 }
2997                 break;
2998         case SRC_NEGOTIATE_CAPABILITIES:
2999                 ret = tcpm_pd_check_request(port);
3000                 if (ret < 0) {
3001                         tcpm_pd_send_control(port, PD_CTRL_REJECT);
3002                         if (!port->explicit_contract) {
3003                                 tcpm_set_state(port,
3004                                                SRC_WAIT_NEW_CAPABILITIES, 0);
3005                         } else {
3006                                 tcpm_set_state(port, SRC_READY, 0);
3007                         }
3008                 } else {
3009                         tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
3010                         tcpm_set_state(port, SRC_TRANSITION_SUPPLY,
3011                                        PD_T_SRC_TRANSITION);
3012                 }
3013                 break;
3014         case SRC_TRANSITION_SUPPLY:
3015                 /* XXX: regulator_set_voltage(vbus, ...) */
3016                 tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
3017                 port->explicit_contract = true;
3018                 typec_set_pwr_opmode(port->typec_port, TYPEC_PWR_MODE_PD);
3019                 port->pwr_opmode = TYPEC_PWR_MODE_PD;
3020                 tcpm_set_state_cond(port, SRC_READY, 0);
3021                 break;
3022         case SRC_READY:
3023 #if 1
3024                 port->hard_reset_count = 0;
3025 #endif
3026                 port->try_src_count = 0;
3027
3028                 tcpm_swap_complete(port, 0);
3029                 tcpm_typec_connect(port);
3030
3031                 tcpm_check_send_discover(port);
3032                 /*
3033                  * 6.3.5
3034                  * Sending ping messages is not necessary if
3035                  * - the source operates at vSafe5V
3036                  * or
3037                  * - The system is not operating in PD mode
3038                  * or
3039                  * - Both partners are connected using a Type-C connector
3040                  *
3041                  * There is no actual need to send PD messages since the local
3042                  * port type-c and the spec does not clearly say whether PD is
3043                  * possible when type-c is connected to Type-A/B
3044                  */
3045                 break;
3046         case SRC_WAIT_NEW_CAPABILITIES:
3047                 /* Nothing to do... */
3048                 break;
3049
3050         /* SNK states */
3051         case SNK_UNATTACHED:
3052                 if (!port->non_pd_role_swap)
3053                         tcpm_swap_complete(port, -ENOTCONN);
3054                 tcpm_pps_complete(port, -ENOTCONN);
3055                 tcpm_snk_detach(port);
3056                 if (tcpm_start_drp_toggling(port, TYPEC_CC_RD)) {
3057                         tcpm_set_state(port, DRP_TOGGLING, 0);
3058                         break;
3059                 }
3060                 tcpm_set_cc(port, TYPEC_CC_RD);
3061                 if (port->port_type == TYPEC_PORT_DRP)
3062                         tcpm_set_state(port, SRC_UNATTACHED, PD_T_DRP_SRC);
3063                 break;
3064         case SNK_ATTACH_WAIT:
3065                 if ((port->cc1 == TYPEC_CC_OPEN &&
3066                      port->cc2 != TYPEC_CC_OPEN) ||
3067                     (port->cc1 != TYPEC_CC_OPEN &&
3068                      port->cc2 == TYPEC_CC_OPEN))
3069                         tcpm_set_state(port, SNK_DEBOUNCED,
3070                                        PD_T_CC_DEBOUNCE);
3071                 else if (tcpm_port_is_disconnected(port))
3072                         tcpm_set_state(port, SNK_UNATTACHED,
3073                                        PD_T_PD_DEBOUNCE);
3074                 break;
3075         case SNK_DEBOUNCED:
3076                 if (tcpm_port_is_disconnected(port))
3077                         tcpm_set_state(port, SNK_UNATTACHED,
3078                                        PD_T_PD_DEBOUNCE);
3079                 else if (port->vbus_present)
3080                         tcpm_set_state(port,
3081                                        tcpm_try_src(port) ? SRC_TRY
3082                                                           : SNK_ATTACHED,
3083                                        0);
3084                 else
3085                         /* Wait for VBUS, but not forever */
3086                         tcpm_set_state(port, PORT_RESET, PD_T_PS_SOURCE_ON);
3087                 break;
3088
3089         case SRC_TRY:
3090                 port->try_src_count++;
3091                 tcpm_set_cc(port, tcpm_rp_cc(port));
3092                 port->max_wait = 0;
3093                 tcpm_set_state(port, SRC_TRY_WAIT, 0);
3094                 break;
3095         case SRC_TRY_WAIT:
3096                 if (port->max_wait == 0) {
3097                         port->max_wait = jiffies +
3098                                          msecs_to_jiffies(PD_T_DRP_TRY);
3099                         msecs = PD_T_DRP_TRY;
3100                 } else {
3101                         if (time_is_after_jiffies(port->max_wait))
3102                                 msecs = jiffies_to_msecs(port->max_wait -
3103                                                          jiffies);
3104                         else
3105                                 msecs = 0;
3106                 }
3107                 tcpm_set_state(port, SNK_TRYWAIT, msecs);
3108                 break;
3109         case SRC_TRY_DEBOUNCE:
3110                 tcpm_set_state(port, SRC_ATTACHED, PD_T_PD_DEBOUNCE);
3111                 break;
3112         case SNK_TRYWAIT:
3113                 tcpm_set_cc(port, TYPEC_CC_RD);
3114                 tcpm_set_state(port, SNK_TRYWAIT_VBUS, PD_T_CC_DEBOUNCE);
3115                 break;
3116         case SNK_TRYWAIT_VBUS:
3117                 /*
3118                  * TCPM stays in this state indefinitely until VBUS
3119                  * is detected as long as Rp is not detected for
3120                  * more than a time period of tPDDebounce.
3121                  */
3122                 if (port->vbus_present && tcpm_port_is_sink(port)) {
3123                         tcpm_set_state(port, SNK_ATTACHED, 0);
3124                         break;
3125                 }
3126                 if (!tcpm_port_is_sink(port))
3127                         tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
3128                 break;
3129         case SNK_TRYWAIT_DEBOUNCE:
3130                 tcpm_set_state(port, SNK_UNATTACHED, PD_T_PD_DEBOUNCE);
3131                 break;
3132         case SNK_ATTACHED:
3133                 ret = tcpm_snk_attach(port);
3134                 if (ret < 0)
3135                         tcpm_set_state(port, SNK_UNATTACHED, 0);
3136                 else
3137                         tcpm_set_state(port, SNK_STARTUP, 0);
3138                 break;
3139         case SNK_STARTUP:
3140                 opmode =  tcpm_get_pwr_opmode(port->polarity ?
3141                                               port->cc2 : port->cc1);
3142                 typec_set_pwr_opmode(port->typec_port, opmode);
3143                 port->pwr_opmode = TYPEC_PWR_MODE_USB;
3144                 port->negotiated_rev = PD_MAX_REV;
3145                 port->message_id = 0;
3146                 port->rx_msgid = -1;
3147                 port->explicit_contract = false;