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