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