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