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