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