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