Linux 6.10-rc6
[linux-block.git] / drivers / usb / typec / tcpm / tcpm.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright 2015-2017 Google, Inc
4  *
5  * USB Power Delivery protocol stack.
6  */
7
8 #include <linux/completion.h>
9 #include <linux/debugfs.h>
10 #include <linux/device.h>
11 #include <linux/hrtimer.h>
12 #include <linux/jiffies.h>
13 #include <linux/kernel.h>
14 #include <linux/kthread.h>
15 #include <linux/module.h>
16 #include <linux/mutex.h>
17 #include <linux/power_supply.h>
18 #include <linux/proc_fs.h>
19 #include <linux/property.h>
20 #include <linux/sched/clock.h>
21 #include <linux/seq_file.h>
22 #include <linux/slab.h>
23 #include <linux/spinlock.h>
24 #include <linux/usb.h>
25 #include <linux/usb/pd.h>
26 #include <linux/usb/pd_ado.h>
27 #include <linux/usb/pd_bdo.h>
28 #include <linux/usb/pd_ext_sdb.h>
29 #include <linux/usb/pd_vdo.h>
30 #include <linux/usb/role.h>
31 #include <linux/usb/tcpm.h>
32 #include <linux/usb/typec_altmode.h>
33
34 #include <uapi/linux/sched/types.h>
35
36 #define FOREACH_STATE(S)                        \
37         S(INVALID_STATE),                       \
38         S(TOGGLING),                    \
39         S(CHECK_CONTAMINANT),                   \
40         S(SRC_UNATTACHED),                      \
41         S(SRC_ATTACH_WAIT),                     \
42         S(SRC_ATTACHED),                        \
43         S(SRC_STARTUP),                         \
44         S(SRC_SEND_CAPABILITIES),               \
45         S(SRC_SEND_CAPABILITIES_TIMEOUT),       \
46         S(SRC_NEGOTIATE_CAPABILITIES),          \
47         S(SRC_TRANSITION_SUPPLY),               \
48         S(SRC_READY),                           \
49         S(SRC_WAIT_NEW_CAPABILITIES),           \
50                                                 \
51         S(SNK_UNATTACHED),                      \
52         S(SNK_ATTACH_WAIT),                     \
53         S(SNK_DEBOUNCED),                       \
54         S(SNK_ATTACHED),                        \
55         S(SNK_STARTUP),                         \
56         S(SNK_DISCOVERY),                       \
57         S(SNK_DISCOVERY_DEBOUNCE),              \
58         S(SNK_DISCOVERY_DEBOUNCE_DONE),         \
59         S(SNK_WAIT_CAPABILITIES),               \
60         S(SNK_NEGOTIATE_CAPABILITIES),          \
61         S(SNK_NEGOTIATE_PPS_CAPABILITIES),      \
62         S(SNK_TRANSITION_SINK),                 \
63         S(SNK_TRANSITION_SINK_VBUS),            \
64         S(SNK_READY),                           \
65                                                 \
66         S(ACC_UNATTACHED),                      \
67         S(DEBUG_ACC_ATTACHED),                  \
68         S(AUDIO_ACC_ATTACHED),                  \
69         S(AUDIO_ACC_DEBOUNCE),                  \
70                                                 \
71         S(HARD_RESET_SEND),                     \
72         S(HARD_RESET_START),                    \
73         S(SRC_HARD_RESET_VBUS_OFF),             \
74         S(SRC_HARD_RESET_VBUS_ON),              \
75         S(SNK_HARD_RESET_SINK_OFF),             \
76         S(SNK_HARD_RESET_WAIT_VBUS),            \
77         S(SNK_HARD_RESET_SINK_ON),              \
78                                                 \
79         S(SOFT_RESET),                          \
80         S(SRC_SOFT_RESET_WAIT_SNK_TX),          \
81         S(SNK_SOFT_RESET),                      \
82         S(SOFT_RESET_SEND),                     \
83                                                 \
84         S(DR_SWAP_ACCEPT),                      \
85         S(DR_SWAP_SEND),                        \
86         S(DR_SWAP_SEND_TIMEOUT),                \
87         S(DR_SWAP_CANCEL),                      \
88         S(DR_SWAP_CHANGE_DR),                   \
89                                                 \
90         S(PR_SWAP_ACCEPT),                      \
91         S(PR_SWAP_SEND),                        \
92         S(PR_SWAP_SEND_TIMEOUT),                \
93         S(PR_SWAP_CANCEL),                      \
94         S(PR_SWAP_START),                       \
95         S(PR_SWAP_SRC_SNK_TRANSITION_OFF),      \
96         S(PR_SWAP_SRC_SNK_SOURCE_OFF),          \
97         S(PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED), \
98         S(PR_SWAP_SRC_SNK_SINK_ON),             \
99         S(PR_SWAP_SNK_SRC_SINK_OFF),            \
100         S(PR_SWAP_SNK_SRC_SOURCE_ON),           \
101         S(PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP),    \
102                                                 \
103         S(VCONN_SWAP_ACCEPT),                   \
104         S(VCONN_SWAP_SEND),                     \
105         S(VCONN_SWAP_SEND_TIMEOUT),             \
106         S(VCONN_SWAP_CANCEL),                   \
107         S(VCONN_SWAP_START),                    \
108         S(VCONN_SWAP_WAIT_FOR_VCONN),           \
109         S(VCONN_SWAP_TURN_ON_VCONN),            \
110         S(VCONN_SWAP_TURN_OFF_VCONN),           \
111         S(VCONN_SWAP_SEND_SOFT_RESET),          \
112                                                 \
113         S(FR_SWAP_SEND),                        \
114         S(FR_SWAP_SEND_TIMEOUT),                \
115         S(FR_SWAP_SNK_SRC_TRANSITION_TO_OFF),                   \
116         S(FR_SWAP_SNK_SRC_NEW_SINK_READY),              \
117         S(FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED), \
118         S(FR_SWAP_CANCEL),                      \
119                                                 \
120         S(SNK_TRY),                             \
121         S(SNK_TRY_WAIT),                        \
122         S(SNK_TRY_WAIT_DEBOUNCE),               \
123         S(SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS),    \
124         S(SRC_TRYWAIT),                         \
125         S(SRC_TRYWAIT_DEBOUNCE),                \
126         S(SRC_TRYWAIT_UNATTACHED),              \
127                                                 \
128         S(SRC_TRY),                             \
129         S(SRC_TRY_WAIT),                        \
130         S(SRC_TRY_DEBOUNCE),                    \
131         S(SNK_TRYWAIT),                         \
132         S(SNK_TRYWAIT_DEBOUNCE),                \
133         S(SNK_TRYWAIT_VBUS),                    \
134         S(BIST_RX),                             \
135                                                 \
136         S(GET_STATUS_SEND),                     \
137         S(GET_STATUS_SEND_TIMEOUT),             \
138         S(GET_PPS_STATUS_SEND),                 \
139         S(GET_PPS_STATUS_SEND_TIMEOUT),         \
140                                                 \
141         S(GET_SINK_CAP),                        \
142         S(GET_SINK_CAP_TIMEOUT),                \
143                                                 \
144         S(ERROR_RECOVERY),                      \
145         S(PORT_RESET),                          \
146         S(PORT_RESET_WAIT_OFF),                 \
147                                                 \
148         S(AMS_START),                           \
149         S(CHUNK_NOT_SUPP),                      \
150                                                 \
151         S(SRC_VDM_IDENTITY_REQUEST)
152
153 #define FOREACH_AMS(S)                          \
154         S(NONE_AMS),                            \
155         S(POWER_NEGOTIATION),                   \
156         S(GOTOMIN),                             \
157         S(SOFT_RESET_AMS),                      \
158         S(HARD_RESET),                          \
159         S(CABLE_RESET),                         \
160         S(GET_SOURCE_CAPABILITIES),             \
161         S(GET_SINK_CAPABILITIES),               \
162         S(POWER_ROLE_SWAP),                     \
163         S(FAST_ROLE_SWAP),                      \
164         S(DATA_ROLE_SWAP),                      \
165         S(VCONN_SWAP),                          \
166         S(SOURCE_ALERT),                        \
167         S(GETTING_SOURCE_EXTENDED_CAPABILITIES),\
168         S(GETTING_SOURCE_SINK_STATUS),          \
169         S(GETTING_BATTERY_CAPABILITIES),        \
170         S(GETTING_BATTERY_STATUS),              \
171         S(GETTING_MANUFACTURER_INFORMATION),    \
172         S(SECURITY),                            \
173         S(FIRMWARE_UPDATE),                     \
174         S(DISCOVER_IDENTITY),                   \
175         S(SOURCE_STARTUP_CABLE_PLUG_DISCOVER_IDENTITY), \
176         S(DISCOVER_SVIDS),                      \
177         S(DISCOVER_MODES),                      \
178         S(DFP_TO_UFP_ENTER_MODE),               \
179         S(DFP_TO_UFP_EXIT_MODE),                \
180         S(DFP_TO_CABLE_PLUG_ENTER_MODE),        \
181         S(DFP_TO_CABLE_PLUG_EXIT_MODE),         \
182         S(ATTENTION),                           \
183         S(BIST),                                \
184         S(UNSTRUCTURED_VDMS),                   \
185         S(STRUCTURED_VDMS),                     \
186         S(COUNTRY_INFO),                        \
187         S(COUNTRY_CODES)
188
189 #define GENERATE_ENUM(e)        e
190 #define GENERATE_STRING(s)      #s
191
192 enum tcpm_state {
193         FOREACH_STATE(GENERATE_ENUM)
194 };
195
196 static const char * const tcpm_states[] = {
197         FOREACH_STATE(GENERATE_STRING)
198 };
199
200 enum tcpm_ams {
201         FOREACH_AMS(GENERATE_ENUM)
202 };
203
204 static const char * const tcpm_ams_str[] = {
205         FOREACH_AMS(GENERATE_STRING)
206 };
207
208 enum vdm_states {
209         VDM_STATE_ERR_BUSY = -3,
210         VDM_STATE_ERR_SEND = -2,
211         VDM_STATE_ERR_TMOUT = -1,
212         VDM_STATE_DONE = 0,
213         /* Anything >0 represents an active state */
214         VDM_STATE_READY = 1,
215         VDM_STATE_BUSY = 2,
216         VDM_STATE_WAIT_RSP_BUSY = 3,
217         VDM_STATE_SEND_MESSAGE = 4,
218 };
219
220 enum pd_msg_request {
221         PD_MSG_NONE = 0,
222         PD_MSG_CTRL_REJECT,
223         PD_MSG_CTRL_WAIT,
224         PD_MSG_CTRL_NOT_SUPP,
225         PD_MSG_DATA_SINK_CAP,
226         PD_MSG_DATA_SOURCE_CAP,
227 };
228
229 enum adev_actions {
230         ADEV_NONE = 0,
231         ADEV_NOTIFY_USB_AND_QUEUE_VDM,
232         ADEV_QUEUE_VDM,
233         ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL,
234         ADEV_ATTENTION,
235 };
236
237 /*
238  * Initial current capability of the new source when vSafe5V is applied during PD3.0 Fast Role Swap.
239  * Based on "Table 6-14 Fixed Supply PDO - Sink" of "USB Power Delivery Specification Revision 3.0,
240  * Version 1.2"
241  */
242 enum frs_typec_current {
243         FRS_NOT_SUPPORTED,
244         FRS_DEFAULT_POWER,
245         FRS_5V_1P5A,
246         FRS_5V_3A,
247 };
248
249 /* Events from low level driver */
250
251 #define TCPM_CC_EVENT           BIT(0)
252 #define TCPM_VBUS_EVENT         BIT(1)
253 #define TCPM_RESET_EVENT        BIT(2)
254 #define TCPM_FRS_EVENT          BIT(3)
255 #define TCPM_SOURCING_VBUS      BIT(4)
256 #define TCPM_PORT_CLEAN         BIT(5)
257 #define TCPM_PORT_ERROR         BIT(6)
258
259 #define LOG_BUFFER_ENTRIES      1024
260 #define LOG_BUFFER_ENTRY_SIZE   128
261
262 /* Alternate mode support */
263
264 #define SVID_DISCOVERY_MAX      16
265 #define ALTMODE_DISCOVERY_MAX   (SVID_DISCOVERY_MAX * MODE_DISCOVERY_MAX)
266
267 #define GET_SINK_CAP_RETRY_MS   100
268 #define SEND_DISCOVER_RETRY_MS  100
269
270 struct pd_mode_data {
271         int svid_index;         /* current SVID index           */
272         int nsvids;
273         u16 svids[SVID_DISCOVERY_MAX];
274         int altmodes;           /* number of alternate modes    */
275         struct typec_altmode_desc altmode_desc[ALTMODE_DISCOVERY_MAX];
276 };
277
278 /*
279  * @min_volt: Actual min voltage at the local port
280  * @req_min_volt: Requested min voltage to the port partner
281  * @max_volt: Actual max voltage at the local port
282  * @req_max_volt: Requested max voltage to the port partner
283  * @max_curr: Actual max current at the local port
284  * @req_max_curr: Requested max current of the port partner
285  * @req_out_volt: Requested output voltage to the port partner
286  * @req_op_curr: Requested operating current to the port partner
287  * @supported: Parter has at least one APDO hence supports PPS
288  * @active: PPS mode is active
289  */
290 struct pd_pps_data {
291         u32 min_volt;
292         u32 req_min_volt;
293         u32 max_volt;
294         u32 req_max_volt;
295         u32 max_curr;
296         u32 req_max_curr;
297         u32 req_out_volt;
298         u32 req_op_curr;
299         bool supported;
300         bool active;
301 };
302
303 struct pd_data {
304         struct usb_power_delivery *pd;
305         struct usb_power_delivery_capabilities *source_cap;
306         struct usb_power_delivery_capabilities_desc source_desc;
307         struct usb_power_delivery_capabilities *sink_cap;
308         struct usb_power_delivery_capabilities_desc sink_desc;
309         unsigned int operating_snk_mw;
310 };
311
312 struct tcpm_port {
313         struct device *dev;
314
315         struct mutex lock;              /* tcpm state machine lock */
316         struct kthread_worker *wq;
317
318         struct typec_capability typec_caps;
319         struct typec_port *typec_port;
320
321         struct tcpc_dev *tcpc;
322         struct usb_role_switch *role_sw;
323
324         enum typec_role vconn_role;
325         enum typec_role pwr_role;
326         enum typec_data_role data_role;
327         enum typec_pwr_opmode pwr_opmode;
328
329         struct usb_pd_identity partner_ident;
330         struct typec_partner_desc partner_desc;
331         struct typec_partner *partner;
332
333         struct usb_pd_identity cable_ident;
334         struct typec_cable_desc cable_desc;
335         struct typec_cable *cable;
336         struct typec_plug_desc plug_prime_desc;
337         struct typec_plug *plug_prime;
338
339         enum typec_cc_status cc_req;
340         enum typec_cc_status src_rp;    /* work only if pd_supported == false */
341
342         enum typec_cc_status cc1;
343         enum typec_cc_status cc2;
344         enum typec_cc_polarity polarity;
345
346         bool attached;
347         bool connected;
348         bool registered;
349         bool pd_supported;
350         enum typec_port_type port_type;
351
352         /*
353          * Set to true when vbus is greater than VSAFE5V min.
354          * Set to false when vbus falls below vSinkDisconnect max threshold.
355          */
356         bool vbus_present;
357
358         /*
359          * Set to true when vbus is less than VSAFE0V max.
360          * Set to false when vbus is greater than VSAFE0V max.
361          */
362         bool vbus_vsafe0v;
363
364         bool vbus_never_low;
365         bool vbus_source;
366         bool vbus_charge;
367
368         /* Set to true when Discover_Identity Command is expected to be sent in Ready states. */
369         bool send_discover;
370         bool op_vsafe5v;
371
372         int try_role;
373         int try_snk_count;
374         int try_src_count;
375
376         enum pd_msg_request queued_message;
377
378         enum tcpm_state enter_state;
379         enum tcpm_state prev_state;
380         enum tcpm_state state;
381         enum tcpm_state delayed_state;
382         ktime_t delayed_runtime;
383         unsigned long delay_ms;
384
385         spinlock_t pd_event_lock;
386         u32 pd_events;
387
388         struct kthread_work event_work;
389         struct hrtimer state_machine_timer;
390         struct kthread_work state_machine;
391         struct hrtimer vdm_state_machine_timer;
392         struct kthread_work vdm_state_machine;
393         struct hrtimer enable_frs_timer;
394         struct kthread_work enable_frs;
395         struct hrtimer send_discover_timer;
396         struct kthread_work send_discover_work;
397         bool state_machine_running;
398         /* Set to true when VDM State Machine has following actions. */
399         bool vdm_sm_running;
400
401         struct completion tx_complete;
402         enum tcpm_transmit_status tx_status;
403
404         struct mutex swap_lock;         /* swap command lock */
405         bool swap_pending;
406         bool non_pd_role_swap;
407         struct completion swap_complete;
408         int swap_status;
409
410         unsigned int negotiated_rev;
411         unsigned int message_id;
412         unsigned int caps_count;
413         unsigned int hard_reset_count;
414         bool pd_capable;
415         bool explicit_contract;
416         unsigned int rx_msgid;
417
418         /* USB PD objects */
419         struct usb_power_delivery **pds;
420         struct pd_data **pd_list;
421         struct usb_power_delivery_capabilities *port_source_caps;
422         struct usb_power_delivery_capabilities *port_sink_caps;
423         struct usb_power_delivery *partner_pd;
424         struct usb_power_delivery_capabilities *partner_source_caps;
425         struct usb_power_delivery_capabilities *partner_sink_caps;
426         struct usb_power_delivery *selected_pd;
427
428         /* Partner capabilities/requests */
429         u32 sink_request;
430         u32 source_caps[PDO_MAX_OBJECTS];
431         unsigned int nr_source_caps;
432         u32 sink_caps[PDO_MAX_OBJECTS];
433         unsigned int nr_sink_caps;
434
435         /* Local capabilities */
436         unsigned int pd_count;
437         u32 src_pdo[PDO_MAX_OBJECTS];
438         unsigned int nr_src_pdo;
439         u32 snk_pdo[PDO_MAX_OBJECTS];
440         unsigned int nr_snk_pdo;
441         u32 snk_vdo_v1[VDO_MAX_OBJECTS];
442         unsigned int nr_snk_vdo_v1;
443         u32 snk_vdo[VDO_MAX_OBJECTS];
444         unsigned int nr_snk_vdo;
445
446         unsigned int operating_snk_mw;
447         bool update_sink_caps;
448
449         /* Requested current / voltage to the port partner */
450         u32 req_current_limit;
451         u32 req_supply_voltage;
452         /* Actual current / voltage limit of the local port */
453         u32 current_limit;
454         u32 supply_voltage;
455
456         /* Used to export TA voltage and current */
457         struct power_supply *psy;
458         struct power_supply_desc psy_desc;
459         enum power_supply_usb_type usb_type;
460
461         u32 bist_request;
462
463         /* PD state for Vendor Defined Messages */
464         enum vdm_states vdm_state;
465         u32 vdm_retries;
466         /* next Vendor Defined Message to send */
467         u32 vdo_data[VDO_MAX_SIZE];
468         u8 vdo_count;
469         /* VDO to retry if UFP responder replied busy */
470         u32 vdo_retry;
471
472         /* PPS */
473         struct pd_pps_data pps_data;
474         struct completion pps_complete;
475         bool pps_pending;
476         int pps_status;
477
478         /* Alternate mode data */
479         struct pd_mode_data mode_data;
480         struct pd_mode_data mode_data_prime;
481         struct typec_altmode *partner_altmode[ALTMODE_DISCOVERY_MAX];
482         struct typec_altmode *plug_prime_altmode[ALTMODE_DISCOVERY_MAX];
483         struct typec_altmode *port_altmode[ALTMODE_DISCOVERY_MAX];
484
485         /* Deadline in jiffies to exit src_try_wait state */
486         unsigned long max_wait;
487
488         /* port belongs to a self powered device */
489         bool self_powered;
490
491         /* Sink FRS */
492         enum frs_typec_current new_source_frs_current;
493
494         /* Sink caps have been queried */
495         bool sink_cap_done;
496
497         /* Collision Avoidance and Atomic Message Sequence */
498         enum tcpm_state upcoming_state;
499         enum tcpm_ams ams;
500         enum tcpm_ams next_ams;
501         bool in_ams;
502
503         /* Auto vbus discharge status */
504         bool auto_vbus_discharge_enabled;
505
506         /*
507          * When set, port requests PD_P_SNK_STDBY_MW upon entering SNK_DISCOVERY and
508          * the actual current limit after RX of PD_CTRL_PSRDY for PD link,
509          * SNK_READY for non-pd link.
510          */
511         bool slow_charger_loop;
512
513         /*
514          * When true indicates that the lower level drivers indicate potential presence
515          * of contaminant in the connector pins based on the tcpm state machine
516          * transitions.
517          */
518         bool potential_contaminant;
519
520         /* SOP* Related Fields */
521         /*
522          * Flag to determine if SOP' Discover Identity is available. The flag
523          * is set if Discover Identity on SOP' does not immediately follow
524          * Discover Identity on SOP.
525          */
526         bool send_discover_prime;
527         /*
528          * tx_sop_type determines which SOP* a message is being sent on.
529          * For messages that are queued and not sent immediately such as in
530          * tcpm_queue_message or messages that send after state changes,
531          * the tx_sop_type is set accordingly.
532          */
533         enum tcpm_transmit_type tx_sop_type;
534         /*
535          * Prior to discovering the port partner's Specification Revision, the
536          * Vconn source and cable plug will use the lower of their two revisions.
537          *
538          * When the port partner's Specification Revision is discovered, the following
539          * rules are put in place.
540          *      1. If the cable revision (1) is lower than the revision negotiated
541          * between the port and partner (2), the port and partner will communicate
542          * on revision (2), but the port and cable will communicate on revision (1).
543          *      2. If the cable revision (1) is higher than the revision negotiated
544          * between the port and partner (2), the port and partner will communicate
545          * on revision (2), and the port and cable will communicate on revision (2)
546          * as well.
547          */
548         unsigned int negotiated_rev_prime;
549         /*
550          * Each SOP* type must maintain their own tx and rx message IDs
551          */
552         unsigned int message_id_prime;
553         unsigned int rx_msgid_prime;
554 #ifdef CONFIG_DEBUG_FS
555         struct dentry *dentry;
556         struct mutex logbuffer_lock;    /* log buffer access lock */
557         int logbuffer_head;
558         int logbuffer_tail;
559         u8 *logbuffer[LOG_BUFFER_ENTRIES];
560 #endif
561 };
562
563 struct pd_rx_event {
564         struct kthread_work work;
565         struct tcpm_port *port;
566         struct pd_message msg;
567         enum tcpm_transmit_type rx_sop_type;
568 };
569
570 static const char * const pd_rev[] = {
571         [PD_REV10]              = "rev1",
572         [PD_REV20]              = "rev2",
573         [PD_REV30]              = "rev3",
574 };
575
576 #define tcpm_cc_is_sink(cc) \
577         ((cc) == TYPEC_CC_RP_DEF || (cc) == TYPEC_CC_RP_1_5 || \
578          (cc) == TYPEC_CC_RP_3_0)
579
580 /* As long as cc is pulled up, we can consider it as sink. */
581 #define tcpm_port_is_sink(port) \
582         (tcpm_cc_is_sink((port)->cc1) || tcpm_cc_is_sink((port)->cc2))
583
584 #define tcpm_cc_is_source(cc) ((cc) == TYPEC_CC_RD)
585 #define tcpm_cc_is_audio(cc) ((cc) == TYPEC_CC_RA)
586 #define tcpm_cc_is_open(cc) ((cc) == TYPEC_CC_OPEN)
587
588 #define tcpm_port_is_source(port) \
589         ((tcpm_cc_is_source((port)->cc1) && \
590          !tcpm_cc_is_source((port)->cc2)) || \
591          (tcpm_cc_is_source((port)->cc2) && \
592           !tcpm_cc_is_source((port)->cc1)))
593
594 #define tcpm_port_is_debug(port) \
595         (tcpm_cc_is_source((port)->cc1) && tcpm_cc_is_source((port)->cc2))
596
597 #define tcpm_port_is_audio(port) \
598         (tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_audio((port)->cc2))
599
600 #define tcpm_port_is_audio_detached(port) \
601         ((tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_open((port)->cc2)) || \
602          (tcpm_cc_is_audio((port)->cc2) && tcpm_cc_is_open((port)->cc1)))
603
604 #define tcpm_try_snk(port) \
605         ((port)->try_snk_count == 0 && (port)->try_role == TYPEC_SINK && \
606         (port)->port_type == TYPEC_PORT_DRP)
607
608 #define tcpm_try_src(port) \
609         ((port)->try_src_count == 0 && (port)->try_role == TYPEC_SOURCE && \
610         (port)->port_type == TYPEC_PORT_DRP)
611
612 #define tcpm_data_role_for_source(port) \
613         ((port)->typec_caps.data == TYPEC_PORT_UFP ? \
614         TYPEC_DEVICE : TYPEC_HOST)
615
616 #define tcpm_data_role_for_sink(port) \
617         ((port)->typec_caps.data == TYPEC_PORT_DFP ? \
618         TYPEC_HOST : TYPEC_DEVICE)
619
620 #define tcpm_sink_tx_ok(port) \
621         (tcpm_port_is_sink(port) && \
622         ((port)->cc1 == TYPEC_CC_RP_3_0 || (port)->cc2 == TYPEC_CC_RP_3_0))
623
624 #define tcpm_wait_for_discharge(port) \
625         (((port)->auto_vbus_discharge_enabled && !(port)->vbus_vsafe0v) ? PD_T_SAFE_0V : 0)
626
627 static enum tcpm_state tcpm_default_state(struct tcpm_port *port)
628 {
629         if (port->port_type == TYPEC_PORT_DRP) {
630                 if (port->try_role == TYPEC_SINK)
631                         return SNK_UNATTACHED;
632                 else if (port->try_role == TYPEC_SOURCE)
633                         return SRC_UNATTACHED;
634                 /* Fall through to return SRC_UNATTACHED */
635         } else if (port->port_type == TYPEC_PORT_SNK) {
636                 return SNK_UNATTACHED;
637         }
638         return SRC_UNATTACHED;
639 }
640
641 static bool tcpm_port_is_disconnected(struct tcpm_port *port)
642 {
643         return (!port->attached && port->cc1 == TYPEC_CC_OPEN &&
644                 port->cc2 == TYPEC_CC_OPEN) ||
645                (port->attached && ((port->polarity == TYPEC_POLARITY_CC1 &&
646                                     port->cc1 == TYPEC_CC_OPEN) ||
647                                    (port->polarity == TYPEC_POLARITY_CC2 &&
648                                     port->cc2 == TYPEC_CC_OPEN)));
649 }
650
651 /*
652  * Logging
653  */
654
655 #ifdef CONFIG_DEBUG_FS
656
657 static bool tcpm_log_full(struct tcpm_port *port)
658 {
659         return port->logbuffer_tail ==
660                 (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
661 }
662
663 __printf(2, 0)
664 static void _tcpm_log(struct tcpm_port *port, const char *fmt, va_list args)
665 {
666         char tmpbuffer[LOG_BUFFER_ENTRY_SIZE];
667         u64 ts_nsec = local_clock();
668         unsigned long rem_nsec;
669
670         mutex_lock(&port->logbuffer_lock);
671         if (!port->logbuffer[port->logbuffer_head]) {
672                 port->logbuffer[port->logbuffer_head] =
673                                 kzalloc(LOG_BUFFER_ENTRY_SIZE, GFP_KERNEL);
674                 if (!port->logbuffer[port->logbuffer_head]) {
675                         mutex_unlock(&port->logbuffer_lock);
676                         return;
677                 }
678         }
679
680         vsnprintf(tmpbuffer, sizeof(tmpbuffer), fmt, args);
681
682         if (tcpm_log_full(port)) {
683                 port->logbuffer_head = max(port->logbuffer_head - 1, 0);
684                 strcpy(tmpbuffer, "overflow");
685         }
686
687         if (port->logbuffer_head < 0 ||
688             port->logbuffer_head >= LOG_BUFFER_ENTRIES) {
689                 dev_warn(port->dev,
690                          "Bad log buffer index %d\n", port->logbuffer_head);
691                 goto abort;
692         }
693
694         if (!port->logbuffer[port->logbuffer_head]) {
695                 dev_warn(port->dev,
696                          "Log buffer index %d is NULL\n", port->logbuffer_head);
697                 goto abort;
698         }
699
700         rem_nsec = do_div(ts_nsec, 1000000000);
701         scnprintf(port->logbuffer[port->logbuffer_head],
702                   LOG_BUFFER_ENTRY_SIZE, "[%5lu.%06lu] %s",
703                   (unsigned long)ts_nsec, rem_nsec / 1000,
704                   tmpbuffer);
705         port->logbuffer_head = (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
706
707 abort:
708         mutex_unlock(&port->logbuffer_lock);
709 }
710
711 __printf(2, 3)
712 static void tcpm_log(struct tcpm_port *port, const char *fmt, ...)
713 {
714         va_list args;
715
716         /* Do not log while disconnected and unattached */
717         if (tcpm_port_is_disconnected(port) &&
718             (port->state == SRC_UNATTACHED || port->state == SNK_UNATTACHED ||
719              port->state == TOGGLING || port->state == CHECK_CONTAMINANT))
720                 return;
721
722         va_start(args, fmt);
723         _tcpm_log(port, fmt, args);
724         va_end(args);
725 }
726
727 __printf(2, 3)
728 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...)
729 {
730         va_list args;
731
732         va_start(args, fmt);
733         _tcpm_log(port, fmt, args);
734         va_end(args);
735 }
736
737 static void tcpm_log_source_caps(struct tcpm_port *port)
738 {
739         int i;
740
741         for (i = 0; i < port->nr_source_caps; i++) {
742                 u32 pdo = port->source_caps[i];
743                 enum pd_pdo_type type = pdo_type(pdo);
744                 char msg[64];
745
746                 switch (type) {
747                 case PDO_TYPE_FIXED:
748                         scnprintf(msg, sizeof(msg),
749                                   "%u mV, %u mA [%s%s%s%s%s%s]",
750                                   pdo_fixed_voltage(pdo),
751                                   pdo_max_current(pdo),
752                                   (pdo & PDO_FIXED_DUAL_ROLE) ?
753                                                         "R" : "",
754                                   (pdo & PDO_FIXED_SUSPEND) ?
755                                                         "S" : "",
756                                   (pdo & PDO_FIXED_HIGHER_CAP) ?
757                                                         "H" : "",
758                                   (pdo & PDO_FIXED_USB_COMM) ?
759                                                         "U" : "",
760                                   (pdo & PDO_FIXED_DATA_SWAP) ?
761                                                         "D" : "",
762                                   (pdo & PDO_FIXED_EXTPOWER) ?
763                                                         "E" : "");
764                         break;
765                 case PDO_TYPE_VAR:
766                         scnprintf(msg, sizeof(msg),
767                                   "%u-%u mV, %u mA",
768                                   pdo_min_voltage(pdo),
769                                   pdo_max_voltage(pdo),
770                                   pdo_max_current(pdo));
771                         break;
772                 case PDO_TYPE_BATT:
773                         scnprintf(msg, sizeof(msg),
774                                   "%u-%u mV, %u mW",
775                                   pdo_min_voltage(pdo),
776                                   pdo_max_voltage(pdo),
777                                   pdo_max_power(pdo));
778                         break;
779                 case PDO_TYPE_APDO:
780                         if (pdo_apdo_type(pdo) == APDO_TYPE_PPS)
781                                 scnprintf(msg, sizeof(msg),
782                                           "%u-%u mV, %u mA",
783                                           pdo_pps_apdo_min_voltage(pdo),
784                                           pdo_pps_apdo_max_voltage(pdo),
785                                           pdo_pps_apdo_max_current(pdo));
786                         else
787                                 strcpy(msg, "undefined APDO");
788                         break;
789                 default:
790                         strcpy(msg, "undefined");
791                         break;
792                 }
793                 tcpm_log(port, " PDO %d: type %d, %s",
794                          i, type, msg);
795         }
796 }
797
798 static int tcpm_debug_show(struct seq_file *s, void *v)
799 {
800         struct tcpm_port *port = s->private;
801         int tail;
802
803         mutex_lock(&port->logbuffer_lock);
804         tail = port->logbuffer_tail;
805         while (tail != port->logbuffer_head) {
806                 seq_printf(s, "%s\n", port->logbuffer[tail]);
807                 tail = (tail + 1) % LOG_BUFFER_ENTRIES;
808         }
809         if (!seq_has_overflowed(s))
810                 port->logbuffer_tail = tail;
811         mutex_unlock(&port->logbuffer_lock);
812
813         return 0;
814 }
815 DEFINE_SHOW_ATTRIBUTE(tcpm_debug);
816
817 static void tcpm_debugfs_init(struct tcpm_port *port)
818 {
819         char name[NAME_MAX];
820
821         mutex_init(&port->logbuffer_lock);
822         snprintf(name, NAME_MAX, "tcpm-%s", dev_name(port->dev));
823         port->dentry = debugfs_create_dir(name, usb_debug_root);
824         debugfs_create_file("log", S_IFREG | 0444, port->dentry, port,
825                             &tcpm_debug_fops);
826 }
827
828 static void tcpm_debugfs_exit(struct tcpm_port *port)
829 {
830         int i;
831
832         mutex_lock(&port->logbuffer_lock);
833         for (i = 0; i < LOG_BUFFER_ENTRIES; i++) {
834                 kfree(port->logbuffer[i]);
835                 port->logbuffer[i] = NULL;
836         }
837         mutex_unlock(&port->logbuffer_lock);
838
839         debugfs_remove(port->dentry);
840 }
841
842 #else
843
844 __printf(2, 3)
845 static void tcpm_log(const struct tcpm_port *port, const char *fmt, ...) { }
846 __printf(2, 3)
847 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...) { }
848 static void tcpm_log_source_caps(struct tcpm_port *port) { }
849 static void tcpm_debugfs_init(const struct tcpm_port *port) { }
850 static void tcpm_debugfs_exit(const struct tcpm_port *port) { }
851
852 #endif
853
854 static void tcpm_set_cc(struct tcpm_port *port, enum typec_cc_status cc)
855 {
856         tcpm_log(port, "cc:=%d", cc);
857         port->cc_req = cc;
858         port->tcpc->set_cc(port->tcpc, cc);
859 }
860
861 static int tcpm_enable_auto_vbus_discharge(struct tcpm_port *port, bool enable)
862 {
863         int ret = 0;
864
865         if (port->tcpc->enable_auto_vbus_discharge) {
866                 ret = port->tcpc->enable_auto_vbus_discharge(port->tcpc, enable);
867                 tcpm_log_force(port, "%s vbus discharge ret:%d", enable ? "enable" : "disable",
868                                ret);
869                 if (!ret)
870                         port->auto_vbus_discharge_enabled = enable;
871         }
872
873         return ret;
874 }
875
876 static void tcpm_apply_rc(struct tcpm_port *port)
877 {
878         /*
879          * TCPCI: Move to APPLY_RC state to prevent disconnect during PR_SWAP
880          * when Vbus auto discharge on disconnect is enabled.
881          */
882         if (port->tcpc->enable_auto_vbus_discharge && port->tcpc->apply_rc) {
883                 tcpm_log(port, "Apply_RC");
884                 port->tcpc->apply_rc(port->tcpc, port->cc_req, port->polarity);
885                 tcpm_enable_auto_vbus_discharge(port, false);
886         }
887 }
888
889 /*
890  * Determine RP value to set based on maximum current supported
891  * by a port if configured as source.
892  * Returns CC value to report to link partner.
893  */
894 static enum typec_cc_status tcpm_rp_cc(struct tcpm_port *port)
895 {
896         const u32 *src_pdo = port->src_pdo;
897         int nr_pdo = port->nr_src_pdo;
898         int i;
899
900         if (!port->pd_supported)
901                 return port->src_rp;
902
903         /*
904          * Search for first entry with matching voltage.
905          * It should report the maximum supported current.
906          */
907         for (i = 0; i < nr_pdo; i++) {
908                 const u32 pdo = src_pdo[i];
909
910                 if (pdo_type(pdo) == PDO_TYPE_FIXED &&
911                     pdo_fixed_voltage(pdo) == 5000) {
912                         unsigned int curr = pdo_max_current(pdo);
913
914                         if (curr >= 3000)
915                                 return TYPEC_CC_RP_3_0;
916                         else if (curr >= 1500)
917                                 return TYPEC_CC_RP_1_5;
918                         return TYPEC_CC_RP_DEF;
919                 }
920         }
921
922         return TYPEC_CC_RP_DEF;
923 }
924
925 static void tcpm_ams_finish(struct tcpm_port *port)
926 {
927         tcpm_log(port, "AMS %s finished", tcpm_ams_str[port->ams]);
928
929         if (port->pd_capable && port->pwr_role == TYPEC_SOURCE) {
930                 if (port->negotiated_rev >= PD_REV30)
931                         tcpm_set_cc(port, SINK_TX_OK);
932                 else
933                         tcpm_set_cc(port, SINK_TX_NG);
934         } else if (port->pwr_role == TYPEC_SOURCE) {
935                 tcpm_set_cc(port, tcpm_rp_cc(port));
936         }
937
938         port->in_ams = false;
939         port->ams = NONE_AMS;
940 }
941
942 static int tcpm_pd_transmit(struct tcpm_port *port,
943                             enum tcpm_transmit_type tx_sop_type,
944                             const struct pd_message *msg)
945 {
946         unsigned long timeout;
947         int ret;
948         unsigned int negotiated_rev;
949
950         switch (tx_sop_type) {
951         case TCPC_TX_SOP_PRIME:
952                 negotiated_rev = port->negotiated_rev_prime;
953                 break;
954         case TCPC_TX_SOP:
955         default:
956                 negotiated_rev = port->negotiated_rev;
957                 break;
958         }
959
960         if (msg)
961                 tcpm_log(port, "PD TX, header: %#x", le16_to_cpu(msg->header));
962         else
963                 tcpm_log(port, "PD TX, type: %#x", tx_sop_type);
964
965         reinit_completion(&port->tx_complete);
966         ret = port->tcpc->pd_transmit(port->tcpc, tx_sop_type, msg, negotiated_rev);
967         if (ret < 0)
968                 return ret;
969
970         mutex_unlock(&port->lock);
971         timeout = wait_for_completion_timeout(&port->tx_complete,
972                                 msecs_to_jiffies(PD_T_TCPC_TX_TIMEOUT));
973         mutex_lock(&port->lock);
974         if (!timeout)
975                 return -ETIMEDOUT;
976
977         switch (port->tx_status) {
978         case TCPC_TX_SUCCESS:
979                 switch (tx_sop_type) {
980                 case TCPC_TX_SOP_PRIME:
981                         port->message_id_prime = (port->message_id_prime + 1) &
982                                                  PD_HEADER_ID_MASK;
983                         break;
984                 case TCPC_TX_SOP:
985                 default:
986                         port->message_id = (port->message_id + 1) &
987                                            PD_HEADER_ID_MASK;
988                         break;
989                 }
990                 /*
991                  * USB PD rev 2.0, 8.3.2.2.1:
992                  * USB PD rev 3.0, 8.3.2.1.3:
993                  * "... Note that every AMS is Interruptible until the first
994                  * Message in the sequence has been successfully sent (GoodCRC
995                  * Message received)."
996                  */
997                 if (port->ams != NONE_AMS)
998                         port->in_ams = true;
999                 break;
1000         case TCPC_TX_DISCARDED:
1001                 ret = -EAGAIN;
1002                 break;
1003         case TCPC_TX_FAILED:
1004         default:
1005                 ret = -EIO;
1006                 break;
1007         }
1008
1009         /* Some AMS don't expect responses. Finish them here. */
1010         if (port->ams == ATTENTION || port->ams == SOURCE_ALERT)
1011                 tcpm_ams_finish(port);
1012
1013         return ret;
1014 }
1015
1016 void tcpm_pd_transmit_complete(struct tcpm_port *port,
1017                                enum tcpm_transmit_status status)
1018 {
1019         tcpm_log(port, "PD TX complete, status: %u", status);
1020         port->tx_status = status;
1021         complete(&port->tx_complete);
1022 }
1023 EXPORT_SYMBOL_GPL(tcpm_pd_transmit_complete);
1024
1025 static int tcpm_mux_set(struct tcpm_port *port, int state,
1026                         enum usb_role usb_role,
1027                         enum typec_orientation orientation)
1028 {
1029         int ret;
1030
1031         tcpm_log(port, "Requesting mux state %d, usb-role %d, orientation %d",
1032                  state, usb_role, orientation);
1033
1034         ret = typec_set_orientation(port->typec_port, orientation);
1035         if (ret)
1036                 return ret;
1037
1038         if (port->role_sw) {
1039                 ret = usb_role_switch_set_role(port->role_sw, usb_role);
1040                 if (ret)
1041                         return ret;
1042         }
1043
1044         return typec_set_mode(port->typec_port, state);
1045 }
1046
1047 static int tcpm_set_polarity(struct tcpm_port *port,
1048                              enum typec_cc_polarity polarity)
1049 {
1050         int ret;
1051
1052         tcpm_log(port, "polarity %d", polarity);
1053
1054         ret = port->tcpc->set_polarity(port->tcpc, polarity);
1055         if (ret < 0)
1056                 return ret;
1057
1058         port->polarity = polarity;
1059
1060         return 0;
1061 }
1062
1063 static int tcpm_set_vconn(struct tcpm_port *port, bool enable)
1064 {
1065         int ret;
1066
1067         tcpm_log(port, "vconn:=%d", enable);
1068
1069         ret = port->tcpc->set_vconn(port->tcpc, enable);
1070         if (!ret) {
1071                 port->vconn_role = enable ? TYPEC_SOURCE : TYPEC_SINK;
1072                 typec_set_vconn_role(port->typec_port, port->vconn_role);
1073         }
1074
1075         return ret;
1076 }
1077
1078 static u32 tcpm_get_current_limit(struct tcpm_port *port)
1079 {
1080         enum typec_cc_status cc;
1081         u32 limit;
1082
1083         cc = port->polarity ? port->cc2 : port->cc1;
1084         switch (cc) {
1085         case TYPEC_CC_RP_1_5:
1086                 limit = 1500;
1087                 break;
1088         case TYPEC_CC_RP_3_0:
1089                 limit = 3000;
1090                 break;
1091         case TYPEC_CC_RP_DEF:
1092         default:
1093                 if (port->tcpc->get_current_limit)
1094                         limit = port->tcpc->get_current_limit(port->tcpc);
1095                 else
1096                         limit = 0;
1097                 break;
1098         }
1099
1100         return limit;
1101 }
1102
1103 static int tcpm_set_current_limit(struct tcpm_port *port, u32 max_ma, u32 mv)
1104 {
1105         int ret = -EOPNOTSUPP;
1106
1107         tcpm_log(port, "Setting voltage/current limit %u mV %u mA", mv, max_ma);
1108
1109         port->supply_voltage = mv;
1110         port->current_limit = max_ma;
1111         power_supply_changed(port->psy);
1112
1113         if (port->tcpc->set_current_limit)
1114                 ret = port->tcpc->set_current_limit(port->tcpc, max_ma, mv);
1115
1116         return ret;
1117 }
1118
1119 static int tcpm_set_attached_state(struct tcpm_port *port, bool attached)
1120 {
1121         return port->tcpc->set_roles(port->tcpc, attached, port->pwr_role,
1122                                      port->data_role);
1123 }
1124
1125 static int tcpm_set_roles(struct tcpm_port *port, bool attached,
1126                           enum typec_role role, enum typec_data_role data)
1127 {
1128         enum typec_orientation orientation;
1129         enum usb_role usb_role;
1130         int ret;
1131
1132         if (port->polarity == TYPEC_POLARITY_CC1)
1133                 orientation = TYPEC_ORIENTATION_NORMAL;
1134         else
1135                 orientation = TYPEC_ORIENTATION_REVERSE;
1136
1137         if (port->typec_caps.data == TYPEC_PORT_DRD) {
1138                 if (data == TYPEC_HOST)
1139                         usb_role = USB_ROLE_HOST;
1140                 else
1141                         usb_role = USB_ROLE_DEVICE;
1142         } else if (port->typec_caps.data == TYPEC_PORT_DFP) {
1143                 if (data == TYPEC_HOST) {
1144                         if (role == TYPEC_SOURCE)
1145                                 usb_role = USB_ROLE_HOST;
1146                         else
1147                                 usb_role = USB_ROLE_NONE;
1148                 } else {
1149                         return -ENOTSUPP;
1150                 }
1151         } else {
1152                 if (data == TYPEC_DEVICE) {
1153                         if (role == TYPEC_SINK)
1154                                 usb_role = USB_ROLE_DEVICE;
1155                         else
1156                                 usb_role = USB_ROLE_NONE;
1157                 } else {
1158                         return -ENOTSUPP;
1159                 }
1160         }
1161
1162         ret = tcpm_mux_set(port, TYPEC_STATE_USB, usb_role, orientation);
1163         if (ret < 0)
1164                 return ret;
1165
1166         ret = port->tcpc->set_roles(port->tcpc, attached, role, data);
1167         if (ret < 0)
1168                 return ret;
1169
1170         if (port->tcpc->set_orientation) {
1171                 ret = port->tcpc->set_orientation(port->tcpc, orientation);
1172                 if (ret < 0)
1173                         return ret;
1174         }
1175
1176         port->pwr_role = role;
1177         port->data_role = data;
1178         typec_set_data_role(port->typec_port, data);
1179         typec_set_pwr_role(port->typec_port, role);
1180
1181         return 0;
1182 }
1183
1184 static int tcpm_set_pwr_role(struct tcpm_port *port, enum typec_role role)
1185 {
1186         int ret;
1187
1188         ret = port->tcpc->set_roles(port->tcpc, true, role,
1189                                     port->data_role);
1190         if (ret < 0)
1191                 return ret;
1192
1193         port->pwr_role = role;
1194         typec_set_pwr_role(port->typec_port, role);
1195
1196         return 0;
1197 }
1198
1199 /*
1200  * Transform the PDO to be compliant to PD rev2.0.
1201  * Return 0 if the PDO type is not defined in PD rev2.0.
1202  * Otherwise, return the converted PDO.
1203  */
1204 static u32 tcpm_forge_legacy_pdo(struct tcpm_port *port, u32 pdo, enum typec_role role)
1205 {
1206         switch (pdo_type(pdo)) {
1207         case PDO_TYPE_FIXED:
1208                 if (role == TYPEC_SINK)
1209                         return pdo & ~PDO_FIXED_FRS_CURR_MASK;
1210                 else
1211                         return pdo & ~PDO_FIXED_UNCHUNK_EXT;
1212         case PDO_TYPE_VAR:
1213         case PDO_TYPE_BATT:
1214                 return pdo;
1215         case PDO_TYPE_APDO:
1216         default:
1217                 return 0;
1218         }
1219 }
1220
1221 static int tcpm_pd_send_source_caps(struct tcpm_port *port)
1222 {
1223         struct pd_message msg;
1224         u32 pdo;
1225         unsigned int i, nr_pdo = 0;
1226
1227         memset(&msg, 0, sizeof(msg));
1228
1229         for (i = 0; i < port->nr_src_pdo; i++) {
1230                 if (port->negotiated_rev >= PD_REV30) {
1231                         msg.payload[nr_pdo++] = cpu_to_le32(port->src_pdo[i]);
1232                 } else {
1233                         pdo = tcpm_forge_legacy_pdo(port, port->src_pdo[i], TYPEC_SOURCE);
1234                         if (pdo)
1235                                 msg.payload[nr_pdo++] = cpu_to_le32(pdo);
1236                 }
1237         }
1238
1239         if (!nr_pdo) {
1240                 /* No source capabilities defined, sink only */
1241                 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
1242                                           port->pwr_role,
1243                                           port->data_role,
1244                                           port->negotiated_rev,
1245                                           port->message_id, 0);
1246         } else {
1247                 msg.header = PD_HEADER_LE(PD_DATA_SOURCE_CAP,
1248                                           port->pwr_role,
1249                                           port->data_role,
1250                                           port->negotiated_rev,
1251                                           port->message_id,
1252                                           nr_pdo);
1253         }
1254
1255         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1256 }
1257
1258 static int tcpm_pd_send_sink_caps(struct tcpm_port *port)
1259 {
1260         struct pd_message msg;
1261         u32 pdo;
1262         unsigned int i, nr_pdo = 0;
1263
1264         memset(&msg, 0, sizeof(msg));
1265
1266         for (i = 0; i < port->nr_snk_pdo; i++) {
1267                 if (port->negotiated_rev >= PD_REV30) {
1268                         msg.payload[nr_pdo++] = cpu_to_le32(port->snk_pdo[i]);
1269                 } else {
1270                         pdo = tcpm_forge_legacy_pdo(port, port->snk_pdo[i], TYPEC_SINK);
1271                         if (pdo)
1272                                 msg.payload[nr_pdo++] = cpu_to_le32(pdo);
1273                 }
1274         }
1275
1276         if (!nr_pdo) {
1277                 /* No sink capabilities defined, source only */
1278                 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
1279                                           port->pwr_role,
1280                                           port->data_role,
1281                                           port->negotiated_rev,
1282                                           port->message_id, 0);
1283         } else {
1284                 msg.header = PD_HEADER_LE(PD_DATA_SINK_CAP,
1285                                           port->pwr_role,
1286                                           port->data_role,
1287                                           port->negotiated_rev,
1288                                           port->message_id,
1289                                           nr_pdo);
1290         }
1291
1292         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1293 }
1294
1295 static void mod_tcpm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1296 {
1297         if (delay_ms) {
1298                 hrtimer_start(&port->state_machine_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1299         } else {
1300                 hrtimer_cancel(&port->state_machine_timer);
1301                 kthread_queue_work(port->wq, &port->state_machine);
1302         }
1303 }
1304
1305 static void mod_vdm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1306 {
1307         if (delay_ms) {
1308                 hrtimer_start(&port->vdm_state_machine_timer, ms_to_ktime(delay_ms),
1309                               HRTIMER_MODE_REL);
1310         } else {
1311                 hrtimer_cancel(&port->vdm_state_machine_timer);
1312                 kthread_queue_work(port->wq, &port->vdm_state_machine);
1313         }
1314 }
1315
1316 static void mod_enable_frs_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1317 {
1318         if (delay_ms) {
1319                 hrtimer_start(&port->enable_frs_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1320         } else {
1321                 hrtimer_cancel(&port->enable_frs_timer);
1322                 kthread_queue_work(port->wq, &port->enable_frs);
1323         }
1324 }
1325
1326 static void mod_send_discover_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1327 {
1328         if (delay_ms) {
1329                 hrtimer_start(&port->send_discover_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1330         } else {
1331                 hrtimer_cancel(&port->send_discover_timer);
1332                 kthread_queue_work(port->wq, &port->send_discover_work);
1333         }
1334 }
1335
1336 static void tcpm_set_state(struct tcpm_port *port, enum tcpm_state state,
1337                            unsigned int delay_ms)
1338 {
1339         if (delay_ms) {
1340                 tcpm_log(port, "pending state change %s -> %s @ %u ms [%s %s]",
1341                          tcpm_states[port->state], tcpm_states[state], delay_ms,
1342                          pd_rev[port->negotiated_rev], tcpm_ams_str[port->ams]);
1343                 port->delayed_state = state;
1344                 mod_tcpm_delayed_work(port, delay_ms);
1345                 port->delayed_runtime = ktime_add(ktime_get(), ms_to_ktime(delay_ms));
1346                 port->delay_ms = delay_ms;
1347         } else {
1348                 tcpm_log(port, "state change %s -> %s [%s %s]",
1349                          tcpm_states[port->state], tcpm_states[state],
1350                          pd_rev[port->negotiated_rev], tcpm_ams_str[port->ams]);
1351                 port->delayed_state = INVALID_STATE;
1352                 port->prev_state = port->state;
1353                 port->state = state;
1354                 /*
1355                  * Don't re-queue the state machine work item if we're currently
1356                  * in the state machine and we're immediately changing states.
1357                  * tcpm_state_machine_work() will continue running the state
1358                  * machine.
1359                  */
1360                 if (!port->state_machine_running)
1361                         mod_tcpm_delayed_work(port, 0);
1362         }
1363 }
1364
1365 static void tcpm_set_state_cond(struct tcpm_port *port, enum tcpm_state state,
1366                                 unsigned int delay_ms)
1367 {
1368         if (port->enter_state == port->state)
1369                 tcpm_set_state(port, state, delay_ms);
1370         else
1371                 tcpm_log(port,
1372                          "skipped %sstate change %s -> %s [%u ms], context state %s [%s %s]",
1373                          delay_ms ? "delayed " : "",
1374                          tcpm_states[port->state], tcpm_states[state],
1375                          delay_ms, tcpm_states[port->enter_state],
1376                          pd_rev[port->negotiated_rev], tcpm_ams_str[port->ams]);
1377 }
1378
1379 static void tcpm_queue_message(struct tcpm_port *port,
1380                                enum pd_msg_request message)
1381 {
1382         port->queued_message = message;
1383         mod_tcpm_delayed_work(port, 0);
1384 }
1385
1386 static bool tcpm_vdm_ams(struct tcpm_port *port)
1387 {
1388         switch (port->ams) {
1389         case DISCOVER_IDENTITY:
1390         case SOURCE_STARTUP_CABLE_PLUG_DISCOVER_IDENTITY:
1391         case DISCOVER_SVIDS:
1392         case DISCOVER_MODES:
1393         case DFP_TO_UFP_ENTER_MODE:
1394         case DFP_TO_UFP_EXIT_MODE:
1395         case DFP_TO_CABLE_PLUG_ENTER_MODE:
1396         case DFP_TO_CABLE_PLUG_EXIT_MODE:
1397         case ATTENTION:
1398         case UNSTRUCTURED_VDMS:
1399         case STRUCTURED_VDMS:
1400                 break;
1401         default:
1402                 return false;
1403         }
1404
1405         return true;
1406 }
1407
1408 static bool tcpm_ams_interruptible(struct tcpm_port *port)
1409 {
1410         switch (port->ams) {
1411         /* Interruptible AMS */
1412         case NONE_AMS:
1413         case SECURITY:
1414         case FIRMWARE_UPDATE:
1415         case DISCOVER_IDENTITY:
1416         case SOURCE_STARTUP_CABLE_PLUG_DISCOVER_IDENTITY:
1417         case DISCOVER_SVIDS:
1418         case DISCOVER_MODES:
1419         case DFP_TO_UFP_ENTER_MODE:
1420         case DFP_TO_UFP_EXIT_MODE:
1421         case DFP_TO_CABLE_PLUG_ENTER_MODE:
1422         case DFP_TO_CABLE_PLUG_EXIT_MODE:
1423         case UNSTRUCTURED_VDMS:
1424         case STRUCTURED_VDMS:
1425         case COUNTRY_INFO:
1426         case COUNTRY_CODES:
1427                 break;
1428         /* Non-Interruptible AMS */
1429         default:
1430                 if (port->in_ams)
1431                         return false;
1432                 break;
1433         }
1434
1435         return true;
1436 }
1437
1438 static int tcpm_ams_start(struct tcpm_port *port, enum tcpm_ams ams)
1439 {
1440         int ret = 0;
1441
1442         tcpm_log(port, "AMS %s start", tcpm_ams_str[ams]);
1443
1444         if (!tcpm_ams_interruptible(port) &&
1445             !(ams == HARD_RESET || ams == SOFT_RESET_AMS)) {
1446                 port->upcoming_state = INVALID_STATE;
1447                 tcpm_log(port, "AMS %s not interruptible, aborting",
1448                          tcpm_ams_str[port->ams]);
1449                 return -EAGAIN;
1450         }
1451
1452         if (port->pwr_role == TYPEC_SOURCE) {
1453                 enum typec_cc_status cc_req = port->cc_req;
1454
1455                 port->ams = ams;
1456
1457                 if (ams == HARD_RESET) {
1458                         tcpm_set_cc(port, tcpm_rp_cc(port));
1459                         tcpm_pd_transmit(port, TCPC_TX_HARD_RESET, NULL);
1460                         tcpm_set_state(port, HARD_RESET_START, 0);
1461                         return ret;
1462                 } else if (ams == SOFT_RESET_AMS) {
1463                         if (!port->explicit_contract)
1464                                 tcpm_set_cc(port, tcpm_rp_cc(port));
1465                         tcpm_set_state(port, SOFT_RESET_SEND, 0);
1466                         return ret;
1467                 } else if (tcpm_vdm_ams(port)) {
1468                         /* tSinkTx is enforced in vdm_run_state_machine */
1469                         if (port->negotiated_rev >= PD_REV30)
1470                                 tcpm_set_cc(port, SINK_TX_NG);
1471                         return ret;
1472                 }
1473
1474                 if (port->negotiated_rev >= PD_REV30)
1475                         tcpm_set_cc(port, SINK_TX_NG);
1476
1477                 switch (port->state) {
1478                 case SRC_READY:
1479                 case SRC_STARTUP:
1480                 case SRC_SOFT_RESET_WAIT_SNK_TX:
1481                 case SOFT_RESET:
1482                 case SOFT_RESET_SEND:
1483                         if (port->negotiated_rev >= PD_REV30)
1484                                 tcpm_set_state(port, AMS_START,
1485                                                cc_req == SINK_TX_OK ?
1486                                                PD_T_SINK_TX : 0);
1487                         else
1488                                 tcpm_set_state(port, AMS_START, 0);
1489                         break;
1490                 default:
1491                         if (port->negotiated_rev >= PD_REV30)
1492                                 tcpm_set_state(port, SRC_READY,
1493                                                cc_req == SINK_TX_OK ?
1494                                                PD_T_SINK_TX : 0);
1495                         else
1496                                 tcpm_set_state(port, SRC_READY, 0);
1497                         break;
1498                 }
1499         } else {
1500                 if (port->negotiated_rev >= PD_REV30 &&
1501                     !tcpm_sink_tx_ok(port) &&
1502                     ams != SOFT_RESET_AMS &&
1503                     ams != HARD_RESET) {
1504                         port->upcoming_state = INVALID_STATE;
1505                         tcpm_log(port, "Sink TX No Go");
1506                         return -EAGAIN;
1507                 }
1508
1509                 port->ams = ams;
1510
1511                 if (ams == HARD_RESET) {
1512                         tcpm_pd_transmit(port, TCPC_TX_HARD_RESET, NULL);
1513                         tcpm_set_state(port, HARD_RESET_START, 0);
1514                         return ret;
1515                 } else if (tcpm_vdm_ams(port)) {
1516                         return ret;
1517                 }
1518
1519                 if (port->state == SNK_READY ||
1520                     port->state == SNK_SOFT_RESET)
1521                         tcpm_set_state(port, AMS_START, 0);
1522                 else
1523                         tcpm_set_state(port, SNK_READY, 0);
1524         }
1525
1526         return ret;
1527 }
1528
1529 /*
1530  * VDM/VDO handling functions
1531  */
1532 static void tcpm_queue_vdm(struct tcpm_port *port, const u32 header,
1533                            const u32 *data, int cnt, enum tcpm_transmit_type tx_sop_type)
1534 {
1535         u32 vdo_hdr = port->vdo_data[0];
1536
1537         WARN_ON(!mutex_is_locked(&port->lock));
1538
1539         /* If is sending discover_identity, handle received message first */
1540         if (PD_VDO_SVDM(vdo_hdr) && PD_VDO_CMD(vdo_hdr) == CMD_DISCOVER_IDENT) {
1541                 if (tx_sop_type == TCPC_TX_SOP_PRIME)
1542                         port->send_discover_prime = true;
1543                 else
1544                         port->send_discover = true;
1545                 mod_send_discover_delayed_work(port, SEND_DISCOVER_RETRY_MS);
1546         } else {
1547                 /* Make sure we are not still processing a previous VDM packet */
1548                 WARN_ON(port->vdm_state > VDM_STATE_DONE);
1549         }
1550
1551         port->vdo_count = cnt + 1;
1552         port->vdo_data[0] = header;
1553         memcpy(&port->vdo_data[1], data, sizeof(u32) * cnt);
1554         /* Set ready, vdm state machine will actually send */
1555         port->vdm_retries = 0;
1556         port->vdm_state = VDM_STATE_READY;
1557         port->vdm_sm_running = true;
1558
1559         port->tx_sop_type = tx_sop_type;
1560
1561         mod_vdm_delayed_work(port, 0);
1562 }
1563
1564 static void tcpm_queue_vdm_unlocked(struct tcpm_port *port, const u32 header,
1565                                     const u32 *data, int cnt, enum tcpm_transmit_type tx_sop_type)
1566 {
1567         if (port->state != SRC_READY && port->state != SNK_READY &&
1568             port->state != SRC_VDM_IDENTITY_REQUEST)
1569                 return;
1570
1571         mutex_lock(&port->lock);
1572         tcpm_queue_vdm(port, header, data, cnt, tx_sop_type);
1573         mutex_unlock(&port->lock);
1574 }
1575
1576 static void svdm_consume_identity(struct tcpm_port *port, const u32 *p, int cnt)
1577 {
1578         u32 vdo = p[VDO_INDEX_IDH];
1579         u32 product = p[VDO_INDEX_PRODUCT];
1580
1581         memset(&port->mode_data, 0, sizeof(port->mode_data));
1582
1583         port->partner_ident.id_header = vdo;
1584         port->partner_ident.cert_stat = p[VDO_INDEX_CSTAT];
1585         port->partner_ident.product = product;
1586
1587         if (port->partner)
1588                 typec_partner_set_identity(port->partner);
1589
1590         tcpm_log(port, "Identity: %04x:%04x.%04x",
1591                  PD_IDH_VID(vdo),
1592                  PD_PRODUCT_PID(product), product & 0xffff);
1593 }
1594
1595 static void svdm_consume_identity_sop_prime(struct tcpm_port *port, const u32 *p, int cnt)
1596 {
1597         u32 idh = p[VDO_INDEX_IDH];
1598         u32 product = p[VDO_INDEX_PRODUCT];
1599         int svdm_version;
1600
1601         /*
1602          * Attempt to consume identity only if cable currently is not set
1603          */
1604         if (!IS_ERR_OR_NULL(port->cable))
1605                 goto register_plug;
1606
1607         /* Reset cable identity */
1608         memset(&port->cable_ident, 0, sizeof(port->cable_ident));
1609
1610         /* Fill out id header, cert, product, cable VDO 1 */
1611         port->cable_ident.id_header = idh;
1612         port->cable_ident.cert_stat = p[VDO_INDEX_CSTAT];
1613         port->cable_ident.product = product;
1614         port->cable_ident.vdo[0] = p[VDO_INDEX_CABLE_1];
1615
1616         /* Fill out cable desc, infer svdm_version from pd revision */
1617         port->cable_desc.type = (enum typec_plug_type) (VDO_TYPEC_CABLE_TYPE(p[VDO_INDEX_CABLE_1]) +
1618                                                         USB_PLUG_TYPE_A);
1619         port->cable_desc.active = PD_IDH_PTYPE(idh) == IDH_PTYPE_ACABLE ? 1 : 0;
1620         /* Log PD Revision and additional cable VDO from negotiated revision */
1621         switch (port->negotiated_rev_prime) {
1622         case PD_REV30:
1623                 port->cable_desc.pd_revision = 0x0300;
1624                 if (port->cable_desc.active)
1625                         port->cable_ident.vdo[1] = p[VDO_INDEX_CABLE_2];
1626                 break;
1627         case PD_REV20:
1628                 port->cable_desc.pd_revision = 0x0200;
1629                 break;
1630         default:
1631                 port->cable_desc.pd_revision = 0x0200;
1632                 break;
1633         }
1634         port->cable_desc.identity = &port->cable_ident;
1635         /* Register Cable, set identity and svdm_version */
1636         port->cable = typec_register_cable(port->typec_port, &port->cable_desc);
1637         if (IS_ERR_OR_NULL(port->cable))
1638                 return;
1639         typec_cable_set_identity(port->cable);
1640         /* Get SVDM version */
1641         svdm_version = PD_VDO_SVDM_VER(p[VDO_INDEX_HDR]);
1642         typec_cable_set_svdm_version(port->cable, svdm_version);
1643
1644 register_plug:
1645         if (IS_ERR_OR_NULL(port->plug_prime)) {
1646                 port->plug_prime_desc.index = TYPEC_PLUG_SOP_P;
1647                 port->plug_prime = typec_register_plug(port->cable,
1648                                                        &port->plug_prime_desc);
1649         }
1650 }
1651
1652 static bool svdm_consume_svids(struct tcpm_port *port, const u32 *p, int cnt,
1653                                enum tcpm_transmit_type rx_sop_type)
1654 {
1655         struct pd_mode_data *pmdata = rx_sop_type == TCPC_TX_SOP_PRIME ?
1656                                       &port->mode_data_prime : &port->mode_data;
1657         int i;
1658
1659         for (i = 1; i < cnt; i++) {
1660                 u16 svid;
1661
1662                 svid = (p[i] >> 16) & 0xffff;
1663                 if (!svid)
1664                         return false;
1665
1666                 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1667                         goto abort;
1668
1669                 pmdata->svids[pmdata->nsvids++] = svid;
1670                 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1671
1672                 svid = p[i] & 0xffff;
1673                 if (!svid)
1674                         return false;
1675
1676                 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1677                         goto abort;
1678
1679                 pmdata->svids[pmdata->nsvids++] = svid;
1680                 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1681         }
1682
1683         /*
1684          * PD3.0 Spec 6.4.4.3.2: The SVIDs are returned 2 per VDO (see Table
1685          * 6-43), and can be returned maximum 6 VDOs per response (see Figure
1686          * 6-19). If the Respondersupports 12 or more SVID then the Discover
1687          * SVIDs Command Shall be executed multiple times until a Discover
1688          * SVIDs VDO is returned ending either with a SVID value of 0x0000 in
1689          * the last part of the last VDO or with a VDO containing two SVIDs
1690          * with values of 0x0000.
1691          *
1692          * However, some odd dockers support SVIDs less than 12 but without
1693          * 0x0000 in the last VDO, so we need to break the Discover SVIDs
1694          * request and return false here.
1695          */
1696         return cnt == 7;
1697 abort:
1698         tcpm_log(port, "SVID_DISCOVERY_MAX(%d) too low!", SVID_DISCOVERY_MAX);
1699         return false;
1700 }
1701
1702 static void svdm_consume_modes(struct tcpm_port *port, const u32 *p, int cnt,
1703                                enum tcpm_transmit_type rx_sop_type)
1704 {
1705         struct pd_mode_data *pmdata = &port->mode_data;
1706         struct typec_altmode_desc *paltmode;
1707         int i;
1708
1709         switch (rx_sop_type) {
1710         case TCPC_TX_SOP_PRIME:
1711                 pmdata = &port->mode_data_prime;
1712                 if (pmdata->altmodes >= ARRAY_SIZE(port->plug_prime_altmode)) {
1713                         /* Already logged in svdm_consume_svids() */
1714                         return;
1715                 }
1716                 break;
1717         case TCPC_TX_SOP:
1718                 pmdata = &port->mode_data;
1719                 if (pmdata->altmodes >= ARRAY_SIZE(port->partner_altmode)) {
1720                         /* Already logged in svdm_consume_svids() */
1721                         return;
1722                 }
1723                 break;
1724         default:
1725                 return;
1726         }
1727
1728         for (i = 1; i < cnt; i++) {
1729                 paltmode = &pmdata->altmode_desc[pmdata->altmodes];
1730                 memset(paltmode, 0, sizeof(*paltmode));
1731
1732                 paltmode->svid = pmdata->svids[pmdata->svid_index];
1733                 paltmode->mode = i;
1734                 paltmode->vdo = p[i];
1735
1736                 tcpm_log(port, " Alternate mode %d: SVID 0x%04x, VDO %d: 0x%08x",
1737                          pmdata->altmodes, paltmode->svid,
1738                          paltmode->mode, paltmode->vdo);
1739
1740                 pmdata->altmodes++;
1741         }
1742 }
1743
1744 static void tcpm_register_partner_altmodes(struct tcpm_port *port)
1745 {
1746         struct pd_mode_data *modep = &port->mode_data;
1747         struct typec_altmode *altmode;
1748         int i;
1749
1750         if (!port->partner)
1751                 return;
1752
1753         for (i = 0; i < modep->altmodes; i++) {
1754                 altmode = typec_partner_register_altmode(port->partner,
1755                                                 &modep->altmode_desc[i]);
1756                 if (IS_ERR(altmode)) {
1757                         tcpm_log(port, "Failed to register partner SVID 0x%04x",
1758                                  modep->altmode_desc[i].svid);
1759                         altmode = NULL;
1760                 }
1761                 port->partner_altmode[i] = altmode;
1762         }
1763 }
1764
1765 static void tcpm_register_plug_altmodes(struct tcpm_port *port)
1766 {
1767         struct pd_mode_data *modep = &port->mode_data_prime;
1768         struct typec_altmode *altmode;
1769         int i;
1770
1771         typec_plug_set_num_altmodes(port->plug_prime, modep->altmodes);
1772
1773         for (i = 0; i < modep->altmodes; i++) {
1774                 altmode = typec_plug_register_altmode(port->plug_prime,
1775                                                 &modep->altmode_desc[i]);
1776                 if (IS_ERR(altmode)) {
1777                         tcpm_log(port, "Failed to register plug SVID 0x%04x",
1778                                  modep->altmode_desc[i].svid);
1779                         altmode = NULL;
1780                 }
1781                 port->plug_prime_altmode[i] = altmode;
1782         }
1783 }
1784
1785 #define supports_modal(port)    PD_IDH_MODAL_SUPP((port)->partner_ident.id_header)
1786 #define supports_modal_cable(port)     PD_IDH_MODAL_SUPP((port)->cable_ident.id_header)
1787 #define supports_host(port)    PD_IDH_HOST_SUPP((port->partner_ident.id_header))
1788
1789 /*
1790  * Helper to determine whether the port is capable of SOP' communication at the
1791  * current point in time.
1792  */
1793 static bool tcpm_can_communicate_sop_prime(struct tcpm_port *port)
1794 {
1795         /* Check to see if tcpc supports SOP' communication */
1796         if (!port->tcpc->cable_comm_capable || !port->tcpc->cable_comm_capable(port->tcpc))
1797                 return false;
1798         /*
1799          * Power Delivery 2.0 Section 6.3.11
1800          * Before communicating with a Cable Plug a Port Should ensure that it
1801          * is the Vconn Source and that the Cable Plugs are powered by
1802          * performing a Vconn swap if necessary. Since it cannot be guaranteed
1803          * that the present Vconn Source is supplying Vconn, the only means to
1804          * ensure that the Cable Plugs are powered is for a Port wishing to
1805          * communicate with a Cable Plug is to become the Vconn Source.
1806          *
1807          * Power Delivery 3.0 Section 6.3.11
1808          * Before communicating with a Cable Plug a Port Shall ensure that it
1809          * is the Vconn source.
1810          */
1811         if (port->vconn_role != TYPEC_SOURCE)
1812                 return false;
1813         /*
1814          * Power Delivery 2.0 Section 2.4.4
1815          * When no Contract or an Implicit Contract is in place the Source can
1816          * communicate with a Cable Plug using SOP' packets in order to discover
1817          * its characteristics.
1818          *
1819          * Power Delivery 3.0 Section 2.4.4
1820          * When no Contract or an Implicit Contract is in place only the Source
1821          * port that is supplying Vconn is allowed to send packets to a Cable
1822          * Plug and is allowed to respond to packets from the Cable Plug.
1823          */
1824         if (!port->explicit_contract)
1825                 return port->pwr_role == TYPEC_SOURCE;
1826         if (port->negotiated_rev == PD_REV30)
1827                 return true;
1828         /*
1829          * Power Delivery 2.0 Section 2.4.4
1830          *
1831          * When an Explicit Contract is in place the DFP (either the Source or
1832          * the Sink) can communicate with the Cable Plug(s) using SOP’/SOP”
1833          * Packets (see Figure 2-3).
1834          */
1835         if (port->negotiated_rev == PD_REV20)
1836                 return port->data_role == TYPEC_HOST;
1837         return false;
1838 }
1839
1840 static bool tcpm_attempt_vconn_swap_discovery(struct tcpm_port *port)
1841 {
1842         if (!port->tcpc->attempt_vconn_swap_discovery)
1843                 return false;
1844
1845         /* Port is already source, no need to perform swap */
1846         if (port->vconn_role == TYPEC_SOURCE)
1847                 return false;
1848
1849         /*
1850          * Partner needs to support Alternate Modes with modal support. If
1851          * partner is also capable of being a USB Host, it could be a device
1852          * that supports Alternate Modes as the DFP.
1853          */
1854         if (!supports_modal(port) || supports_host(port))
1855                 return false;
1856
1857         if ((port->negotiated_rev == PD_REV20 && port->data_role == TYPEC_HOST) ||
1858             port->negotiated_rev == PD_REV30)
1859                 return port->tcpc->attempt_vconn_swap_discovery(port->tcpc);
1860
1861         return false;
1862 }
1863
1864
1865 static bool tcpm_cable_vdm_supported(struct tcpm_port *port)
1866 {
1867         return !IS_ERR_OR_NULL(port->cable) &&
1868                typec_cable_is_active(port->cable) &&
1869                supports_modal_cable(port) &&
1870                tcpm_can_communicate_sop_prime(port);
1871 }
1872
1873 static int tcpm_pd_svdm(struct tcpm_port *port, struct typec_altmode *adev,
1874                         const u32 *p, int cnt, u32 *response,
1875                         enum adev_actions *adev_action,
1876                         enum tcpm_transmit_type rx_sop_type,
1877                         enum tcpm_transmit_type *response_tx_sop_type)
1878 {
1879         struct typec_port *typec = port->typec_port;
1880         struct typec_altmode *pdev, *pdev_prime;
1881         struct pd_mode_data *modep, *modep_prime;
1882         int svdm_version;
1883         int rlen = 0;
1884         int cmd_type;
1885         int cmd;
1886         int i;
1887         int ret;
1888
1889         cmd_type = PD_VDO_CMDT(p[0]);
1890         cmd = PD_VDO_CMD(p[0]);
1891
1892         tcpm_log(port, "Rx VDM cmd 0x%x type %d cmd %d len %d",
1893                  p[0], cmd_type, cmd, cnt);
1894
1895         switch (rx_sop_type) {
1896         case TCPC_TX_SOP_PRIME:
1897                 modep_prime = &port->mode_data_prime;
1898                 pdev_prime = typec_match_altmode(port->plug_prime_altmode,
1899                                                  ALTMODE_DISCOVERY_MAX,
1900                                                  PD_VDO_VID(p[0]),
1901                                                  PD_VDO_OPOS(p[0]));
1902                 svdm_version = typec_get_cable_svdm_version(typec);
1903                 /*
1904                  * Update SVDM version if cable was discovered before port partner.
1905                  */
1906                 if (!IS_ERR_OR_NULL(port->cable) &&
1907                     PD_VDO_SVDM_VER(p[0]) < svdm_version)
1908                         typec_cable_set_svdm_version(port->cable, svdm_version);
1909                 break;
1910         case TCPC_TX_SOP:
1911                 modep = &port->mode_data;
1912                 pdev = typec_match_altmode(port->partner_altmode,
1913                                            ALTMODE_DISCOVERY_MAX,
1914                                            PD_VDO_VID(p[0]),
1915                                            PD_VDO_OPOS(p[0]));
1916                 svdm_version = typec_get_negotiated_svdm_version(typec);
1917                 if (svdm_version < 0)
1918                         return 0;
1919                 break;
1920         default:
1921                 modep = &port->mode_data;
1922                 pdev = typec_match_altmode(port->partner_altmode,
1923                                            ALTMODE_DISCOVERY_MAX,
1924                                            PD_VDO_VID(p[0]),
1925                                            PD_VDO_OPOS(p[0]));
1926                 svdm_version = typec_get_negotiated_svdm_version(typec);
1927                 if (svdm_version < 0)
1928                         return 0;
1929                 break;
1930         }
1931
1932         switch (cmd_type) {
1933         case CMDT_INIT:
1934                 /*
1935                  * Only the port or port partner is allowed to initialize SVDM
1936                  * commands over SOP'. In case the port partner initializes a
1937                  * sequence when it is not allowed to send SOP' messages, drop
1938                  * the message should the TCPM port try to process it.
1939                  */
1940                 if (rx_sop_type == TCPC_TX_SOP_PRIME)
1941                         return 0;
1942
1943                 switch (cmd) {
1944                 case CMD_DISCOVER_IDENT:
1945                         if (PD_VDO_VID(p[0]) != USB_SID_PD)
1946                                 break;
1947
1948                         if (IS_ERR_OR_NULL(port->partner))
1949                                 break;
1950
1951                         if (PD_VDO_SVDM_VER(p[0]) < svdm_version) {
1952                                 typec_partner_set_svdm_version(port->partner,
1953                                                                PD_VDO_SVDM_VER(p[0]));
1954                                 svdm_version = PD_VDO_SVDM_VER(p[0]);
1955                         }
1956
1957                         port->ams = DISCOVER_IDENTITY;
1958                         /*
1959                          * PD2.0 Spec 6.10.3: respond with NAK as DFP (data host)
1960                          * PD3.1 Spec 6.4.4.2.5.1: respond with NAK if "invalid field" or
1961                          * "wrong configuation" or "Unrecognized"
1962                          */
1963                         if ((port->data_role == TYPEC_DEVICE || svdm_version >= SVDM_VER_2_0) &&
1964                             port->nr_snk_vdo) {
1965                                 if (svdm_version < SVDM_VER_2_0) {
1966                                         for (i = 0; i < port->nr_snk_vdo_v1; i++)
1967                                                 response[i + 1] = port->snk_vdo_v1[i];
1968                                         rlen = port->nr_snk_vdo_v1 + 1;
1969
1970                                 } else {
1971                                         for (i = 0; i < port->nr_snk_vdo; i++)
1972                                                 response[i + 1] = port->snk_vdo[i];
1973                                         rlen = port->nr_snk_vdo + 1;
1974                                 }
1975                         }
1976                         break;
1977                 case CMD_DISCOVER_SVID:
1978                         port->ams = DISCOVER_SVIDS;
1979                         break;
1980                 case CMD_DISCOVER_MODES:
1981                         port->ams = DISCOVER_MODES;
1982                         break;
1983                 case CMD_ENTER_MODE:
1984                         port->ams = DFP_TO_UFP_ENTER_MODE;
1985                         break;
1986                 case CMD_EXIT_MODE:
1987                         port->ams = DFP_TO_UFP_EXIT_MODE;
1988                         break;
1989                 case CMD_ATTENTION:
1990                         /* Attention command does not have response */
1991                         *adev_action = ADEV_ATTENTION;
1992                         return 0;
1993                 default:
1994                         break;
1995                 }
1996                 if (rlen >= 1) {
1997                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_ACK);
1998                 } else if (rlen == 0) {
1999                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
2000                         rlen = 1;
2001                 } else {
2002                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_BUSY);
2003                         rlen = 1;
2004                 }
2005                 response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
2006                               (VDO_SVDM_VERS(typec_get_negotiated_svdm_version(typec)));
2007                 break;
2008         case CMDT_RSP_ACK:
2009                 /*
2010                  * Silently drop message if we are not connected, but can process
2011                  * if SOP' Discover Identity prior to explicit contract.
2012                  */
2013                 if (IS_ERR_OR_NULL(port->partner) &&
2014                     !(rx_sop_type == TCPC_TX_SOP_PRIME && cmd == CMD_DISCOVER_IDENT))
2015                         break;
2016
2017                 tcpm_ams_finish(port);
2018
2019                 switch (cmd) {
2020                 /*
2021                  * SVDM Command Flow for SOP and SOP':
2022                  * SOP          Discover Identity
2023                  * SOP'         Discover Identity
2024                  * SOP          Discover SVIDs
2025                  *              Discover Modes
2026                  * (Active Cables)
2027                  * SOP'         Discover SVIDs
2028                  *              Discover Modes
2029                  *
2030                  * Perform Discover SOP' if the port can communicate with cable
2031                  * plug.
2032                  */
2033                 case CMD_DISCOVER_IDENT:
2034                         switch (rx_sop_type) {
2035                         case TCPC_TX_SOP:
2036                                 if (PD_VDO_SVDM_VER(p[0]) < svdm_version) {
2037                                         typec_partner_set_svdm_version(port->partner,
2038                                                                        PD_VDO_SVDM_VER(p[0]));
2039                                         /* If cable is discovered before partner, downgrade svdm */
2040                                         if (!IS_ERR_OR_NULL(port->cable) &&
2041                                             (typec_get_cable_svdm_version(port->typec_port) >
2042                                             svdm_version))
2043                                                 typec_cable_set_svdm_version(port->cable,
2044                                                                              svdm_version);
2045                                 }
2046                                 /* 6.4.4.3.1 */
2047                                 svdm_consume_identity(port, p, cnt);
2048                                 /* Attempt Vconn swap, delay SOP' discovery if necessary */
2049                                 if (tcpm_attempt_vconn_swap_discovery(port)) {
2050                                         port->send_discover_prime = true;
2051                                         port->upcoming_state = VCONN_SWAP_SEND;
2052                                         ret = tcpm_ams_start(port, VCONN_SWAP);
2053                                         if (!ret)
2054                                                 return 0;
2055                                         /* Cannot perform Vconn swap */
2056                                         port->upcoming_state = INVALID_STATE;
2057                                         port->send_discover_prime = false;
2058                                 }
2059
2060                                 /*
2061                                  * Attempt Discover Identity on SOP' if the
2062                                  * cable was not discovered previously, and use
2063                                  * the SVDM version of the partner to probe.
2064                                  */
2065                                 if (IS_ERR_OR_NULL(port->cable) &&
2066                                     tcpm_can_communicate_sop_prime(port)) {
2067                                         *response_tx_sop_type = TCPC_TX_SOP_PRIME;
2068                                         port->send_discover_prime = true;
2069                                         response[0] = VDO(USB_SID_PD, 1,
2070                                                           typec_get_negotiated_svdm_version(typec),
2071                                                           CMD_DISCOVER_IDENT);
2072                                         rlen = 1;
2073                                 } else {
2074                                         *response_tx_sop_type = TCPC_TX_SOP;
2075                                         response[0] = VDO(USB_SID_PD, 1,
2076                                                           typec_get_negotiated_svdm_version(typec),
2077                                                           CMD_DISCOVER_SVID);
2078                                         rlen = 1;
2079                                 }
2080                                 break;
2081                         case TCPC_TX_SOP_PRIME:
2082                                 /*
2083                                  * svdm_consume_identity_sop_prime will determine
2084                                  * the svdm_version for the cable moving forward.
2085                                  */
2086                                 svdm_consume_identity_sop_prime(port, p, cnt);
2087
2088                                 /*
2089                                  * If received in SRC_VDM_IDENTITY_REQUEST, continue
2090                                  * to SRC_SEND_CAPABILITIES
2091                                  */
2092                                 if (port->state == SRC_VDM_IDENTITY_REQUEST) {
2093                                         tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
2094                                         return 0;
2095                                 }
2096
2097                                 *response_tx_sop_type = TCPC_TX_SOP;
2098                                 response[0] = VDO(USB_SID_PD, 1,
2099                                                   typec_get_negotiated_svdm_version(typec),
2100                                                   CMD_DISCOVER_SVID);
2101                                 rlen = 1;
2102                                 break;
2103                         default:
2104                                 return 0;
2105                         }
2106                         break;
2107                 case CMD_DISCOVER_SVID:
2108                         *response_tx_sop_type = rx_sop_type;
2109                         /* 6.4.4.3.2 */
2110                         if (svdm_consume_svids(port, p, cnt, rx_sop_type)) {
2111                                 response[0] = VDO(USB_SID_PD, 1, svdm_version, CMD_DISCOVER_SVID);
2112                                 rlen = 1;
2113                         } else {
2114                                 if (rx_sop_type == TCPC_TX_SOP) {
2115                                         if (modep->nsvids && supports_modal(port)) {
2116                                                 response[0] = VDO(modep->svids[0], 1, svdm_version,
2117                                                                 CMD_DISCOVER_MODES);
2118                                                 rlen = 1;
2119                                         }
2120                                 } else if (rx_sop_type == TCPC_TX_SOP_PRIME) {
2121                                         if (modep_prime->nsvids) {
2122                                                 response[0] = VDO(modep_prime->svids[0], 1,
2123                                                                   svdm_version, CMD_DISCOVER_MODES);
2124                                                 rlen = 1;
2125                                         }
2126                                 }
2127                         }
2128                         break;
2129                 case CMD_DISCOVER_MODES:
2130                         if (rx_sop_type == TCPC_TX_SOP) {
2131                                 /* 6.4.4.3.3 */
2132                                 svdm_consume_modes(port, p, cnt, rx_sop_type);
2133                                 modep->svid_index++;
2134                                 if (modep->svid_index < modep->nsvids) {
2135                                         u16 svid = modep->svids[modep->svid_index];
2136                                         *response_tx_sop_type = TCPC_TX_SOP;
2137                                         response[0] = VDO(svid, 1, svdm_version,
2138                                                           CMD_DISCOVER_MODES);
2139                                         rlen = 1;
2140                                 } else if (tcpm_cable_vdm_supported(port)) {
2141                                         *response_tx_sop_type = TCPC_TX_SOP_PRIME;
2142                                         response[0] = VDO(USB_SID_PD, 1,
2143                                                           typec_get_cable_svdm_version(typec),
2144                                                           CMD_DISCOVER_SVID);
2145                                         rlen = 1;
2146                                 } else {
2147                                         tcpm_register_partner_altmodes(port);
2148                                 }
2149                         } else if (rx_sop_type == TCPC_TX_SOP_PRIME) {
2150                                 /* 6.4.4.3.3 */
2151                                 svdm_consume_modes(port, p, cnt, rx_sop_type);
2152                                 modep_prime->svid_index++;
2153                                 if (modep_prime->svid_index < modep_prime->nsvids) {
2154                                         u16 svid = modep_prime->svids[modep_prime->svid_index];
2155                                         *response_tx_sop_type = TCPC_TX_SOP_PRIME;
2156                                         response[0] = VDO(svid, 1,
2157                                                           typec_get_cable_svdm_version(typec),
2158                                                           CMD_DISCOVER_MODES);
2159                                         rlen = 1;
2160                                 } else {
2161                                         tcpm_register_plug_altmodes(port);
2162                                         tcpm_register_partner_altmodes(port);
2163                                 }
2164                         }
2165                         break;
2166                 case CMD_ENTER_MODE:
2167                         *response_tx_sop_type = rx_sop_type;
2168                         if (rx_sop_type == TCPC_TX_SOP) {
2169                                 if (adev && pdev) {
2170                                         typec_altmode_update_active(pdev, true);
2171                                         *adev_action = ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL;
2172                                 }
2173                         } else if (rx_sop_type == TCPC_TX_SOP_PRIME) {
2174                                 if (adev && pdev_prime) {
2175                                         typec_altmode_update_active(pdev_prime, true);
2176                                         *adev_action = ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL;
2177                                 }
2178                         }
2179                         return 0;
2180                 case CMD_EXIT_MODE:
2181                         *response_tx_sop_type = rx_sop_type;
2182                         if (rx_sop_type == TCPC_TX_SOP) {
2183                                 if (adev && pdev) {
2184                                         typec_altmode_update_active(pdev, false);
2185                                         /* Back to USB Operation */
2186                                         *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
2187                                         return 0;
2188                                 }
2189                         }
2190                         break;
2191                 case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
2192                         break;
2193                 default:
2194                         /* Unrecognized SVDM */
2195                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
2196                         rlen = 1;
2197                         response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
2198                                       (VDO_SVDM_VERS(svdm_version));
2199                         break;
2200                 }
2201                 break;
2202         case CMDT_RSP_NAK:
2203                 tcpm_ams_finish(port);
2204                 switch (cmd) {
2205                 case CMD_DISCOVER_IDENT:
2206                 case CMD_DISCOVER_SVID:
2207                 case CMD_DISCOVER_MODES:
2208                 case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
2209                         break;
2210                 case CMD_ENTER_MODE:
2211                         /* Back to USB Operation */
2212                         *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
2213                         return 0;
2214                 default:
2215                         /* Unrecognized SVDM */
2216                         response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
2217                         rlen = 1;
2218                         response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
2219                                       (VDO_SVDM_VERS(svdm_version));
2220                         break;
2221                 }
2222                 break;
2223         default:
2224                 response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
2225                 rlen = 1;
2226                 response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
2227                               (VDO_SVDM_VERS(svdm_version));
2228                 break;
2229         }
2230
2231         /* Informing the alternate mode drivers about everything */
2232         *adev_action = ADEV_QUEUE_VDM;
2233         return rlen;
2234 }
2235
2236 static void tcpm_pd_handle_msg(struct tcpm_port *port,
2237                                enum pd_msg_request message,
2238                                enum tcpm_ams ams);
2239
2240 static void tcpm_handle_vdm_request(struct tcpm_port *port,
2241                                     const __le32 *payload, int cnt,
2242                                     enum tcpm_transmit_type rx_sop_type)
2243 {
2244         enum adev_actions adev_action = ADEV_NONE;
2245         struct typec_altmode *adev;
2246         u32 p[PD_MAX_PAYLOAD];
2247         u32 response[8] = { };
2248         int i, rlen = 0;
2249         enum tcpm_transmit_type response_tx_sop_type = TCPC_TX_SOP;
2250
2251         for (i = 0; i < cnt; i++)
2252                 p[i] = le32_to_cpu(payload[i]);
2253
2254         adev = typec_match_altmode(port->port_altmode, ALTMODE_DISCOVERY_MAX,
2255                                    PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
2256
2257         if (port->vdm_state == VDM_STATE_BUSY) {
2258                 /* If UFP responded busy retry after timeout */
2259                 if (PD_VDO_CMDT(p[0]) == CMDT_RSP_BUSY) {
2260                         port->vdm_state = VDM_STATE_WAIT_RSP_BUSY;
2261                         port->vdo_retry = (p[0] & ~VDO_CMDT_MASK) |
2262                                 CMDT_INIT;
2263                         mod_vdm_delayed_work(port, PD_T_VDM_BUSY);
2264                         return;
2265                 }
2266                 port->vdm_state = VDM_STATE_DONE;
2267         }
2268
2269         if (PD_VDO_SVDM(p[0]) && (adev || tcpm_vdm_ams(port) || port->nr_snk_vdo)) {
2270                 /*
2271                  * Here a SVDM is received (INIT or RSP or unknown). Set the vdm_sm_running in
2272                  * advance because we are dropping the lock but may send VDMs soon.
2273                  * For the cases of INIT received:
2274                  *  - If no response to send, it will be cleared later in this function.
2275                  *  - If there are responses to send, it will be cleared in the state machine.
2276                  * For the cases of RSP received:
2277                  *  - If no further INIT to send, it will be cleared later in this function.
2278                  *  - Otherwise, it will be cleared in the state machine if timeout or it will go
2279                  *    back here until no further INIT to send.
2280                  * For the cases of unknown type received:
2281                  *  - We will send NAK and the flag will be cleared in the state machine.
2282                  */
2283                 port->vdm_sm_running = true;
2284                 rlen = tcpm_pd_svdm(port, adev, p, cnt, response, &adev_action,
2285                                     rx_sop_type, &response_tx_sop_type);
2286         } else {
2287                 if (port->negotiated_rev >= PD_REV30)
2288                         tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
2289         }
2290
2291         /*
2292          * We are done with any state stored in the port struct now, except
2293          * for any port struct changes done by the tcpm_queue_vdm() call
2294          * below, which is a separate operation.
2295          *
2296          * So we can safely release the lock here; and we MUST release the
2297          * lock here to avoid an AB BA lock inversion:
2298          *
2299          * If we keep the lock here then the lock ordering in this path is:
2300          * 1. tcpm_pd_rx_handler take the tcpm port lock
2301          * 2. One of the typec_altmode_* calls below takes the alt-mode's lock
2302          *
2303          * And we also have this ordering:
2304          * 1. alt-mode driver takes the alt-mode's lock
2305          * 2. alt-mode driver calls tcpm_altmode_enter which takes the
2306          *    tcpm port lock
2307          *
2308          * Dropping our lock here avoids this.
2309          */
2310         mutex_unlock(&port->lock);
2311
2312         if (adev) {
2313                 switch (adev_action) {
2314                 case ADEV_NONE:
2315                         break;
2316                 case ADEV_NOTIFY_USB_AND_QUEUE_VDM:
2317                         WARN_ON(typec_altmode_notify(adev, TYPEC_STATE_USB, NULL));
2318                         typec_altmode_vdm(adev, p[0], &p[1], cnt);
2319                         break;
2320                 case ADEV_QUEUE_VDM:
2321                         if (response_tx_sop_type == TCPC_TX_SOP_PRIME)
2322                                 typec_cable_altmode_vdm(adev, TYPEC_PLUG_SOP_P, p[0], &p[1], cnt);
2323                         else
2324                                 typec_altmode_vdm(adev, p[0], &p[1], cnt);
2325                         break;
2326                 case ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL:
2327                         if (response_tx_sop_type == TCPC_TX_SOP_PRIME) {
2328                                 if (typec_cable_altmode_vdm(adev, TYPEC_PLUG_SOP_P,
2329                                                             p[0], &p[1], cnt)) {
2330                                         int svdm_version = typec_get_cable_svdm_version(
2331                                                                                 port->typec_port);
2332                                         if (svdm_version < 0)
2333                                                 break;
2334
2335                                         response[0] = VDO(adev->svid, 1, svdm_version,
2336                                                         CMD_EXIT_MODE);
2337                                         response[0] |= VDO_OPOS(adev->mode);
2338                                         rlen = 1;
2339                                 }
2340                         } else {
2341                                 if (typec_altmode_vdm(adev, p[0], &p[1], cnt)) {
2342                                         int svdm_version = typec_get_negotiated_svdm_version(
2343                                                                                 port->typec_port);
2344                                         if (svdm_version < 0)
2345                                                 break;
2346
2347                                         response[0] = VDO(adev->svid, 1, svdm_version,
2348                                                         CMD_EXIT_MODE);
2349                                         response[0] |= VDO_OPOS(adev->mode);
2350                                         rlen = 1;
2351                                 }
2352                         }
2353                         break;
2354                 case ADEV_ATTENTION:
2355                         if (typec_altmode_attention(adev, p[1]))
2356                                 tcpm_log(port, "typec_altmode_attention no port partner altmode");
2357                         break;
2358                 }
2359         }
2360
2361         /*
2362          * We must re-take the lock here to balance the unlock in
2363          * tcpm_pd_rx_handler, note that no changes, other then the
2364          * tcpm_queue_vdm call, are made while the lock is held again.
2365          * All that is done after the call is unwinding the call stack until
2366          * we return to tcpm_pd_rx_handler and do the unlock there.
2367          */
2368         mutex_lock(&port->lock);
2369
2370         if (rlen > 0)
2371                 tcpm_queue_vdm(port, response[0], &response[1], rlen - 1, response_tx_sop_type);
2372         else
2373                 port->vdm_sm_running = false;
2374 }
2375
2376 static void tcpm_send_vdm(struct tcpm_port *port, u32 vid, int cmd,
2377                           const u32 *data, int count, enum tcpm_transmit_type tx_sop_type)
2378 {
2379         int svdm_version;
2380         u32 header;
2381
2382         switch (tx_sop_type) {
2383         case TCPC_TX_SOP_PRIME:
2384                 /*
2385                  * If the port partner is discovered, then the port partner's
2386                  * SVDM Version will be returned
2387                  */
2388                 svdm_version = typec_get_cable_svdm_version(port->typec_port);
2389                 if (svdm_version < 0)
2390                         svdm_version = SVDM_VER_MAX;
2391                 break;
2392         case TCPC_TX_SOP:
2393                 svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2394                 if (svdm_version < 0)
2395                         return;
2396                 break;
2397         default:
2398                 svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2399                 if (svdm_version < 0)
2400                         return;
2401                 break;
2402         }
2403
2404         if (WARN_ON(count > VDO_MAX_SIZE - 1))
2405                 count = VDO_MAX_SIZE - 1;
2406
2407         /* set VDM header with VID & CMD */
2408         header = VDO(vid, ((vid & USB_SID_PD) == USB_SID_PD) ?
2409                         1 : (PD_VDO_CMD(cmd) <= CMD_ATTENTION),
2410                         svdm_version, cmd);
2411         tcpm_queue_vdm(port, header, data, count, tx_sop_type);
2412 }
2413
2414 static unsigned int vdm_ready_timeout(u32 vdm_hdr)
2415 {
2416         unsigned int timeout;
2417         int cmd = PD_VDO_CMD(vdm_hdr);
2418
2419         /* its not a structured VDM command */
2420         if (!PD_VDO_SVDM(vdm_hdr))
2421                 return PD_T_VDM_UNSTRUCTURED;
2422
2423         switch (PD_VDO_CMDT(vdm_hdr)) {
2424         case CMDT_INIT:
2425                 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
2426                         timeout = PD_T_VDM_WAIT_MODE_E;
2427                 else
2428                         timeout = PD_T_VDM_SNDR_RSP;
2429                 break;
2430         default:
2431                 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
2432                         timeout = PD_T_VDM_E_MODE;
2433                 else
2434                         timeout = PD_T_VDM_RCVR_RSP;
2435                 break;
2436         }
2437         return timeout;
2438 }
2439
2440 static void vdm_run_state_machine(struct tcpm_port *port)
2441 {
2442         struct pd_message msg;
2443         int i, res = 0;
2444         u32 vdo_hdr = port->vdo_data[0];
2445         u32 response[8] = { };
2446
2447         switch (port->vdm_state) {
2448         case VDM_STATE_READY:
2449                 /* Only transmit VDM if attached */
2450                 if (!port->attached) {
2451                         port->vdm_state = VDM_STATE_ERR_BUSY;
2452                         break;
2453                 }
2454
2455                 /*
2456                  * if there's traffic or we're not in PDO ready state don't send
2457                  * a VDM.
2458                  */
2459                 if (port->state != SRC_READY && port->state != SNK_READY &&
2460                     port->state != SRC_VDM_IDENTITY_REQUEST) {
2461                         port->vdm_sm_running = false;
2462                         break;
2463                 }
2464
2465                 /* TODO: AMS operation for Unstructured VDM */
2466                 if (PD_VDO_SVDM(vdo_hdr) && PD_VDO_CMDT(vdo_hdr) == CMDT_INIT) {
2467                         switch (PD_VDO_CMD(vdo_hdr)) {
2468                         case CMD_DISCOVER_IDENT:
2469                                 res = tcpm_ams_start(port, DISCOVER_IDENTITY);
2470                                 if (res == 0) {
2471                                         switch (port->tx_sop_type) {
2472                                         case TCPC_TX_SOP_PRIME:
2473                                                 port->send_discover_prime = false;
2474                                                 break;
2475                                         case TCPC_TX_SOP:
2476                                                 port->send_discover = false;
2477                                                 break;
2478                                         default:
2479                                                 port->send_discover = false;
2480                                                 break;
2481                                         }
2482                                 } else if (res == -EAGAIN) {
2483                                         port->vdo_data[0] = 0;
2484                                         mod_send_discover_delayed_work(port,
2485                                                                        SEND_DISCOVER_RETRY_MS);
2486                                 }
2487                                 break;
2488                         case CMD_DISCOVER_SVID:
2489                                 res = tcpm_ams_start(port, DISCOVER_SVIDS);
2490                                 break;
2491                         case CMD_DISCOVER_MODES:
2492                                 res = tcpm_ams_start(port, DISCOVER_MODES);
2493                                 break;
2494                         case CMD_ENTER_MODE:
2495                                 res = tcpm_ams_start(port, DFP_TO_UFP_ENTER_MODE);
2496                                 break;
2497                         case CMD_EXIT_MODE:
2498                                 res = tcpm_ams_start(port, DFP_TO_UFP_EXIT_MODE);
2499                                 break;
2500                         case CMD_ATTENTION:
2501                                 res = tcpm_ams_start(port, ATTENTION);
2502                                 break;
2503                         case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
2504                                 res = tcpm_ams_start(port, STRUCTURED_VDMS);
2505                                 break;
2506                         default:
2507                                 res = -EOPNOTSUPP;
2508                                 break;
2509                         }
2510
2511                         if (res < 0) {
2512                                 port->vdm_state = VDM_STATE_ERR_BUSY;
2513                                 return;
2514                         }
2515                 }
2516
2517                 port->vdm_state = VDM_STATE_SEND_MESSAGE;
2518                 mod_vdm_delayed_work(port, (port->negotiated_rev >= PD_REV30 &&
2519                                             port->pwr_role == TYPEC_SOURCE &&
2520                                             PD_VDO_SVDM(vdo_hdr) &&
2521                                             PD_VDO_CMDT(vdo_hdr) == CMDT_INIT) ?
2522                                            PD_T_SINK_TX : 0);
2523                 break;
2524         case VDM_STATE_WAIT_RSP_BUSY:
2525                 port->vdo_data[0] = port->vdo_retry;
2526                 port->vdo_count = 1;
2527                 port->vdm_state = VDM_STATE_READY;
2528                 tcpm_ams_finish(port);
2529                 break;
2530         case VDM_STATE_BUSY:
2531                 port->vdm_state = VDM_STATE_ERR_TMOUT;
2532                 if (port->ams != NONE_AMS)
2533                         tcpm_ams_finish(port);
2534                 break;
2535         case VDM_STATE_ERR_SEND:
2536                 /*
2537                  * When sending Discover Identity to SOP' before establishing an
2538                  * explicit contract, do not retry. Instead, weave sending
2539                  * Source_Capabilities over SOP and Discover Identity over SOP'.
2540                  */
2541                 if (port->state == SRC_VDM_IDENTITY_REQUEST) {
2542                         tcpm_ams_finish(port);
2543                         port->vdm_state = VDM_STATE_DONE;
2544                         tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
2545                 /*
2546                  * A partner which does not support USB PD will not reply,
2547                  * so this is not a fatal error. At the same time, some
2548                  * devices may not return GoodCRC under some circumstances,
2549                  * so we need to retry.
2550                  */
2551                 } else if (port->vdm_retries < 3) {
2552                         tcpm_log(port, "VDM Tx error, retry");
2553                         port->vdm_retries++;
2554                         port->vdm_state = VDM_STATE_READY;
2555                         if (PD_VDO_SVDM(vdo_hdr) && PD_VDO_CMDT(vdo_hdr) == CMDT_INIT)
2556                                 tcpm_ams_finish(port);
2557                 } else {
2558                         tcpm_ams_finish(port);
2559                         if (port->tx_sop_type == TCPC_TX_SOP)
2560                                 break;
2561                         /* Handle SOP' Transmission Errors */
2562                         switch (PD_VDO_CMD(vdo_hdr)) {
2563                         /*
2564                          * If Discover Identity fails on SOP', then resume
2565                          * discovery process on SOP only.
2566                          */
2567                         case CMD_DISCOVER_IDENT:
2568                                 port->vdo_data[0] = 0;
2569                                 response[0] = VDO(USB_SID_PD, 1,
2570                                                   typec_get_negotiated_svdm_version(
2571                                                                         port->typec_port),
2572                                                   CMD_DISCOVER_SVID);
2573                                 tcpm_queue_vdm(port, response[0], &response[1],
2574                                                0, TCPC_TX_SOP);
2575                                 break;
2576                         /*
2577                          * If Discover SVIDs or Discover Modes fail, then
2578                          * proceed with Alt Mode discovery process on SOP.
2579                          */
2580                         case CMD_DISCOVER_SVID:
2581                                 tcpm_register_partner_altmodes(port);
2582                                 break;
2583                         case CMD_DISCOVER_MODES:
2584                                 tcpm_register_partner_altmodes(port);
2585                                 break;
2586                         default:
2587                                 break;
2588                         }
2589                 }
2590                 break;
2591         case VDM_STATE_SEND_MESSAGE:
2592                 /* Prepare and send VDM */
2593                 memset(&msg, 0, sizeof(msg));
2594                 if (port->tx_sop_type == TCPC_TX_SOP_PRIME) {
2595                         msg.header = PD_HEADER_LE(PD_DATA_VENDOR_DEF,
2596                                                   0,    /* Cable Plug Indicator for DFP/UFP */
2597                                                   0,    /* Reserved */
2598                                                   port->negotiated_rev_prime,
2599                                                   port->message_id_prime,
2600                                                   port->vdo_count);
2601                 } else {
2602                         msg.header = PD_HEADER_LE(PD_DATA_VENDOR_DEF,
2603                                                   port->pwr_role,
2604                                                   port->data_role,
2605                                                   port->negotiated_rev,
2606                                                   port->message_id,
2607                                                   port->vdo_count);
2608                 }
2609                 for (i = 0; i < port->vdo_count; i++)
2610                         msg.payload[i] = cpu_to_le32(port->vdo_data[i]);
2611                 res = tcpm_pd_transmit(port, port->tx_sop_type, &msg);
2612                 if (res < 0) {
2613                         port->vdm_state = VDM_STATE_ERR_SEND;
2614                 } else {
2615                         unsigned long timeout;
2616
2617                         port->vdm_retries = 0;
2618                         port->vdo_data[0] = 0;
2619                         port->vdm_state = VDM_STATE_BUSY;
2620                         timeout = vdm_ready_timeout(vdo_hdr);
2621                         mod_vdm_delayed_work(port, timeout);
2622                 }
2623                 break;
2624         default:
2625                 break;
2626         }
2627 }
2628
2629 static void vdm_state_machine_work(struct kthread_work *work)
2630 {
2631         struct tcpm_port *port = container_of(work, struct tcpm_port, vdm_state_machine);
2632         enum vdm_states prev_state;
2633
2634         mutex_lock(&port->lock);
2635
2636         /*
2637          * Continue running as long as the port is not busy and there was
2638          * a state change.
2639          */
2640         do {
2641                 prev_state = port->vdm_state;
2642                 vdm_run_state_machine(port);
2643         } while (port->vdm_state != prev_state &&
2644                  port->vdm_state != VDM_STATE_BUSY &&
2645                  port->vdm_state != VDM_STATE_SEND_MESSAGE);
2646
2647         if (port->vdm_state < VDM_STATE_READY)
2648                 port->vdm_sm_running = false;
2649
2650         mutex_unlock(&port->lock);
2651 }
2652
2653 enum pdo_err {
2654         PDO_NO_ERR,
2655         PDO_ERR_NO_VSAFE5V,
2656         PDO_ERR_VSAFE5V_NOT_FIRST,
2657         PDO_ERR_PDO_TYPE_NOT_IN_ORDER,
2658         PDO_ERR_FIXED_NOT_SORTED,
2659         PDO_ERR_VARIABLE_BATT_NOT_SORTED,
2660         PDO_ERR_DUPE_PDO,
2661         PDO_ERR_PPS_APDO_NOT_SORTED,
2662         PDO_ERR_DUPE_PPS_APDO,
2663 };
2664
2665 static const char * const pdo_err_msg[] = {
2666         [PDO_ERR_NO_VSAFE5V] =
2667         " err: source/sink caps should at least have vSafe5V",
2668         [PDO_ERR_VSAFE5V_NOT_FIRST] =
2669         " err: vSafe5V Fixed Supply Object Shall always be the first object",
2670         [PDO_ERR_PDO_TYPE_NOT_IN_ORDER] =
2671         " err: PDOs should be in the following order: Fixed; Battery; Variable",
2672         [PDO_ERR_FIXED_NOT_SORTED] =
2673         " err: Fixed supply pdos should be in increasing order of their fixed voltage",
2674         [PDO_ERR_VARIABLE_BATT_NOT_SORTED] =
2675         " err: Variable/Battery supply pdos should be in increasing order of their minimum voltage",
2676         [PDO_ERR_DUPE_PDO] =
2677         " err: Variable/Batt supply pdos cannot have same min/max voltage",
2678         [PDO_ERR_PPS_APDO_NOT_SORTED] =
2679         " err: Programmable power supply apdos should be in increasing order of their maximum voltage",
2680         [PDO_ERR_DUPE_PPS_APDO] =
2681         " err: Programmable power supply apdos cannot have same min/max voltage and max current",
2682 };
2683
2684 static enum pdo_err tcpm_caps_err(struct tcpm_port *port, const u32 *pdo,
2685                                   unsigned int nr_pdo)
2686 {
2687         unsigned int i;
2688
2689         /* Should at least contain vSafe5v */
2690         if (nr_pdo < 1)
2691                 return PDO_ERR_NO_VSAFE5V;
2692
2693         /* The vSafe5V Fixed Supply Object Shall always be the first object */
2694         if (pdo_type(pdo[0]) != PDO_TYPE_FIXED ||
2695             pdo_fixed_voltage(pdo[0]) != VSAFE5V)
2696                 return PDO_ERR_VSAFE5V_NOT_FIRST;
2697
2698         for (i = 1; i < nr_pdo; i++) {
2699                 if (pdo_type(pdo[i]) < pdo_type(pdo[i - 1])) {
2700                         return PDO_ERR_PDO_TYPE_NOT_IN_ORDER;
2701                 } else if (pdo_type(pdo[i]) == pdo_type(pdo[i - 1])) {
2702                         enum pd_pdo_type type = pdo_type(pdo[i]);
2703
2704                         switch (type) {
2705                         /*
2706                          * The remaining Fixed Supply Objects, if
2707                          * present, shall be sent in voltage order;
2708                          * lowest to highest.
2709                          */
2710                         case PDO_TYPE_FIXED:
2711                                 if (pdo_fixed_voltage(pdo[i]) <=
2712                                     pdo_fixed_voltage(pdo[i - 1]))
2713                                         return PDO_ERR_FIXED_NOT_SORTED;
2714                                 break;
2715                         /*
2716                          * The Battery Supply Objects and Variable
2717                          * supply, if present shall be sent in Minimum
2718                          * Voltage order; lowest to highest.
2719                          */
2720                         case PDO_TYPE_VAR:
2721                         case PDO_TYPE_BATT:
2722                                 if (pdo_min_voltage(pdo[i]) <
2723                                     pdo_min_voltage(pdo[i - 1]))
2724                                         return PDO_ERR_VARIABLE_BATT_NOT_SORTED;
2725                                 else if ((pdo_min_voltage(pdo[i]) ==
2726                                           pdo_min_voltage(pdo[i - 1])) &&
2727                                          (pdo_max_voltage(pdo[i]) ==
2728                                           pdo_max_voltage(pdo[i - 1])))
2729                                         return PDO_ERR_DUPE_PDO;
2730                                 break;
2731                         /*
2732                          * The Programmable Power Supply APDOs, if present,
2733                          * shall be sent in Maximum Voltage order;
2734                          * lowest to highest.
2735                          */
2736                         case PDO_TYPE_APDO:
2737                                 if (pdo_apdo_type(pdo[i]) != APDO_TYPE_PPS)
2738                                         break;
2739
2740                                 if (pdo_pps_apdo_max_voltage(pdo[i]) <
2741                                     pdo_pps_apdo_max_voltage(pdo[i - 1]))
2742                                         return PDO_ERR_PPS_APDO_NOT_SORTED;
2743                                 else if (pdo_pps_apdo_min_voltage(pdo[i]) ==
2744                                           pdo_pps_apdo_min_voltage(pdo[i - 1]) &&
2745                                          pdo_pps_apdo_max_voltage(pdo[i]) ==
2746                                           pdo_pps_apdo_max_voltage(pdo[i - 1]) &&
2747                                          pdo_pps_apdo_max_current(pdo[i]) ==
2748                                           pdo_pps_apdo_max_current(pdo[i - 1]))
2749                                         return PDO_ERR_DUPE_PPS_APDO;
2750                                 break;
2751                         default:
2752                                 tcpm_log_force(port, " Unknown pdo type");
2753                         }
2754                 }
2755         }
2756
2757         return PDO_NO_ERR;
2758 }
2759
2760 static int tcpm_validate_caps(struct tcpm_port *port, const u32 *pdo,
2761                               unsigned int nr_pdo)
2762 {
2763         enum pdo_err err_index = tcpm_caps_err(port, pdo, nr_pdo);
2764
2765         if (err_index != PDO_NO_ERR) {
2766                 tcpm_log_force(port, " %s", pdo_err_msg[err_index]);
2767                 return -EINVAL;
2768         }
2769
2770         return 0;
2771 }
2772
2773 static int tcpm_altmode_enter(struct typec_altmode *altmode, u32 *vdo)
2774 {
2775         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2776         int svdm_version;
2777         u32 header;
2778
2779         svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2780         if (svdm_version < 0)
2781                 return svdm_version;
2782
2783         header = VDO(altmode->svid, vdo ? 2 : 1, svdm_version, CMD_ENTER_MODE);
2784         header |= VDO_OPOS(altmode->mode);
2785
2786         tcpm_queue_vdm_unlocked(port, header, vdo, vdo ? 1 : 0, TCPC_TX_SOP);
2787         return 0;
2788 }
2789
2790 static int tcpm_altmode_exit(struct typec_altmode *altmode)
2791 {
2792         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2793         int svdm_version;
2794         u32 header;
2795
2796         svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2797         if (svdm_version < 0)
2798                 return svdm_version;
2799
2800         header = VDO(altmode->svid, 1, svdm_version, CMD_EXIT_MODE);
2801         header |= VDO_OPOS(altmode->mode);
2802
2803         tcpm_queue_vdm_unlocked(port, header, NULL, 0, TCPC_TX_SOP);
2804         return 0;
2805 }
2806
2807 static int tcpm_altmode_vdm(struct typec_altmode *altmode,
2808                             u32 header, const u32 *data, int count)
2809 {
2810         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2811
2812         tcpm_queue_vdm_unlocked(port, header, data, count - 1, TCPC_TX_SOP);
2813
2814         return 0;
2815 }
2816
2817 static const struct typec_altmode_ops tcpm_altmode_ops = {
2818         .enter = tcpm_altmode_enter,
2819         .exit = tcpm_altmode_exit,
2820         .vdm = tcpm_altmode_vdm,
2821 };
2822
2823
2824 static int tcpm_cable_altmode_enter(struct typec_altmode *altmode, enum typec_plug_index sop,
2825                                     u32 *vdo)
2826 {
2827         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2828         int svdm_version;
2829         u32 header;
2830
2831         svdm_version = typec_get_cable_svdm_version(port->typec_port);
2832         if (svdm_version < 0)
2833                 return svdm_version;
2834
2835         header = VDO(altmode->svid, vdo ? 2 : 1, svdm_version, CMD_ENTER_MODE);
2836         header |= VDO_OPOS(altmode->mode);
2837
2838         tcpm_queue_vdm_unlocked(port, header, vdo, vdo ? 1 : 0, TCPC_TX_SOP_PRIME);
2839         return 0;
2840 }
2841
2842 static int tcpm_cable_altmode_exit(struct typec_altmode *altmode, enum typec_plug_index sop)
2843 {
2844         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2845         int svdm_version;
2846         u32 header;
2847
2848         svdm_version = typec_get_cable_svdm_version(port->typec_port);
2849         if (svdm_version < 0)
2850                 return svdm_version;
2851
2852         header = VDO(altmode->svid, 1, svdm_version, CMD_EXIT_MODE);
2853         header |= VDO_OPOS(altmode->mode);
2854
2855         tcpm_queue_vdm_unlocked(port, header, NULL, 0, TCPC_TX_SOP_PRIME);
2856         return 0;
2857 }
2858
2859 static int tcpm_cable_altmode_vdm(struct typec_altmode *altmode, enum typec_plug_index sop,
2860                                   u32 header, const u32 *data, int count)
2861 {
2862         struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2863
2864         tcpm_queue_vdm_unlocked(port, header, data, count - 1, TCPC_TX_SOP_PRIME);
2865
2866         return 0;
2867 }
2868
2869 static const struct typec_cable_ops tcpm_cable_ops = {
2870         .enter = tcpm_cable_altmode_enter,
2871         .exit = tcpm_cable_altmode_exit,
2872         .vdm = tcpm_cable_altmode_vdm,
2873 };
2874
2875 /*
2876  * PD (data, control) command handling functions
2877  */
2878 static inline enum tcpm_state ready_state(struct tcpm_port *port)
2879 {
2880         if (port->pwr_role == TYPEC_SOURCE)
2881                 return SRC_READY;
2882         else
2883                 return SNK_READY;
2884 }
2885
2886 static int tcpm_pd_send_control(struct tcpm_port *port,
2887                                 enum pd_ctrl_msg_type type,
2888                                 enum tcpm_transmit_type tx_sop_type);
2889
2890 static void tcpm_handle_alert(struct tcpm_port *port, const __le32 *payload,
2891                               int cnt)
2892 {
2893         u32 p0 = le32_to_cpu(payload[0]);
2894         unsigned int type = usb_pd_ado_type(p0);
2895
2896         if (!type) {
2897                 tcpm_log(port, "Alert message received with no type");
2898                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2899                 return;
2900         }
2901
2902         /* Just handling non-battery alerts for now */
2903         if (!(type & USB_PD_ADO_TYPE_BATT_STATUS_CHANGE)) {
2904                 if (port->pwr_role == TYPEC_SOURCE) {
2905                         port->upcoming_state = GET_STATUS_SEND;
2906                         tcpm_ams_start(port, GETTING_SOURCE_SINK_STATUS);
2907                 } else {
2908                         /*
2909                          * Do not check SinkTxOk here in case the Source doesn't set its Rp to
2910                          * SinkTxOk in time.
2911                          */
2912                         port->ams = GETTING_SOURCE_SINK_STATUS;
2913                         tcpm_set_state(port, GET_STATUS_SEND, 0);
2914                 }
2915         } else {
2916                 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2917         }
2918 }
2919
2920 static int tcpm_set_auto_vbus_discharge_threshold(struct tcpm_port *port,
2921                                                   enum typec_pwr_opmode mode, bool pps_active,
2922                                                   u32 requested_vbus_voltage)
2923 {
2924         int ret;
2925
2926         if (!port->tcpc->set_auto_vbus_discharge_threshold)
2927                 return 0;
2928
2929         ret = port->tcpc->set_auto_vbus_discharge_threshold(port->tcpc, mode, pps_active,
2930                                                             requested_vbus_voltage);
2931         tcpm_log_force(port,
2932                        "set_auto_vbus_discharge_threshold mode:%d pps_active:%c vbus:%u ret:%d",
2933                        mode, pps_active ? 'y' : 'n', requested_vbus_voltage, ret);
2934
2935         return ret;
2936 }
2937
2938 static void tcpm_pd_handle_state(struct tcpm_port *port,
2939                                  enum tcpm_state state,
2940                                  enum tcpm_ams ams,
2941                                  unsigned int delay_ms)
2942 {
2943         switch (port->state) {
2944         case SRC_READY:
2945         case SNK_READY:
2946                 port->ams = ams;
2947                 tcpm_set_state(port, state, delay_ms);
2948                 break;
2949         /* 8.3.3.4.1.1 and 6.8.1 power transitioning */
2950         case SNK_TRANSITION_SINK:
2951         case SNK_TRANSITION_SINK_VBUS:
2952         case SRC_TRANSITION_SUPPLY:
2953                 tcpm_set_state(port, HARD_RESET_SEND, 0);
2954                 break;
2955         default:
2956                 if (!tcpm_ams_interruptible(port)) {
2957                         tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
2958                                        SRC_SOFT_RESET_WAIT_SNK_TX :
2959                                        SNK_SOFT_RESET,
2960                                        0);
2961                 } else {
2962                         /* process the Message 6.8.1 */
2963                         port->upcoming_state = state;
2964                         port->next_ams = ams;
2965                         tcpm_set_state(port, ready_state(port), delay_ms);
2966                 }
2967                 break;
2968         }
2969 }
2970
2971 static void tcpm_pd_handle_msg(struct tcpm_port *port,
2972                                enum pd_msg_request message,
2973                                enum tcpm_ams ams)
2974 {
2975         switch (port->state) {
2976         case SRC_READY:
2977         case SNK_READY:
2978                 port->ams = ams;
2979                 tcpm_queue_message(port, message);
2980                 break;
2981         /* PD 3.0 Spec 8.3.3.4.1.1 and 6.8.1 */
2982         case SNK_TRANSITION_SINK:
2983         case SNK_TRANSITION_SINK_VBUS:
2984         case SRC_TRANSITION_SUPPLY:
2985                 tcpm_set_state(port, HARD_RESET_SEND, 0);
2986                 break;
2987         default:
2988                 if (!tcpm_ams_interruptible(port)) {
2989                         tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
2990                                        SRC_SOFT_RESET_WAIT_SNK_TX :
2991                                        SNK_SOFT_RESET,
2992                                        0);
2993                 } else {
2994                         port->next_ams = ams;
2995                         tcpm_set_state(port, ready_state(port), 0);
2996                         /* 6.8.1 process the Message */
2997                         tcpm_queue_message(port, message);
2998                 }
2999                 break;
3000         }
3001 }
3002
3003 static int tcpm_register_source_caps(struct tcpm_port *port)
3004 {
3005         struct usb_power_delivery_desc desc = { port->negotiated_rev };
3006         struct usb_power_delivery_capabilities_desc caps = { };
3007         struct usb_power_delivery_capabilities *cap = port->partner_source_caps;
3008
3009         if (!port->partner_pd)
3010                 port->partner_pd = usb_power_delivery_register(NULL, &desc);
3011         if (IS_ERR(port->partner_pd))
3012                 return PTR_ERR(port->partner_pd);
3013
3014         memcpy(caps.pdo, port->source_caps, sizeof(u32) * port->nr_source_caps);
3015         caps.role = TYPEC_SOURCE;
3016
3017         if (cap) {
3018                 usb_power_delivery_unregister_capabilities(cap);
3019                 port->partner_source_caps = NULL;
3020         }
3021
3022         cap = usb_power_delivery_register_capabilities(port->partner_pd, &caps);
3023         if (IS_ERR(cap))
3024                 return PTR_ERR(cap);
3025
3026         port->partner_source_caps = cap;
3027
3028         return 0;
3029 }
3030
3031 static int tcpm_register_sink_caps(struct tcpm_port *port)
3032 {
3033         struct usb_power_delivery_desc desc = { port->negotiated_rev };
3034         struct usb_power_delivery_capabilities_desc caps = { };
3035         struct usb_power_delivery_capabilities *cap;
3036
3037         if (!port->partner_pd)
3038                 port->partner_pd = usb_power_delivery_register(NULL, &desc);
3039         if (IS_ERR(port->partner_pd))
3040                 return PTR_ERR(port->partner_pd);
3041
3042         memcpy(caps.pdo, port->sink_caps, sizeof(u32) * port->nr_sink_caps);
3043         caps.role = TYPEC_SINK;
3044
3045         cap = usb_power_delivery_register_capabilities(port->partner_pd, &caps);
3046         if (IS_ERR(cap))
3047                 return PTR_ERR(cap);
3048
3049         port->partner_sink_caps = cap;
3050
3051         return 0;
3052 }
3053
3054 static void tcpm_pd_data_request(struct tcpm_port *port,
3055                                  const struct pd_message *msg,
3056                                  enum tcpm_transmit_type rx_sop_type)
3057 {
3058         enum pd_data_msg_type type = pd_header_type_le(msg->header);
3059         unsigned int cnt = pd_header_cnt_le(msg->header);
3060         unsigned int rev = pd_header_rev_le(msg->header);
3061         unsigned int i;
3062         enum frs_typec_current partner_frs_current;
3063         bool frs_enable;
3064         int ret;
3065
3066         if (tcpm_vdm_ams(port) && type != PD_DATA_VENDOR_DEF) {
3067                 port->vdm_state = VDM_STATE_ERR_BUSY;
3068                 tcpm_ams_finish(port);
3069                 mod_vdm_delayed_work(port, 0);
3070         }
3071
3072         switch (type) {
3073         case PD_DATA_SOURCE_CAP:
3074                 for (i = 0; i < cnt; i++)
3075                         port->source_caps[i] = le32_to_cpu(msg->payload[i]);
3076
3077                 port->nr_source_caps = cnt;
3078
3079                 tcpm_log_source_caps(port);
3080
3081                 tcpm_validate_caps(port, port->source_caps,
3082                                    port->nr_source_caps);
3083
3084                 tcpm_register_source_caps(port);
3085
3086                 /*
3087                  * Adjust revision in subsequent message headers, as required,
3088                  * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
3089                  * support Rev 1.0 so just do nothing in that scenario.
3090                  */
3091                 if (rev == PD_REV10) {
3092                         if (port->ams == GET_SOURCE_CAPABILITIES)
3093                                 tcpm_ams_finish(port);
3094                         break;
3095                 }
3096
3097                 if (rev < PD_MAX_REV) {
3098                         port->negotiated_rev = rev;
3099                         if (port->negotiated_rev_prime > port->negotiated_rev)
3100                                 port->negotiated_rev_prime = port->negotiated_rev;
3101                 }
3102
3103                 if (port->pwr_role == TYPEC_SOURCE) {
3104                         if (port->ams == GET_SOURCE_CAPABILITIES)
3105                                 tcpm_pd_handle_state(port, SRC_READY, NONE_AMS, 0);
3106                         /* Unexpected Source Capabilities */
3107                         else
3108                                 tcpm_pd_handle_msg(port,
3109                                                    port->negotiated_rev < PD_REV30 ?
3110                                                    PD_MSG_CTRL_REJECT :
3111                                                    PD_MSG_CTRL_NOT_SUPP,
3112                                                    NONE_AMS);
3113                 } else if (port->state == SNK_WAIT_CAPABILITIES) {
3114                 /*
3115                  * This message may be received even if VBUS is not
3116                  * present. This is quite unexpected; see USB PD
3117                  * specification, sections 8.3.3.6.3.1 and 8.3.3.6.3.2.
3118                  * However, at the same time, we must be ready to
3119                  * receive this message and respond to it 15ms after
3120                  * receiving PS_RDY during power swap operations, no matter
3121                  * if VBUS is available or not (USB PD specification,
3122                  * section 6.5.9.2).
3123                  * So we need to accept the message either way,
3124                  * but be prepared to keep waiting for VBUS after it was
3125                  * handled.
3126                  */
3127                         port->ams = POWER_NEGOTIATION;
3128                         port->in_ams = true;
3129                         tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
3130                 } else {
3131                         if (port->ams == GET_SOURCE_CAPABILITIES)
3132                                 tcpm_ams_finish(port);
3133                         tcpm_pd_handle_state(port, SNK_NEGOTIATE_CAPABILITIES,
3134                                              POWER_NEGOTIATION, 0);
3135                 }
3136                 break;
3137         case PD_DATA_REQUEST:
3138                 /*
3139                  * Adjust revision in subsequent message headers, as required,
3140                  * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
3141                  * support Rev 1.0 so just reject in that scenario.
3142                  */
3143                 if (rev == PD_REV10) {
3144                         tcpm_pd_handle_msg(port,
3145                                            port->negotiated_rev < PD_REV30 ?
3146                                            PD_MSG_CTRL_REJECT :
3147                                            PD_MSG_CTRL_NOT_SUPP,
3148                                            NONE_AMS);
3149                         break;
3150                 }
3151
3152                 if (rev < PD_MAX_REV) {
3153                         port->negotiated_rev = rev;
3154                         if (port->negotiated_rev_prime > port->negotiated_rev)
3155                                 port->negotiated_rev_prime = port->negotiated_rev;
3156                 }
3157
3158                 if (port->pwr_role != TYPEC_SOURCE || cnt != 1) {
3159                         tcpm_pd_handle_msg(port,
3160                                            port->negotiated_rev < PD_REV30 ?
3161                                            PD_MSG_CTRL_REJECT :
3162                                            PD_MSG_CTRL_NOT_SUPP,
3163                                            NONE_AMS);
3164                         break;
3165                 }
3166
3167                 port->sink_request = le32_to_cpu(msg->payload[0]);
3168
3169                 if (port->vdm_sm_running && port->explicit_contract) {
3170                         tcpm_pd_handle_msg(port, PD_MSG_CTRL_WAIT, port->ams);
3171                         break;
3172                 }
3173
3174                 if (port->state == SRC_SEND_CAPABILITIES)
3175                         tcpm_set_state(port, SRC_NEGOTIATE_CAPABILITIES, 0);
3176                 else
3177                         tcpm_pd_handle_state(port, SRC_NEGOTIATE_CAPABILITIES,
3178                                              POWER_NEGOTIATION, 0);
3179                 break;
3180         case PD_DATA_SINK_CAP:
3181                 /* We don't do anything with this at the moment... */
3182                 for (i = 0; i < cnt; i++)
3183                         port->sink_caps[i] = le32_to_cpu(msg->payload[i]);
3184
3185                 partner_frs_current = (port->sink_caps[0] & PDO_FIXED_FRS_CURR_MASK) >>
3186                         PDO_FIXED_FRS_CURR_SHIFT;
3187                 frs_enable = partner_frs_current && (partner_frs_current <=
3188                                                      port->new_source_frs_current);
3189                 tcpm_log(port,
3190                          "Port partner FRS capable partner_frs_current:%u port_frs_current:%u enable:%c",
3191                          partner_frs_current, port->new_source_frs_current, frs_enable ? 'y' : 'n');
3192                 if (frs_enable) {
3193                         ret  = port->tcpc->enable_frs(port->tcpc, true);
3194                         tcpm_log(port, "Enable FRS %s, ret:%d\n", ret ? "fail" : "success", ret);
3195                 }
3196
3197                 port->nr_sink_caps = cnt;
3198                 port->sink_cap_done = true;
3199                 tcpm_register_sink_caps(port);
3200
3201                 if (port->ams == GET_SINK_CAPABILITIES)
3202                         tcpm_set_state(port, ready_state(port), 0);
3203                 /* Unexpected Sink Capabilities */
3204                 else
3205                         tcpm_pd_handle_msg(port,
3206                                            port->negotiated_rev < PD_REV30 ?
3207                                            PD_MSG_CTRL_REJECT :
3208                                            PD_MSG_CTRL_NOT_SUPP,
3209                                            NONE_AMS);
3210                 break;
3211         case PD_DATA_VENDOR_DEF:
3212                 tcpm_handle_vdm_request(port, msg->payload, cnt, rx_sop_type);
3213                 break;
3214         case PD_DATA_BIST:
3215                 port->bist_request = le32_to_cpu(msg->payload[0]);
3216                 tcpm_pd_handle_state(port, BIST_RX, BIST, 0);
3217                 break;
3218         case PD_DATA_ALERT:
3219                 if (port->state != SRC_READY && port->state != SNK_READY)
3220                         tcpm_pd_handle_state(port, port->pwr_role == TYPEC_SOURCE ?
3221                                              SRC_SOFT_RESET_WAIT_SNK_TX : SNK_SOFT_RESET,
3222                                              NONE_AMS, 0);
3223                 else
3224                         tcpm_handle_alert(port, msg->payload, cnt);
3225                 break;
3226         case PD_DATA_BATT_STATUS:
3227         case PD_DATA_GET_COUNTRY_INFO:
3228                 /* Currently unsupported */
3229                 tcpm_pd_handle_msg(port, port->negotiated_rev < PD_REV30 ?
3230                                    PD_MSG_CTRL_REJECT :
3231                                    PD_MSG_CTRL_NOT_SUPP,
3232                                    NONE_AMS);
3233                 break;
3234         default:
3235                 tcpm_pd_handle_msg(port, port->negotiated_rev < PD_REV30 ?
3236                                    PD_MSG_CTRL_REJECT :
3237                                    PD_MSG_CTRL_NOT_SUPP,
3238                                    NONE_AMS);
3239                 tcpm_log(port, "Unrecognized data message type %#x", type);
3240                 break;
3241         }
3242 }
3243
3244 static void tcpm_pps_complete(struct tcpm_port *port, int result)
3245 {
3246         if (port->pps_pending) {
3247                 port->pps_status = result;
3248                 port->pps_pending = false;
3249                 complete(&port->pps_complete);
3250         }
3251 }
3252
3253 static void tcpm_pd_ctrl_request(struct tcpm_port *port,
3254                                  const struct pd_message *msg,
3255                                  enum tcpm_transmit_type rx_sop_type)
3256 {
3257         enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
3258         enum tcpm_state next_state;
3259         unsigned int rev = pd_header_rev_le(msg->header);
3260
3261         /*
3262          * Stop VDM state machine if interrupted by other Messages while NOT_SUPP is allowed in
3263          * VDM AMS if waiting for VDM responses and will be handled later.
3264          */
3265         if (tcpm_vdm_ams(port) && type != PD_CTRL_NOT_SUPP && type != PD_CTRL_GOOD_CRC) {
3266                 port->vdm_state = VDM_STATE_ERR_BUSY;
3267                 tcpm_ams_finish(port);
3268                 mod_vdm_delayed_work(port, 0);
3269         }
3270
3271         switch (type) {
3272         case PD_CTRL_GOOD_CRC:
3273         case PD_CTRL_PING:
3274                 break;
3275         case PD_CTRL_GET_SOURCE_CAP:
3276                 tcpm_pd_handle_msg(port, PD_MSG_DATA_SOURCE_CAP, GET_SOURCE_CAPABILITIES);
3277                 break;
3278         case PD_CTRL_GET_SINK_CAP:
3279                 tcpm_pd_handle_msg(port, PD_MSG_DATA_SINK_CAP, GET_SINK_CAPABILITIES);
3280                 break;
3281         case PD_CTRL_GOTO_MIN:
3282                 break;
3283         case PD_CTRL_PS_RDY:
3284                 switch (port->state) {
3285                 case SNK_TRANSITION_SINK:
3286                         if (port->vbus_present) {
3287                                 tcpm_set_current_limit(port,
3288                                                        port->req_current_limit,
3289                                                        port->req_supply_voltage);
3290                                 port->explicit_contract = true;
3291                                 tcpm_set_auto_vbus_discharge_threshold(port,
3292                                                                        TYPEC_PWR_MODE_PD,
3293                                                                        port->pps_data.active,
3294                                                                        port->supply_voltage);
3295                                 tcpm_set_state(port, SNK_READY, 0);
3296                         } else {
3297                                 /*
3298                                  * Seen after power swap. Keep waiting for VBUS
3299                                  * in a transitional state.
3300                                  */
3301                                 tcpm_set_state(port,
3302                                                SNK_TRANSITION_SINK_VBUS, 0);
3303                         }
3304                         break;
3305                 case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
3306                         tcpm_set_state(port, PR_SWAP_SRC_SNK_SINK_ON, 0);
3307                         break;
3308                 case PR_SWAP_SNK_SRC_SINK_OFF:
3309                         tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON, 0);
3310                         break;
3311                 case VCONN_SWAP_WAIT_FOR_VCONN:
3312                         tcpm_set_state(port, VCONN_SWAP_TURN_OFF_VCONN, 0);
3313                         break;
3314                 case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
3315                         tcpm_set_state(port, FR_SWAP_SNK_SRC_NEW_SINK_READY, 0);
3316                         break;
3317                 default:
3318                         tcpm_pd_handle_state(port,
3319                                              port->pwr_role == TYPEC_SOURCE ?
3320                                              SRC_SOFT_RESET_WAIT_SNK_TX :
3321                                              SNK_SOFT_RESET,
3322                                              NONE_AMS, 0);
3323                         break;
3324                 }
3325                 break;
3326         case PD_CTRL_REJECT:
3327         case PD_CTRL_WAIT:
3328         case PD_CTRL_NOT_SUPP:
3329                 switch (port->state) {
3330                 case SNK_NEGOTIATE_CAPABILITIES:
3331                         /* USB PD specification, Figure 8-43 */
3332                         if (port->explicit_contract)
3333                                 next_state = SNK_READY;
3334                         else
3335                                 next_state = SNK_WAIT_CAPABILITIES;
3336
3337                         /* Threshold was relaxed before sending Request. Restore it back. */
3338                         tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
3339                                                                port->pps_data.active,
3340                                                                port->supply_voltage);
3341                         tcpm_set_state(port, next_state, 0);
3342                         break;
3343                 case SNK_NEGOTIATE_PPS_CAPABILITIES:
3344                         /* Revert data back from any requested PPS updates */
3345                         port->pps_data.req_out_volt = port->supply_voltage;
3346                         port->pps_data.req_op_curr = port->current_limit;
3347                         port->pps_status = (type == PD_CTRL_WAIT ?
3348                                             -EAGAIN : -EOPNOTSUPP);
3349
3350                         /* Threshold was relaxed before sending Request. Restore it back. */
3351                         tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
3352                                                                port->pps_data.active,
3353                                                                port->supply_voltage);
3354
3355                         tcpm_set_state(port, SNK_READY, 0);
3356                         break;
3357                 case DR_SWAP_SEND:
3358                         port->swap_status = (type == PD_CTRL_WAIT ?
3359                                              -EAGAIN : -EOPNOTSUPP);
3360                         tcpm_set_state(port, DR_SWAP_CANCEL, 0);
3361                         break;
3362                 case PR_SWAP_SEND:
3363                         port->swap_status = (type == PD_CTRL_WAIT ?
3364                                              -EAGAIN : -EOPNOTSUPP);
3365                         tcpm_set_state(port, PR_SWAP_CANCEL, 0);
3366                         break;
3367                 case VCONN_SWAP_SEND:
3368                         port->swap_status = (type == PD_CTRL_WAIT ?
3369                                              -EAGAIN : -EOPNOTSUPP);
3370                         tcpm_set_state(port, VCONN_SWAP_CANCEL, 0);
3371                         break;
3372                 case FR_SWAP_SEND:
3373                         tcpm_set_state(port, FR_SWAP_CANCEL, 0);
3374                         break;
3375                 case GET_SINK_CAP:
3376                         port->sink_cap_done = true;
3377                         tcpm_set_state(port, ready_state(port), 0);
3378                         break;
3379                 /*
3380                  * Some port partners do not support GET_STATUS, avoid soft reset the link to
3381                  * prevent redundant power re-negotiation
3382                  */
3383                 case GET_STATUS_SEND:
3384                         tcpm_set_state(port, ready_state(port), 0);
3385                         break;
3386                 case SRC_READY:
3387                 case SNK_READY:
3388                         if (port->vdm_state > VDM_STATE_READY) {
3389                                 port->vdm_state = VDM_STATE_DONE;
3390                                 if (tcpm_vdm_ams(port))
3391                                         tcpm_ams_finish(port);
3392                                 mod_vdm_delayed_work(port, 0);
3393                                 break;
3394                         }
3395                         fallthrough;
3396                 default:
3397                         tcpm_pd_handle_state(port,
3398                                              port->pwr_role == TYPEC_SOURCE ?
3399                                              SRC_SOFT_RESET_WAIT_SNK_TX :
3400                                              SNK_SOFT_RESET,
3401                                              NONE_AMS, 0);
3402                         break;
3403                 }
3404                 break;
3405         case PD_CTRL_ACCEPT:
3406                 switch (port->state) {
3407                 case SNK_NEGOTIATE_CAPABILITIES:
3408                         port->pps_data.active = false;
3409                         tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
3410                         break;
3411                 case SNK_NEGOTIATE_PPS_CAPABILITIES:
3412                         port->pps_data.active = true;
3413                         port->pps_data.min_volt = port->pps_data.req_min_volt;
3414                         port->pps_data.max_volt = port->pps_data.req_max_volt;
3415                         port->pps_data.max_curr = port->pps_data.req_max_curr;
3416                         port->req_supply_voltage = port->pps_data.req_out_volt;
3417                         port->req_current_limit = port->pps_data.req_op_curr;
3418                         power_supply_changed(port->psy);
3419                         tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
3420                         break;
3421                 case SOFT_RESET_SEND:
3422                         if (port->ams == SOFT_RESET_AMS)
3423                                 tcpm_ams_finish(port);
3424                         /*
3425                          * SOP' Soft Reset is done after Vconn Swap,
3426                          * which returns to ready state
3427                          */
3428                         if (rx_sop_type == TCPC_TX_SOP_PRIME) {
3429                                 if (rev < port->negotiated_rev_prime)
3430                                         port->negotiated_rev_prime = rev;
3431                                 tcpm_set_state(port, ready_state(port), 0);
3432                                 break;
3433                         }
3434                         if (port->pwr_role == TYPEC_SOURCE) {
3435                                 port->upcoming_state = SRC_SEND_CAPABILITIES;
3436                                 tcpm_ams_start(port, POWER_NEGOTIATION);
3437                         } else {
3438                                 tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
3439                         }
3440                         break;
3441                 case DR_SWAP_SEND:
3442                         tcpm_set_state(port, DR_SWAP_CHANGE_DR, 0);
3443                         break;
3444                 case PR_SWAP_SEND:
3445                         tcpm_set_state(port, PR_SWAP_START, 0);
3446                         break;
3447                 case VCONN_SWAP_SEND:
3448                         tcpm_set_state(port, VCONN_SWAP_START, 0);
3449                         break;
3450                 case FR_SWAP_SEND:
3451                         tcpm_set_state(port, FR_SWAP_SNK_SRC_TRANSITION_TO_OFF, 0);
3452                         break;
3453                 default:
3454                         tcpm_pd_handle_state(port,
3455                                              port->pwr_role == TYPEC_SOURCE ?
3456                                              SRC_SOFT_RESET_WAIT_SNK_TX :
3457                                              SNK_SOFT_RESET,
3458                                              NONE_AMS, 0);
3459                         break;
3460                 }
3461                 break;
3462         case PD_CTRL_SOFT_RESET:
3463                 port->ams = SOFT_RESET_AMS;
3464                 tcpm_set_state(port, SOFT_RESET, 0);
3465                 break;
3466         case PD_CTRL_DR_SWAP:
3467                 /*
3468                  * XXX
3469                  * 6.3.9: If an alternate mode is active, a request to swap
3470                  * alternate modes shall trigger a port reset.
3471                  */
3472                 if (port->typec_caps.data != TYPEC_PORT_DRD) {
3473                         tcpm_pd_handle_msg(port,
3474                                            port->negotiated_rev < PD_REV30 ?
3475                                            PD_MSG_CTRL_REJECT :
3476                                            PD_MSG_CTRL_NOT_SUPP,
3477                                            NONE_AMS);
3478                 } else {
3479                         if (port->send_discover && port->negotiated_rev < PD_REV30) {
3480                                 tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
3481                                 break;
3482                         }
3483
3484                         tcpm_pd_handle_state(port, DR_SWAP_ACCEPT, DATA_ROLE_SWAP, 0);
3485                 }
3486                 break;
3487         case PD_CTRL_PR_SWAP:
3488                 if (port->port_type != TYPEC_PORT_DRP) {
3489                         tcpm_pd_handle_msg(port,
3490                                            port->negotiated_rev < PD_REV30 ?
3491                                            PD_MSG_CTRL_REJECT :
3492                                            PD_MSG_CTRL_NOT_SUPP,
3493                                            NONE_AMS);
3494                 } else {
3495                         if (port->send_discover && port->negotiated_rev < PD_REV30) {
3496                                 tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
3497                                 break;
3498                         }
3499
3500                         tcpm_pd_handle_state(port, PR_SWAP_ACCEPT, POWER_ROLE_SWAP, 0);
3501                 }
3502                 break;
3503         case PD_CTRL_VCONN_SWAP:
3504                 if (port->send_discover && port->negotiated_rev < PD_REV30) {
3505                         tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
3506                         break;
3507                 }
3508
3509                 tcpm_pd_handle_state(port, VCONN_SWAP_ACCEPT, VCONN_SWAP, 0);
3510                 break;
3511         case PD_CTRL_GET_SOURCE_CAP_EXT:
3512         case PD_CTRL_GET_STATUS:
3513         case PD_CTRL_FR_SWAP:
3514         case PD_CTRL_GET_PPS_STATUS:
3515         case PD_CTRL_GET_COUNTRY_CODES:
3516                 /* Currently not supported */
3517                 tcpm_pd_handle_msg(port,
3518                                    port->negotiated_rev < PD_REV30 ?
3519                                    PD_MSG_CTRL_REJECT :
3520                                    PD_MSG_CTRL_NOT_SUPP,
3521                                    NONE_AMS);
3522                 break;
3523         default:
3524                 tcpm_pd_handle_msg(port,
3525                                    port->negotiated_rev < PD_REV30 ?
3526                                    PD_MSG_CTRL_REJECT :
3527                                    PD_MSG_CTRL_NOT_SUPP,
3528                                    NONE_AMS);
3529                 tcpm_log(port, "Unrecognized ctrl message type %#x", type);
3530                 break;
3531         }
3532 }
3533
3534 static void tcpm_pd_ext_msg_request(struct tcpm_port *port,
3535                                     const struct pd_message *msg)
3536 {
3537         enum pd_ext_msg_type type = pd_header_type_le(msg->header);
3538         unsigned int data_size = pd_ext_header_data_size_le(msg->ext_msg.header);
3539
3540         /* stopping VDM state machine if interrupted by other Messages */
3541         if (tcpm_vdm_ams(port)) {
3542                 port->vdm_state = VDM_STATE_ERR_BUSY;
3543                 tcpm_ams_finish(port);
3544                 mod_vdm_delayed_work(port, 0);
3545         }
3546
3547         if (!(le16_to_cpu(msg->ext_msg.header) & PD_EXT_HDR_CHUNKED)) {
3548                 tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
3549                 tcpm_log(port, "Unchunked extended messages unsupported");
3550                 return;
3551         }
3552
3553         if (data_size > PD_EXT_MAX_CHUNK_DATA) {
3554                 tcpm_pd_handle_state(port, CHUNK_NOT_SUPP, NONE_AMS, PD_T_CHUNK_NOT_SUPP);
3555                 tcpm_log(port, "Chunk handling not yet supported");
3556                 return;
3557         }
3558
3559         switch (type) {
3560         case PD_EXT_STATUS:
3561         case PD_EXT_PPS_STATUS:
3562                 if (port->ams == GETTING_SOURCE_SINK_STATUS) {
3563                         tcpm_ams_finish(port);
3564                         tcpm_set_state(port, ready_state(port), 0);
3565                 } else {
3566                         /* unexpected Status or PPS_Status Message */
3567                         tcpm_pd_handle_state(port, port->pwr_role == TYPEC_SOURCE ?
3568                                              SRC_SOFT_RESET_WAIT_SNK_TX : SNK_SOFT_RESET,
3569                                              NONE_AMS, 0);
3570                 }
3571                 break;
3572         case PD_EXT_SOURCE_CAP_EXT:
3573         case PD_EXT_GET_BATT_CAP:
3574         case PD_EXT_GET_BATT_STATUS:
3575         case PD_EXT_BATT_CAP:
3576         case PD_EXT_GET_MANUFACTURER_INFO:
3577         case PD_EXT_MANUFACTURER_INFO:
3578         case PD_EXT_SECURITY_REQUEST:
3579         case PD_EXT_SECURITY_RESPONSE:
3580         case PD_EXT_FW_UPDATE_REQUEST:
3581         case PD_EXT_FW_UPDATE_RESPONSE:
3582         case PD_EXT_COUNTRY_INFO:
3583         case PD_EXT_COUNTRY_CODES:
3584                 tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
3585                 break;
3586         default:
3587                 tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
3588                 tcpm_log(port, "Unrecognized extended message type %#x", type);
3589                 break;
3590         }
3591 }
3592
3593 static void tcpm_pd_rx_handler(struct kthread_work *work)
3594 {
3595         struct pd_rx_event *event = container_of(work,
3596                                                  struct pd_rx_event, work);
3597         const struct pd_message *msg = &event->msg;
3598         unsigned int cnt = pd_header_cnt_le(msg->header);
3599         struct tcpm_port *port = event->port;
3600         enum tcpm_transmit_type rx_sop_type = event->rx_sop_type;
3601
3602         mutex_lock(&port->lock);
3603
3604         tcpm_log(port, "PD RX, header: %#x [%d]", le16_to_cpu(msg->header),
3605                  port->attached);
3606
3607         if (port->attached) {
3608                 enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
3609                 unsigned int msgid = pd_header_msgid_le(msg->header);
3610
3611                 /*
3612                  * Drop SOP' messages if cannot receive via
3613                  * tcpm_can_communicate_sop_prime
3614                  */
3615                 if (rx_sop_type == TCPC_TX_SOP_PRIME &&
3616                     !tcpm_can_communicate_sop_prime(port))
3617                         goto done;
3618
3619                 /*
3620                  * USB PD standard, 6.6.1.2:
3621                  * "... if MessageID value in a received Message is the
3622                  * same as the stored value, the receiver shall return a
3623                  * GoodCRC Message with that MessageID value and drop
3624                  * the Message (this is a retry of an already received
3625                  * Message). Note: this shall not apply to the Soft_Reset
3626                  * Message which always has a MessageID value of zero."
3627                  */
3628                 switch (rx_sop_type) {
3629                 case TCPC_TX_SOP_PRIME:
3630                         if (msgid == port->rx_msgid_prime)
3631                                 goto done;
3632                         port->rx_msgid_prime = msgid;
3633                         break;
3634                 case TCPC_TX_SOP:
3635                 default:
3636                         if (msgid == port->rx_msgid && type != PD_CTRL_SOFT_RESET)
3637                                 goto done;
3638                         port->rx_msgid = msgid;
3639                         break;
3640                 }
3641
3642                 /*
3643                  * If both ends believe to be DFP/host, we have a data role
3644                  * mismatch.
3645                  */
3646                 if (!!(le16_to_cpu(msg->header) & PD_HEADER_DATA_ROLE) ==
3647                     (port->data_role == TYPEC_HOST) && rx_sop_type == TCPC_TX_SOP) {
3648                         tcpm_log(port,
3649                                  "Data role mismatch, initiating error recovery");
3650                         tcpm_set_state(port, ERROR_RECOVERY, 0);
3651                 } else {
3652                         if (le16_to_cpu(msg->header) & PD_HEADER_EXT_HDR)
3653                                 tcpm_pd_ext_msg_request(port, msg);
3654                         else if (cnt)
3655                                 tcpm_pd_data_request(port, msg, rx_sop_type);
3656                         else
3657                                 tcpm_pd_ctrl_request(port, msg, rx_sop_type);
3658                 }
3659         }
3660
3661 done:
3662         mutex_unlock(&port->lock);
3663         kfree(event);
3664 }
3665
3666 void tcpm_pd_receive(struct tcpm_port *port, const struct pd_message *msg,
3667                      enum tcpm_transmit_type rx_sop_type)
3668 {
3669         struct pd_rx_event *event;
3670
3671         event = kzalloc(sizeof(*event), GFP_ATOMIC);
3672         if (!event)
3673                 return;
3674
3675         kthread_init_work(&event->work, tcpm_pd_rx_handler);
3676         event->port = port;
3677         event->rx_sop_type = rx_sop_type;
3678         memcpy(&event->msg, msg, sizeof(*msg));
3679         kthread_queue_work(port->wq, &event->work);
3680 }
3681 EXPORT_SYMBOL_GPL(tcpm_pd_receive);
3682
3683 static int tcpm_pd_send_control(struct tcpm_port *port,
3684                                 enum pd_ctrl_msg_type type,
3685                                 enum tcpm_transmit_type tx_sop_type)
3686 {
3687         struct pd_message msg;
3688
3689         memset(&msg, 0, sizeof(msg));
3690         switch (tx_sop_type) {
3691         case TCPC_TX_SOP_PRIME:
3692                 msg.header = PD_HEADER_LE(type,
3693                                           0,    /* Cable Plug Indicator for DFP/UFP */
3694                                           0,    /* Reserved */
3695                                           port->negotiated_rev,
3696                                           port->message_id_prime,
3697                                           0);
3698                 break;
3699         case TCPC_TX_SOP:
3700                 msg.header = PD_HEADER_LE(type,
3701                                           port->pwr_role,
3702                                           port->data_role,
3703                                           port->negotiated_rev,
3704                                           port->message_id,
3705                                           0);
3706                 break;
3707         default:
3708                 msg.header = PD_HEADER_LE(type,
3709                                           port->pwr_role,
3710                                           port->data_role,
3711                                           port->negotiated_rev,
3712                                           port->message_id,
3713                                           0);
3714                 break;
3715         }
3716
3717         return tcpm_pd_transmit(port, tx_sop_type, &msg);
3718 }
3719
3720 /*
3721  * Send queued message without affecting state.
3722  * Return true if state machine should go back to sleep,
3723  * false otherwise.
3724  */
3725 static bool tcpm_send_queued_message(struct tcpm_port *port)
3726 {
3727         enum pd_msg_request queued_message;
3728         int ret;
3729
3730         do {
3731                 queued_message = port->queued_message;
3732                 port->queued_message = PD_MSG_NONE;
3733
3734                 switch (queued_message) {
3735                 case PD_MSG_CTRL_WAIT:
3736                         tcpm_pd_send_control(port, PD_CTRL_WAIT, TCPC_TX_SOP);
3737                         break;
3738                 case PD_MSG_CTRL_REJECT:
3739                         tcpm_pd_send_control(port, PD_CTRL_REJECT, TCPC_TX_SOP);
3740                         break;
3741                 case PD_MSG_CTRL_NOT_SUPP:
3742                         tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP, TCPC_TX_SOP);
3743                         break;
3744                 case PD_MSG_DATA_SINK_CAP:
3745                         ret = tcpm_pd_send_sink_caps(port);
3746                         if (ret < 0) {
3747                                 tcpm_log(port, "Unable to send snk caps, ret=%d", ret);
3748                                 tcpm_set_state(port, SNK_SOFT_RESET, 0);
3749                         }
3750                         tcpm_ams_finish(port);
3751                         break;
3752                 case PD_MSG_DATA_SOURCE_CAP:
3753                         ret = tcpm_pd_send_source_caps(port);
3754                         if (ret < 0) {
3755                                 tcpm_log(port,
3756                                          "Unable to send src caps, ret=%d",
3757                                          ret);
3758                                 tcpm_set_state(port, SOFT_RESET_SEND, 0);
3759                         } else if (port->pwr_role == TYPEC_SOURCE) {
3760                                 tcpm_ams_finish(port);
3761                                 tcpm_set_state(port, HARD_RESET_SEND,
3762                                                PD_T_SENDER_RESPONSE);
3763                         } else {
3764                                 tcpm_ams_finish(port);
3765                         }
3766                         break;
3767                 default:
3768                         break;
3769                 }
3770         } while (port->queued_message != PD_MSG_NONE);
3771
3772         if (port->delayed_state != INVALID_STATE) {
3773                 if (ktime_after(port->delayed_runtime, ktime_get())) {
3774                         mod_tcpm_delayed_work(port, ktime_to_ms(ktime_sub(port->delayed_runtime,
3775                                                                           ktime_get())));
3776                         return true;
3777                 }
3778                 port->delayed_state = INVALID_STATE;
3779         }
3780         return false;
3781 }
3782
3783 static int tcpm_pd_check_request(struct tcpm_port *port)
3784 {
3785         u32 pdo, rdo = port->sink_request;
3786         unsigned int max, op, pdo_max, index;
3787         enum pd_pdo_type type;
3788
3789         index = rdo_index(rdo);
3790         if (!index || index > port->nr_src_pdo)
3791                 return -EINVAL;
3792
3793         pdo = port->src_pdo[index - 1];
3794         type = pdo_type(pdo);
3795         switch (type) {
3796         case PDO_TYPE_FIXED:
3797         case PDO_TYPE_VAR:
3798                 max = rdo_max_current(rdo);
3799                 op = rdo_op_current(rdo);
3800                 pdo_max = pdo_max_current(pdo);
3801
3802                 if (op > pdo_max)
3803                         return -EINVAL;
3804                 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
3805                         return -EINVAL;
3806
3807                 if (type == PDO_TYPE_FIXED)
3808                         tcpm_log(port,
3809                                  "Requested %u mV, %u mA for %u / %u mA",
3810                                  pdo_fixed_voltage(pdo), pdo_max, op, max);
3811                 else
3812                         tcpm_log(port,
3813                                  "Requested %u -> %u mV, %u mA for %u / %u mA",
3814                                  pdo_min_voltage(pdo), pdo_max_voltage(pdo),
3815                                  pdo_max, op, max);
3816                 break;
3817         case PDO_TYPE_BATT:
3818                 max = rdo_max_power(rdo);
3819                 op = rdo_op_power(rdo);
3820                 pdo_max = pdo_max_power(pdo);
3821
3822                 if (op > pdo_max)
3823                         return -EINVAL;
3824                 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
3825                         return -EINVAL;
3826                 tcpm_log(port,
3827                          "Requested %u -> %u mV, %u mW for %u / %u mW",
3828                          pdo_min_voltage(pdo), pdo_max_voltage(pdo),
3829                          pdo_max, op, max);
3830                 break;
3831         default:
3832                 return -EINVAL;
3833         }
3834
3835         port->op_vsafe5v = index == 1;
3836
3837         return 0;
3838 }
3839
3840 #define min_power(x, y) min(pdo_max_power(x), pdo_max_power(y))
3841 #define min_current(x, y) min(pdo_max_current(x), pdo_max_current(y))
3842
3843 static int tcpm_pd_select_pdo(struct tcpm_port *port, int *sink_pdo,
3844                               int *src_pdo)
3845 {
3846         unsigned int i, j, max_src_mv = 0, min_src_mv = 0, max_mw = 0,
3847                      max_mv = 0, src_mw = 0, src_ma = 0, max_snk_mv = 0,
3848                      min_snk_mv = 0;
3849         int ret = -EINVAL;
3850
3851         port->pps_data.supported = false;
3852         port->usb_type = POWER_SUPPLY_USB_TYPE_PD;
3853         power_supply_changed(port->psy);
3854
3855         /*
3856          * Select the source PDO providing the most power which has a
3857          * matchig sink cap.
3858          */
3859         for (i = 0; i < port->nr_source_caps; i++) {
3860                 u32 pdo = port->source_caps[i];
3861                 enum pd_pdo_type type = pdo_type(pdo);
3862
3863                 switch (type) {
3864                 case PDO_TYPE_FIXED:
3865                         max_src_mv = pdo_fixed_voltage(pdo);
3866                         min_src_mv = max_src_mv;
3867                         break;
3868                 case PDO_TYPE_BATT:
3869                 case PDO_TYPE_VAR:
3870                         max_src_mv = pdo_max_voltage(pdo);
3871                         min_src_mv = pdo_min_voltage(pdo);
3872                         break;
3873                 case PDO_TYPE_APDO:
3874                         if (pdo_apdo_type(pdo) == APDO_TYPE_PPS) {
3875                                 port->pps_data.supported = true;
3876                                 port->usb_type =
3877                                         POWER_SUPPLY_USB_TYPE_PD_PPS;
3878                                 power_supply_changed(port->psy);
3879                         }
3880                         continue;
3881                 default:
3882                         tcpm_log(port, "Invalid source PDO type, ignoring");
3883                         continue;
3884                 }
3885
3886                 switch (type) {
3887                 case PDO_TYPE_FIXED:
3888                 case PDO_TYPE_VAR:
3889                         src_ma = pdo_max_current(pdo);
3890                         src_mw = src_ma * min_src_mv / 1000;
3891                         break;
3892                 case PDO_TYPE_BATT:
3893                         src_mw = pdo_max_power(pdo);
3894                         break;
3895                 case PDO_TYPE_APDO:
3896                         continue;
3897                 default:
3898                         tcpm_log(port, "Invalid source PDO type, ignoring");
3899                         continue;
3900                 }
3901
3902                 for (j = 0; j < port->nr_snk_pdo; j++) {
3903                         pdo = port->snk_pdo[j];
3904
3905                         switch (pdo_type(pdo)) {
3906                         case PDO_TYPE_FIXED:
3907                                 max_snk_mv = pdo_fixed_voltage(pdo);
3908                                 min_snk_mv = max_snk_mv;
3909                                 break;
3910                         case PDO_TYPE_BATT:
3911                         case PDO_TYPE_VAR:
3912                                 max_snk_mv = pdo_max_voltage(pdo);
3913                                 min_snk_mv = pdo_min_voltage(pdo);
3914                                 break;
3915                         case PDO_TYPE_APDO:
3916                                 continue;
3917                         default:
3918                                 tcpm_log(port, "Invalid sink PDO type, ignoring");
3919                                 continue;
3920                         }
3921
3922                         if (max_src_mv <= max_snk_mv &&
3923                                 min_src_mv >= min_snk_mv) {
3924                                 /* Prefer higher voltages if available */
3925                                 if ((src_mw == max_mw && min_src_mv > max_mv) ||
3926                                                         src_mw > max_mw) {
3927                                         *src_pdo = i;
3928                                         *sink_pdo = j;
3929                                         max_mw = src_mw;
3930                                         max_mv = min_src_mv;
3931                                         ret = 0;
3932                                 }
3933                         }
3934                 }
3935         }
3936
3937         return ret;
3938 }
3939
3940 static unsigned int tcpm_pd_select_pps_apdo(struct tcpm_port *port)
3941 {
3942         unsigned int i, src_ma, max_temp_mw = 0, max_op_ma, op_mw;
3943         unsigned int src_pdo = 0;
3944         u32 pdo, src;
3945
3946         for (i = 1; i < port->nr_source_caps; ++i) {
3947                 pdo = port->source_caps[i];
3948
3949                 switch (pdo_type(pdo)) {
3950                 case PDO_TYPE_APDO:
3951                         if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
3952                                 tcpm_log(port, "Not PPS APDO (source), ignoring");
3953                                 continue;
3954                         }
3955
3956                         if (port->pps_data.req_out_volt > pdo_pps_apdo_max_voltage(pdo) ||
3957                             port->pps_data.req_out_volt < pdo_pps_apdo_min_voltage(pdo))
3958                                 continue;
3959
3960                         src_ma = pdo_pps_apdo_max_current(pdo);
3961                         max_op_ma = min(src_ma, port->pps_data.req_op_curr);
3962                         op_mw = max_op_ma * port->pps_data.req_out_volt / 1000;
3963                         if (op_mw > max_temp_mw) {
3964                                 src_pdo = i;
3965                                 max_temp_mw = op_mw;
3966                         }
3967                         break;
3968                 default:
3969                         tcpm_log(port, "Not APDO type (source), ignoring");
3970                         continue;
3971                 }
3972         }
3973
3974         if (src_pdo) {
3975                 src = port->source_caps[src_pdo];
3976
3977                 port->pps_data.req_min_volt = pdo_pps_apdo_min_voltage(src);
3978                 port->pps_data.req_max_volt = pdo_pps_apdo_max_voltage(src);
3979                 port->pps_data.req_max_curr = pdo_pps_apdo_max_current(src);
3980                 port->pps_data.req_op_curr = min(port->pps_data.req_max_curr,
3981                                                  port->pps_data.req_op_curr);
3982         }
3983
3984         return src_pdo;
3985 }
3986
3987 static int tcpm_pd_build_request(struct tcpm_port *port, u32 *rdo)
3988 {
3989         unsigned int mv, ma, mw, flags;
3990         unsigned int max_ma, max_mw;
3991         enum pd_pdo_type type;
3992         u32 pdo, matching_snk_pdo;
3993         int src_pdo_index = 0;
3994         int snk_pdo_index = 0;
3995         int ret;
3996
3997         ret = tcpm_pd_select_pdo(port, &snk_pdo_index, &src_pdo_index);
3998         if (ret < 0)
3999                 return ret;
4000
4001         pdo = port->source_caps[src_pdo_index];
4002         matching_snk_pdo = port->snk_pdo[snk_pdo_index];
4003         type = pdo_type(pdo);
4004
4005         switch (type) {
4006         case PDO_TYPE_FIXED:
4007                 mv = pdo_fixed_voltage(pdo);
4008                 break;
4009         case PDO_TYPE_BATT:
4010         case PDO_TYPE_VAR:
4011                 mv = pdo_min_voltage(pdo);
4012                 break;
4013         default:
4014                 tcpm_log(port, "Invalid PDO selected!");
4015                 return -EINVAL;
4016         }
4017
4018         /* Select maximum available current within the sink pdo's limit */
4019         if (type == PDO_TYPE_BATT) {
4020                 mw = min_power(pdo, matching_snk_pdo);
4021                 ma = 1000 * mw / mv;
4022         } else {
4023                 ma = min_current(pdo, matching_snk_pdo);
4024                 mw = ma * mv / 1000;
4025         }
4026
4027         flags = RDO_USB_COMM | RDO_NO_SUSPEND;
4028
4029         /* Set mismatch bit if offered power is less than operating power */
4030         max_ma = ma;
4031         max_mw = mw;
4032         if (mw < port->operating_snk_mw) {
4033                 flags |= RDO_CAP_MISMATCH;
4034                 if (type == PDO_TYPE_BATT &&
4035                     (pdo_max_power(matching_snk_pdo) > pdo_max_power(pdo)))
4036                         max_mw = pdo_max_power(matching_snk_pdo);
4037                 else if (pdo_max_current(matching_snk_pdo) >
4038                          pdo_max_current(pdo))
4039                         max_ma = pdo_max_current(matching_snk_pdo);
4040         }
4041
4042         tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
4043                  port->cc_req, port->cc1, port->cc2, port->vbus_source,
4044                  port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
4045                  port->polarity);
4046
4047         if (type == PDO_TYPE_BATT) {
4048                 *rdo = RDO_BATT(src_pdo_index + 1, mw, max_mw, flags);
4049
4050                 tcpm_log(port, "Requesting PDO %d: %u mV, %u mW%s",
4051                          src_pdo_index, mv, mw,
4052                          flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
4053         } else {
4054                 *rdo = RDO_FIXED(src_pdo_index + 1, ma, max_ma, flags);
4055
4056                 tcpm_log(port, "Requesting PDO %d: %u mV, %u mA%s",
4057                          src_pdo_index, mv, ma,
4058                          flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
4059         }
4060
4061         port->req_current_limit = ma;
4062         port->req_supply_voltage = mv;
4063
4064         return 0;
4065 }
4066
4067 static int tcpm_pd_send_request(struct tcpm_port *port)
4068 {
4069         struct pd_message msg;
4070         int ret;
4071         u32 rdo;
4072
4073         ret = tcpm_pd_build_request(port, &rdo);
4074         if (ret < 0)
4075                 return ret;
4076
4077         /*
4078          * Relax the threshold as voltage will be adjusted after Accept Message plus tSrcTransition.
4079          * It is safer to modify the threshold here.
4080          */
4081         tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
4082
4083         memset(&msg, 0, sizeof(msg));
4084         msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
4085                                   port->pwr_role,
4086                                   port->data_role,
4087                                   port->negotiated_rev,
4088                                   port->message_id, 1);
4089         msg.payload[0] = cpu_to_le32(rdo);
4090
4091         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
4092 }
4093
4094 static int tcpm_pd_build_pps_request(struct tcpm_port *port, u32 *rdo)
4095 {
4096         unsigned int out_mv, op_ma, op_mw, max_mv, max_ma, flags;
4097         unsigned int src_pdo_index;
4098
4099         src_pdo_index = tcpm_pd_select_pps_apdo(port);
4100         if (!src_pdo_index)
4101                 return -EOPNOTSUPP;
4102
4103         max_mv = port->pps_data.req_max_volt;
4104         max_ma = port->pps_data.req_max_curr;
4105         out_mv = port->pps_data.req_out_volt;
4106         op_ma = port->pps_data.req_op_curr;
4107
4108         flags = RDO_USB_COMM | RDO_NO_SUSPEND;
4109
4110         op_mw = (op_ma * out_mv) / 1000;
4111         if (op_mw < port->operating_snk_mw) {
4112                 /*
4113                  * Try raising current to meet power needs. If that's not enough
4114                  * then try upping the voltage. If that's still not enough
4115                  * then we've obviously chosen a PPS APDO which really isn't
4116                  * suitable so abandon ship.
4117                  */
4118                 op_ma = (port->operating_snk_mw * 1000) / out_mv;
4119                 if ((port->operating_snk_mw * 1000) % out_mv)
4120                         ++op_ma;
4121                 op_ma += RDO_PROG_CURR_MA_STEP - (op_ma % RDO_PROG_CURR_MA_STEP);
4122
4123                 if (op_ma > max_ma) {
4124                         op_ma = max_ma;
4125                         out_mv = (port->operating_snk_mw * 1000) / op_ma;
4126                         if ((port->operating_snk_mw * 1000) % op_ma)
4127                                 ++out_mv;
4128                         out_mv += RDO_PROG_VOLT_MV_STEP -
4129                                   (out_mv % RDO_PROG_VOLT_MV_STEP);
4130
4131                         if (out_mv > max_mv) {
4132                                 tcpm_log(port, "Invalid PPS APDO selected!");
4133                                 return -EINVAL;
4134                         }
4135                 }
4136         }
4137
4138         tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
4139                  port->cc_req, port->cc1, port->cc2, port->vbus_source,
4140                  port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
4141                  port->polarity);
4142
4143         *rdo = RDO_PROG(src_pdo_index + 1, out_mv, op_ma, flags);
4144
4145         tcpm_log(port, "Requesting APDO %d: %u mV, %u mA",
4146                  src_pdo_index, out_mv, op_ma);
4147
4148         port->pps_data.req_op_curr = op_ma;
4149         port->pps_data.req_out_volt = out_mv;
4150
4151         return 0;
4152 }
4153
4154 static int tcpm_pd_send_pps_request(struct tcpm_port *port)
4155 {
4156         struct pd_message msg;
4157         int ret;
4158         u32 rdo;
4159
4160         ret = tcpm_pd_build_pps_request(port, &rdo);
4161         if (ret < 0)
4162                 return ret;
4163
4164         /* Relax the threshold as voltage will be adjusted right after Accept Message. */
4165         tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
4166
4167         memset(&msg, 0, sizeof(msg));
4168         msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
4169                                   port->pwr_role,
4170                                   port->data_role,
4171                                   port->negotiated_rev,
4172                                   port->message_id, 1);
4173         msg.payload[0] = cpu_to_le32(rdo);
4174
4175         return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
4176 }
4177
4178 static int tcpm_set_vbus(struct tcpm_port *port, bool enable)
4179 {
4180         int ret;
4181
4182         if (enable && port->vbus_charge)
4183                 return -EINVAL;
4184
4185         tcpm_log(port, "vbus:=%d charge=%d", enable, port->vbus_charge);
4186
4187         ret = port->tcpc->set_vbus(port->tcpc, enable, port->vbus_charge);
4188         if (ret < 0)
4189                 return ret;
4190
4191         port->vbus_source = enable;
4192         return 0;
4193 }
4194
4195 static int tcpm_set_charge(struct tcpm_port *port, bool charge)
4196 {
4197         int ret;
4198
4199         if (charge && port->vbus_source)
4200                 return -EINVAL;
4201
4202         if (charge != port->vbus_charge) {
4203                 tcpm_log(port, "vbus=%d charge:=%d", port->vbus_source, charge);
4204                 ret = port->tcpc->set_vbus(port->tcpc, port->vbus_source,
4205                                            charge);
4206                 if (ret < 0)
4207                         return ret;
4208         }
4209         port->vbus_charge = charge;
4210         power_supply_changed(port->psy);
4211         return 0;
4212 }
4213
4214 static bool tcpm_start_toggling(struct tcpm_port *port, enum typec_cc_status cc)
4215 {
4216         int ret;
4217
4218         if (!port->tcpc->start_toggling)
4219                 return false;
4220
4221         tcpm_log_force(port, "Start toggling");
4222         ret = port->tcpc->start_toggling(port->tcpc, port->port_type, cc);
4223         return ret == 0;
4224 }
4225
4226 static int tcpm_init_vbus(struct tcpm_port *port)
4227 {
4228         int ret;
4229
4230         ret = port->tcpc->set_vbus(port->tcpc, false, false);
4231         port->vbus_source = false;
4232         port->vbus_charge = false;
4233         return ret;
4234 }
4235
4236 static int tcpm_init_vconn(struct tcpm_port *port)
4237 {
4238         int ret;
4239
4240         ret = port->tcpc->set_vconn(port->tcpc, false);
4241         port->vconn_role = TYPEC_SINK;
4242         return ret;
4243 }
4244
4245 static void tcpm_typec_connect(struct tcpm_port *port)
4246 {
4247         struct typec_partner *partner;
4248
4249         if (!port->connected) {
4250                 port->connected = true;
4251                 /* Make sure we don't report stale identity information */
4252                 memset(&port->partner_ident, 0, sizeof(port->partner_ident));
4253                 port->partner_desc.usb_pd = port->pd_capable;
4254                 if (tcpm_port_is_debug(port))
4255                         port->partner_desc.accessory = TYPEC_ACCESSORY_DEBUG;
4256                 else if (tcpm_port_is_audio(port))
4257                         port->partner_desc.accessory = TYPEC_ACCESSORY_AUDIO;
4258                 else
4259                         port->partner_desc.accessory = TYPEC_ACCESSORY_NONE;
4260                 partner = typec_register_partner(port->typec_port, &port->partner_desc);
4261                 if (IS_ERR(partner)) {
4262                         dev_err(port->dev, "Failed to register partner (%ld)\n", PTR_ERR(partner));
4263                         return;
4264                 }
4265
4266                 port->partner = partner;
4267                 typec_partner_set_usb_power_delivery(port->partner, port->partner_pd);
4268         }
4269 }
4270
4271 static int tcpm_src_attach(struct tcpm_port *port)
4272 {
4273         enum typec_cc_polarity polarity =
4274                                 port->cc2 == TYPEC_CC_RD ? TYPEC_POLARITY_CC2
4275                                                          : TYPEC_POLARITY_CC1;
4276         int ret;
4277
4278         if (port->attached)
4279                 return 0;
4280
4281         ret = tcpm_set_polarity(port, polarity);
4282         if (ret < 0)
4283                 return ret;
4284
4285         tcpm_enable_auto_vbus_discharge(port, true);
4286
4287         ret = tcpm_set_roles(port, true, TYPEC_SOURCE, tcpm_data_role_for_source(port));
4288         if (ret < 0)
4289                 return ret;
4290
4291         if (port->pd_supported) {
4292                 ret = port->tcpc->set_pd_rx(port->tcpc, true);
4293                 if (ret < 0)
4294                         goto out_disable_mux;
4295         }
4296
4297         /*
4298          * USB Type-C specification, version 1.2,
4299          * chapter 4.5.2.2.8.1 (Attached.SRC Requirements)
4300          * Enable VCONN only if the non-RD port is set to RA.
4301          */
4302         if ((polarity == TYPEC_POLARITY_CC1 && port->cc2 == TYPEC_CC_RA) ||
4303             (polarity == TYPEC_POLARITY_CC2 && port->cc1 == TYPEC_CC_RA)) {
4304                 ret = tcpm_set_vconn(port, true);
4305                 if (ret < 0)
4306                         goto out_disable_pd;
4307         }
4308
4309         ret = tcpm_set_vbus(port, true);
4310         if (ret < 0)
4311                 goto out_disable_vconn;
4312
4313         port->pd_capable = false;
4314
4315         port->partner = NULL;
4316
4317         port->attached = true;
4318         port->send_discover = true;
4319         port->send_discover_prime = false;
4320
4321         return 0;
4322
4323 out_disable_vconn:
4324         tcpm_set_vconn(port, false);
4325 out_disable_pd:
4326         if (port->pd_supported)
4327                 port->tcpc->set_pd_rx(port->tcpc, false);
4328 out_disable_mux:
4329         tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
4330                      TYPEC_ORIENTATION_NONE);
4331         return ret;
4332 }
4333
4334 static void tcpm_typec_disconnect(struct tcpm_port *port)
4335 {
4336         /*
4337          * Unregister plug/cable outside of port->connected because cable can
4338          * be discovered before SRC_READY/SNK_READY states where port->connected
4339          * is set.
4340          */
4341         typec_unregister_plug(port->plug_prime);
4342         typec_unregister_cable(port->cable);
4343         port->plug_prime = NULL;
4344         port->cable = NULL;
4345         if (port->connected) {
4346                 if (port->partner) {
4347                         typec_partner_set_usb_power_delivery(port->partner, NULL);
4348                         typec_unregister_partner(port->partner);
4349                         port->partner = NULL;
4350                 }
4351                 port->connected = false;
4352         }
4353 }
4354
4355 static void tcpm_unregister_altmodes(struct tcpm_port *port)
4356 {
4357         struct pd_mode_data *modep = &port->mode_data;
4358         struct pd_mode_data *modep_prime = &port->mode_data_prime;
4359         int i;
4360
4361         for (i = 0; i < modep->altmodes; i++) {
4362                 typec_unregister_altmode(port->partner_altmode[i]);
4363                 port->partner_altmode[i] = NULL;
4364         }
4365         for (i = 0; i < modep_prime->altmodes; i++) {
4366                 typec_unregister_altmode(port->plug_prime_altmode[i]);
4367                 port->plug_prime_altmode[i] = NULL;
4368         }
4369
4370         memset(modep, 0, sizeof(*modep));
4371         memset(modep_prime, 0, sizeof(*modep_prime));
4372 }
4373
4374 static void tcpm_set_partner_usb_comm_capable(struct tcpm_port *port, bool capable)
4375 {
4376         tcpm_log(port, "Setting usb_comm capable %s", capable ? "true" : "false");
4377
4378         if (port->tcpc->set_partner_usb_comm_capable)
4379                 port->tcpc->set_partner_usb_comm_capable(port->tcpc, capable);
4380 }
4381
4382 static void tcpm_reset_port(struct tcpm_port *port)
4383 {
4384         tcpm_enable_auto_vbus_discharge(port, false);
4385         port->in_ams = false;
4386         port->ams = NONE_AMS;
4387         port->vdm_sm_running = false;
4388         tcpm_unregister_altmodes(port);
4389         tcpm_typec_disconnect(port);
4390         port->attached = false;
4391         port->pd_capable = false;
4392         port->pps_data.supported = false;
4393         tcpm_set_partner_usb_comm_capable(port, false);
4394
4395         /*
4396          * First Rx ID should be 0; set this to a sentinel of -1 so that
4397          * we can check tcpm_pd_rx_handler() if we had seen it before.
4398          */
4399         port->rx_msgid = -1;
4400         port->rx_msgid_prime = -1;
4401
4402         port->tcpc->set_pd_rx(port->tcpc, false);
4403         tcpm_init_vbus(port);   /* also disables charging */
4404         tcpm_init_vconn(port);
4405         tcpm_set_current_limit(port, 0, 0);
4406         tcpm_set_polarity(port, TYPEC_POLARITY_CC1);
4407         tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
4408                      TYPEC_ORIENTATION_NONE);
4409         tcpm_set_attached_state(port, false);
4410         port->try_src_count = 0;
4411         port->try_snk_count = 0;
4412         port->usb_type = POWER_SUPPLY_USB_TYPE_C;
4413         power_supply_changed(port->psy);
4414         port->nr_sink_caps = 0;
4415         port->sink_cap_done = false;
4416         if (port->tcpc->enable_frs)
4417                 port->tcpc->enable_frs(port->tcpc, false);
4418
4419         usb_power_delivery_unregister_capabilities(port->partner_sink_caps);
4420         port->partner_sink_caps = NULL;
4421         usb_power_delivery_unregister_capabilities(port->partner_source_caps);
4422         port->partner_source_caps = NULL;
4423         usb_power_delivery_unregister(port->partner_pd);
4424         port->partner_pd = NULL;
4425 }
4426
4427 static void tcpm_detach(struct tcpm_port *port)
4428 {
4429         if (tcpm_port_is_disconnected(port))
4430                 port->hard_reset_count = 0;
4431
4432         if (!port->attached)
4433                 return;
4434
4435         if (port->tcpc->set_bist_data) {
4436                 tcpm_log(port, "disable BIST MODE TESTDATA");
4437                 port->tcpc->set_bist_data(port->tcpc, false);
4438         }
4439
4440         tcpm_reset_port(port);
4441 }
4442
4443 static void tcpm_src_detach(struct tcpm_port *port)
4444 {
4445         tcpm_detach(port);
4446 }
4447
4448 static int tcpm_snk_attach(struct tcpm_port *port)
4449 {
4450         int ret;
4451
4452         if (port->attached)
4453                 return 0;
4454
4455         ret = tcpm_set_polarity(port, port->cc2 != TYPEC_CC_OPEN ?
4456                                 TYPEC_POLARITY_CC2 : TYPEC_POLARITY_CC1);
4457         if (ret < 0)
4458                 return ret;
4459
4460         tcpm_enable_auto_vbus_discharge(port, true);
4461
4462         ret = tcpm_set_roles(port, true, TYPEC_SINK, tcpm_data_role_for_sink(port));
4463         if (ret < 0)
4464                 return ret;
4465
4466         port->pd_capable = false;
4467
4468         port->partner = NULL;
4469
4470         port->attached = true;
4471         port->send_discover = true;
4472         port->send_discover_prime = false;
4473
4474         return 0;
4475 }
4476
4477 static void tcpm_snk_detach(struct tcpm_port *port)
4478 {
4479         tcpm_detach(port);
4480 }
4481
4482 static int tcpm_acc_attach(struct tcpm_port *port)
4483 {
4484         int ret;
4485
4486         if (port->attached)
4487                 return 0;
4488
4489         ret = tcpm_set_roles(port, true, TYPEC_SOURCE,
4490                              tcpm_data_role_for_source(port));
4491         if (ret < 0)
4492                 return ret;
4493
4494         port->partner = NULL;
4495
4496         tcpm_typec_connect(port);
4497
4498         port->attached = true;
4499
4500         return 0;
4501 }
4502
4503 static void tcpm_acc_detach(struct tcpm_port *port)
4504 {
4505         tcpm_detach(port);
4506 }
4507
4508 static inline enum tcpm_state hard_reset_state(struct tcpm_port *port)
4509 {
4510         if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
4511                 return HARD_RESET_SEND;
4512         if (port->pd_capable)
4513                 return ERROR_RECOVERY;
4514         if (port->pwr_role == TYPEC_SOURCE)
4515                 return SRC_UNATTACHED;
4516         if (port->state == SNK_WAIT_CAPABILITIES)
4517                 return SNK_READY;
4518         return SNK_UNATTACHED;
4519 }
4520
4521 static inline enum tcpm_state unattached_state(struct tcpm_port *port)
4522 {
4523         if (port->port_type == TYPEC_PORT_DRP) {
4524                 if (port->pwr_role == TYPEC_SOURCE)
4525                         return SRC_UNATTACHED;
4526                 else
4527                         return SNK_UNATTACHED;
4528         } else if (port->port_type == TYPEC_PORT_SRC) {
4529                 return SRC_UNATTACHED;
4530         }
4531
4532         return SNK_UNATTACHED;
4533 }
4534
4535 static void tcpm_swap_complete(struct tcpm_port *port, int result)
4536 {
4537         if (port->swap_pending) {
4538                 port->swap_status = result;
4539                 port->swap_pending = false;
4540                 port->non_pd_role_swap = false;
4541                 complete(&port->swap_complete);
4542         }
4543 }
4544
4545 static enum typec_pwr_opmode tcpm_get_pwr_opmode(enum typec_cc_status cc)
4546 {
4547         switch (cc) {
4548         case TYPEC_CC_RP_1_5:
4549                 return TYPEC_PWR_MODE_1_5A;
4550         case TYPEC_CC_RP_3_0:
4551                 return TYPEC_PWR_MODE_3_0A;
4552         case TYPEC_CC_RP_DEF:
4553         default:
4554                 return TYPEC_PWR_MODE_USB;
4555         }
4556 }
4557
4558 static enum typec_cc_status tcpm_pwr_opmode_to_rp(enum typec_pwr_opmode opmode)
4559 {
4560         switch (opmode) {
4561         case TYPEC_PWR_MODE_USB:
4562                 return TYPEC_CC_RP_DEF;
4563         case TYPEC_PWR_MODE_1_5A:
4564                 return TYPEC_CC_RP_1_5;
4565         case TYPEC_PWR_MODE_3_0A:
4566         case TYPEC_PWR_MODE_PD:
4567         default:
4568                 return TYPEC_CC_RP_3_0;
4569         }
4570 }
4571
4572 static void tcpm_set_initial_svdm_version(struct tcpm_port *port)
4573 {
4574         if (!port->partner)
4575                 return;
4576
4577         switch (port->negotiated_rev) {
4578         case PD_REV30:
4579                 break;
4580         /*
4581          * 6.4.4.2.3 Structured VDM Version
4582          * 2.0 states "At this time, there is only one version (1.0) defined.
4583          * This field Shall be set to zero to indicate Version 1.0."
4584          * 3.0 states "This field Shall be set to 01b to indicate Version 2.0."
4585          * To ensure that we follow the Power Delivery revision we are currently
4586          * operating on, downgrade the SVDM version to the highest one supported
4587          * by the Power Delivery revision.
4588          */
4589         case PD_REV20:
4590                 typec_partner_set_svdm_version(port->partner, SVDM_VER_1_0);
4591                 break;
4592         default:
4593                 typec_partner_set_svdm_version(port->partner, SVDM_VER_1_0);
4594                 break;
4595         }
4596 }
4597
4598 static void run_state_machine(struct tcpm_port *port)
4599 {
4600         int ret;
4601         enum typec_pwr_opmode opmode;
4602         unsigned int msecs;
4603         enum tcpm_state upcoming_state;
4604
4605         if (port->tcpc->check_contaminant && port->state != CHECK_CONTAMINANT)
4606                 port->potential_contaminant = ((port->enter_state == SRC_ATTACH_WAIT &&
4607                                                 port->state == SRC_UNATTACHED) ||
4608                                                (port->enter_state == SNK_ATTACH_WAIT &&
4609                                                 port->state == SNK_UNATTACHED) ||
4610                                                (port->enter_state == SNK_DEBOUNCED &&
4611                                                 port->state == SNK_UNATTACHED));
4612
4613         port->enter_state = port->state;
4614         switch (port->state) {
4615         case TOGGLING:
4616                 break;
4617         case CHECK_CONTAMINANT:
4618                 port->tcpc->check_contaminant(port->tcpc);
4619                 break;
4620         /* SRC states */
4621         case SRC_UNATTACHED:
4622                 if (!port->non_pd_role_swap)
4623                         tcpm_swap_complete(port, -ENOTCONN);
4624                 tcpm_src_detach(port);
4625                 if (port->potential_contaminant) {
4626                         tcpm_set_state(port, CHECK_CONTAMINANT, 0);
4627                         break;
4628                 }
4629                 if (tcpm_start_toggling(port, tcpm_rp_cc(port))) {
4630                         tcpm_set_state(port, TOGGLING, 0);
4631                         break;
4632                 }
4633                 tcpm_set_cc(port, tcpm_rp_cc(port));
4634                 if (port->port_type == TYPEC_PORT_DRP)
4635                         tcpm_set_state(port, SNK_UNATTACHED, PD_T_DRP_SNK);
4636                 break;
4637         case SRC_ATTACH_WAIT:
4638                 if (tcpm_port_is_debug(port))
4639                         tcpm_set_state(port, DEBUG_ACC_ATTACHED,
4640                                        PD_T_CC_DEBOUNCE);
4641                 else if (tcpm_port_is_audio(port))
4642                         tcpm_set_state(port, AUDIO_ACC_ATTACHED,
4643                                        PD_T_CC_DEBOUNCE);
4644                 else if (tcpm_port_is_source(port) && port->vbus_vsafe0v)
4645                         tcpm_set_state(port,
4646                                        tcpm_try_snk(port) ? SNK_TRY
4647                                                           : SRC_ATTACHED,
4648                                        PD_T_CC_DEBOUNCE);
4649                 break;
4650
4651         case SNK_TRY:
4652                 port->try_snk_count++;
4653                 /*
4654                  * Requirements:
4655                  * - Do not drive vconn or vbus
4656                  * - Terminate CC pins (both) to Rd
4657                  * Action:
4658                  * - Wait for tDRPTry (PD_T_DRP_TRY).
4659                  *   Until then, ignore any state changes.
4660                  */
4661                 tcpm_set_cc(port, TYPEC_CC_RD);
4662                 tcpm_set_state(port, SNK_TRY_WAIT, PD_T_DRP_TRY);
4663                 break;
4664         case SNK_TRY_WAIT:
4665                 if (tcpm_port_is_sink(port)) {
4666                         tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE, 0);
4667                 } else {
4668                         tcpm_set_state(port, SRC_TRYWAIT, 0);
4669                         port->max_wait = 0;
4670                 }
4671                 break;
4672         case SNK_TRY_WAIT_DEBOUNCE:
4673                 tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS,
4674                                PD_T_TRY_CC_DEBOUNCE);
4675                 break;
4676         case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
4677                 if (port->vbus_present && tcpm_port_is_sink(port))
4678                         tcpm_set_state(port, SNK_ATTACHED, 0);
4679                 else
4680                         port->max_wait = 0;
4681                 break;
4682         case SRC_TRYWAIT:
4683                 tcpm_set_cc(port, tcpm_rp_cc(port));
4684                 if (port->max_wait == 0) {
4685                         port->max_wait = jiffies +
4686                                          msecs_to_jiffies(PD_T_DRP_TRY);
4687                         tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
4688                                        PD_T_DRP_TRY);
4689                 } else {
4690                         if (time_is_after_jiffies(port->max_wait))
4691                                 tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
4692                                                jiffies_to_msecs(port->max_wait -
4693                                                                 jiffies));
4694                         else
4695                                 tcpm_set_state(port, SNK_UNATTACHED, 0);
4696                 }
4697                 break;
4698         case SRC_TRYWAIT_DEBOUNCE:
4699                 tcpm_set_state(port, SRC_ATTACHED, PD_T_CC_DEBOUNCE);
4700                 break;
4701         case SRC_TRYWAIT_UNATTACHED:
4702                 tcpm_set_state(port, SNK_UNATTACHED, 0);
4703                 break;
4704
4705         case SRC_ATTACHED:
4706                 ret = tcpm_src_attach(port);
4707                 tcpm_set_state(port, SRC_UNATTACHED,
4708                                ret < 0 ? 0 : PD_T_PS_SOURCE_ON);
4709                 break;
4710         case SRC_STARTUP:
4711                 opmode =  tcpm_get_pwr_opmode(tcpm_rp_cc(port));
4712                 typec_set_pwr_opmode(port->typec_port, opmode);
4713                 port->pwr_opmode = TYPEC_PWR_MODE_USB;
4714                 port->caps_count = 0;
4715                 port->negotiated_rev = PD_MAX_REV;
4716                 port->negotiated_rev_prime = PD_MAX_REV;
4717                 port->message_id = 0;
4718                 port->message_id_prime = 0;
4719                 port->rx_msgid = -1;
4720                 port->rx_msgid_prime = -1;
4721                 port->explicit_contract = false;
4722                 /* SNK -> SRC POWER/FAST_ROLE_SWAP finished */
4723                 if (port->ams == POWER_ROLE_SWAP ||
4724                     port->ams == FAST_ROLE_SWAP)
4725                         tcpm_ams_finish(port);
4726                 if (!port->pd_supported) {
4727                         tcpm_set_state(port, SRC_READY, 0);
4728                         break;
4729                 }
4730                 port->upcoming_state = SRC_SEND_CAPABILITIES;
4731                 tcpm_ams_start(port, POWER_NEGOTIATION);
4732                 break;
4733         case SRC_SEND_CAPABILITIES:
4734                 port->caps_count++;
4735                 if (port->caps_count > PD_N_CAPS_COUNT) {
4736                         tcpm_set_state(port, SRC_READY, 0);
4737                         break;
4738                 }
4739                 ret = tcpm_pd_send_source_caps(port);
4740                 if (ret < 0) {
4741                         if (tcpm_can_communicate_sop_prime(port) &&
4742                             IS_ERR_OR_NULL(port->cable))
4743                                 tcpm_set_state(port, SRC_VDM_IDENTITY_REQUEST, 0);
4744                         else
4745                                 tcpm_set_state(port, SRC_SEND_CAPABILITIES,
4746                                                PD_T_SEND_SOURCE_CAP);
4747                 } else {
4748                         /*
4749                          * Per standard, we should clear the reset counter here.
4750                          * However, that can result in state machine hang-ups.
4751                          * Reset it only in READY state to improve stability.
4752                          */
4753                         /* port->hard_reset_count = 0; */
4754                         port->caps_count = 0;
4755                         port->pd_capable = true;
4756                         tcpm_set_state_cond(port, SRC_SEND_CAPABILITIES_TIMEOUT,
4757                                             PD_T_SEND_SOURCE_CAP);
4758                 }
4759                 break;
4760         case SRC_SEND_CAPABILITIES_TIMEOUT:
4761                 /*
4762                  * Error recovery for a PD_DATA_SOURCE_CAP reply timeout.
4763                  *
4764                  * PD 2.0 sinks are supposed to accept src-capabilities with a
4765                  * 3.0 header and simply ignore any src PDOs which the sink does
4766                  * not understand such as PPS but some 2.0 sinks instead ignore
4767                  * the entire PD_DATA_SOURCE_CAP message, causing contract
4768                  * negotiation to fail.
4769                  *
4770                  * After PD_N_HARD_RESET_COUNT hard-reset attempts, we try
4771                  * sending src-capabilities with a lower PD revision to
4772                  * make these broken sinks work.
4773                  */
4774                 if (port->hard_reset_count < PD_N_HARD_RESET_COUNT) {
4775                         tcpm_set_state(port, HARD_RESET_SEND, 0);
4776                 } else if (port->negotiated_rev > PD_REV20) {
4777                         port->negotiated_rev--;
4778                         port->hard_reset_count = 0;
4779                         tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
4780                 } else {
4781                         tcpm_set_state(port, hard_reset_state(port), 0);
4782                 }
4783                 break;
4784         case SRC_NEGOTIATE_CAPABILITIES:
4785                 ret = tcpm_pd_check_request(port);
4786                 if (ret < 0) {
4787                         tcpm_pd_send_control(port, PD_CTRL_REJECT, TCPC_TX_SOP);
4788                         if (!port->explicit_contract) {
4789                                 tcpm_set_state(port,
4790                                                SRC_WAIT_NEW_CAPABILITIES, 0);
4791                         } else {
4792                                 tcpm_set_state(port, SRC_READY, 0);
4793                         }
4794                 } else {
4795                         tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
4796                         tcpm_set_partner_usb_comm_capable(port,
4797                                                           !!(port->sink_request & RDO_USB_COMM));
4798                         tcpm_set_state(port, SRC_TRANSITION_SUPPLY,
4799                                        PD_T_SRC_TRANSITION);
4800                 }
4801                 break;
4802         case SRC_TRANSITION_SUPPLY:
4803                 /* XXX: regulator_set_voltage(vbus, ...) */
4804                 tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP);
4805                 port->explicit_contract = true;
4806                 typec_set_pwr_opmode(port->typec_port, TYPEC_PWR_MODE_PD);
4807                 port->pwr_opmode = TYPEC_PWR_MODE_PD;
4808                 tcpm_set_state_cond(port, SRC_READY, 0);
4809                 break;
4810         case SRC_READY:
4811 #if 1
4812                 port->hard_reset_count = 0;
4813 #endif
4814                 port->try_src_count = 0;
4815
4816                 tcpm_swap_complete(port, 0);
4817                 tcpm_typec_connect(port);
4818
4819                 if (port->ams != NONE_AMS)
4820                         tcpm_ams_finish(port);
4821                 if (port->next_ams != NONE_AMS) {
4822                         port->ams = port->next_ams;
4823                         port->next_ams = NONE_AMS;
4824                 }
4825
4826                 /*
4827                  * If previous AMS is interrupted, switch to the upcoming
4828                  * state.
4829                  */
4830                 if (port->upcoming_state != INVALID_STATE) {
4831                         upcoming_state = port->upcoming_state;
4832                         port->upcoming_state = INVALID_STATE;
4833                         tcpm_set_state(port, upcoming_state, 0);
4834                         break;
4835                 }
4836
4837                 /*
4838                  * 6.4.4.3.1 Discover Identity
4839                  * "The Discover Identity Command Shall only be sent to SOP when there is an
4840                  * Explicit Contract."
4841                  *
4842                  * Discover Identity on SOP' should be discovered prior to the
4843                  * ready state, but if done after a Vconn Swap following Discover
4844                  * Identity on SOP then the discovery process can be run here
4845                  * as well.
4846                  */
4847                 if (port->explicit_contract) {
4848                         if (port->send_discover_prime) {
4849                                 port->tx_sop_type = TCPC_TX_SOP_PRIME;
4850                         } else {
4851                                 port->tx_sop_type = TCPC_TX_SOP;
4852                                 tcpm_set_initial_svdm_version(port);
4853                         }
4854                         mod_send_discover_delayed_work(port, 0);
4855                 } else {
4856                         port->send_discover = false;
4857                         port->send_discover_prime = false;
4858                 }
4859
4860                 /*
4861                  * 6.3.5
4862                  * Sending ping messages is not necessary if
4863                  * - the source operates at vSafe5V
4864                  * or
4865                  * - The system is not operating in PD mode
4866                  * or
4867                  * - Both partners are connected using a Type-C connector
4868                  *
4869                  * There is no actual need to send PD messages since the local
4870                  * port type-c and the spec does not clearly say whether PD is
4871                  * possible when type-c is connected to Type-A/B
4872                  */
4873                 break;
4874         case SRC_WAIT_NEW_CAPABILITIES:
4875                 /* Nothing to do... */
4876                 break;
4877
4878         /* SNK states */
4879         case SNK_UNATTACHED:
4880                 if (!port->non_pd_role_swap)
4881                         tcpm_swap_complete(port, -ENOTCONN);
4882                 tcpm_pps_complete(port, -ENOTCONN);
4883                 tcpm_snk_detach(port);
4884                 if (port->potential_contaminant) {
4885                         tcpm_set_state(port, CHECK_CONTAMINANT, 0);
4886                         break;
4887                 }
4888                 if (tcpm_start_toggling(port, TYPEC_CC_RD)) {
4889                         tcpm_set_state(port, TOGGLING, 0);
4890                         break;
4891                 }
4892                 tcpm_set_cc(port, TYPEC_CC_RD);
4893                 if (port->port_type == TYPEC_PORT_DRP)
4894                         tcpm_set_state(port, SRC_UNATTACHED, PD_T_DRP_SRC);
4895                 break;
4896         case SNK_ATTACH_WAIT:
4897                 if ((port->cc1 == TYPEC_CC_OPEN &&
4898                      port->cc2 != TYPEC_CC_OPEN) ||
4899                     (port->cc1 != TYPEC_CC_OPEN &&
4900                      port->cc2 == TYPEC_CC_OPEN))
4901                         tcpm_set_state(port, SNK_DEBOUNCED,
4902                                        PD_T_CC_DEBOUNCE);
4903                 else if (tcpm_port_is_disconnected(port))
4904                         tcpm_set_state(port, SNK_UNATTACHED,
4905                                        PD_T_PD_DEBOUNCE);
4906                 break;
4907         case SNK_DEBOUNCED:
4908                 if (tcpm_port_is_disconnected(port))
4909                         tcpm_set_state(port, SNK_UNATTACHED,
4910                                        PD_T_PD_DEBOUNCE);
4911                 else if (port->vbus_present)
4912                         tcpm_set_state(port,
4913                                        tcpm_try_src(port) ? SRC_TRY
4914                                                           : SNK_ATTACHED,
4915                                        0);
4916                 break;
4917         case SRC_TRY:
4918                 port->try_src_count++;
4919                 tcpm_set_cc(port, tcpm_rp_cc(port));
4920                 port->max_wait = 0;
4921                 tcpm_set_state(port, SRC_TRY_WAIT, 0);
4922                 break;
4923         case SRC_TRY_WAIT:
4924                 if (port->max_wait == 0) {
4925                         port->max_wait = jiffies +
4926                                          msecs_to_jiffies(PD_T_DRP_TRY);
4927                         msecs = PD_T_DRP_TRY;
4928                 } else {
4929                         if (time_is_after_jiffies(port->max_wait))
4930                                 msecs = jiffies_to_msecs(port->max_wait -
4931                                                          jiffies);
4932                         else
4933                                 msecs = 0;
4934                 }
4935                 tcpm_set_state(port, SNK_TRYWAIT, msecs);
4936                 break;
4937         case SRC_TRY_DEBOUNCE:
4938                 tcpm_set_state(port, SRC_ATTACHED, PD_T_PD_DEBOUNCE);
4939                 break;
4940         case SNK_TRYWAIT:
4941                 tcpm_set_cc(port, TYPEC_CC_RD);
4942                 tcpm_set_state(port, SNK_TRYWAIT_VBUS, PD_T_CC_DEBOUNCE);
4943                 break;
4944         case SNK_TRYWAIT_VBUS:
4945                 /*
4946                  * TCPM stays in this state indefinitely until VBUS
4947                  * is detected as long as Rp is not detected for
4948                  * more than a time period of tPDDebounce.
4949                  */
4950                 if (port->vbus_present && tcpm_port_is_sink(port)) {
4951                         tcpm_set_state(port, SNK_ATTACHED, 0);
4952                         break;
4953                 }
4954                 if (!tcpm_port_is_sink(port))
4955                         tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
4956                 break;
4957         case SNK_TRYWAIT_DEBOUNCE:
4958                 tcpm_set_state(port, SNK_UNATTACHED, PD_T_PD_DEBOUNCE);
4959                 break;
4960         case SNK_ATTACHED:
4961                 ret = tcpm_snk_attach(port);
4962                 if (ret < 0)
4963                         tcpm_set_state(port, SNK_UNATTACHED, 0);
4964                 else
4965                         tcpm_set_state(port, SNK_STARTUP, 0);
4966                 break;
4967         case SNK_STARTUP:
4968                 opmode =  tcpm_get_pwr_opmode(port->polarity ?
4969                                               port->cc2 : port->cc1);
4970                 typec_set_pwr_opmode(port->typec_port, opmode);
4971                 port->pwr_opmode = TYPEC_PWR_MODE_USB;
4972                 port->negotiated_rev = PD_MAX_REV;
4973                 port->negotiated_rev_prime = PD_MAX_REV;
4974                 port->message_id = 0;
4975                 port->message_id_prime = 0;
4976                 port->rx_msgid = -1;
4977                 port->rx_msgid_prime = -1;
4978                 port->explicit_contract = false;
4979
4980                 if (port->ams == POWER_ROLE_SWAP ||
4981                     port->ams == FAST_ROLE_SWAP)
4982                         /* SRC -> SNK POWER/FAST_ROLE_SWAP finished */
4983                         tcpm_ams_finish(port);
4984
4985                 tcpm_set_state(port, SNK_DISCOVERY, 0);
4986                 break;
4987         case SNK_DISCOVERY:
4988                 if (port->vbus_present) {
4989                         u32 current_lim = tcpm_get_current_limit(port);
4990
4991                         if (port->slow_charger_loop && (current_lim > PD_P_SNK_STDBY_MW / 5))
4992                                 current_lim = PD_P_SNK_STDBY_MW / 5;
4993                         tcpm_set_current_limit(port, current_lim, 5000);
4994                         /* Not sink vbus if operational current is 0mA */
4995                         tcpm_set_charge(port, !port->pd_supported ||
4996                                         pdo_max_current(port->snk_pdo[0]));
4997
4998                         if (!port->pd_supported)
4999                                 tcpm_set_state(port, SNK_READY, 0);
5000                         else
5001                                 tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
5002                         break;
5003                 }
5004                 /*
5005                  * For DRP, timeouts differ. Also, handling is supposed to be
5006                  * different and much more complex (dead battery detection;
5007                  * see USB power delivery specification, section 8.3.3.6.1.5.1).
5008                  */
5009                 tcpm_set_state(port, hard_reset_state(port),
5010                                port->port_type == TYPEC_PORT_DRP ?
5011                                         PD_T_DB_DETECT : PD_T_NO_RESPONSE);
5012                 break;
5013         case SNK_DISCOVERY_DEBOUNCE:
5014                 tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE_DONE,
5015                                PD_T_CC_DEBOUNCE);
5016                 break;
5017         case SNK_DISCOVERY_DEBOUNCE_DONE:
5018                 if (!tcpm_port_is_disconnected(port) &&
5019                     tcpm_port_is_sink(port) &&
5020                     ktime_after(port->delayed_runtime, ktime_get())) {
5021                         tcpm_set_state(port, SNK_DISCOVERY,
5022                                        ktime_to_ms(ktime_sub(port->delayed_runtime, ktime_get())));
5023                         break;
5024                 }
5025                 tcpm_set_state(port, unattached_state(port), 0);
5026                 break;
5027         case SNK_WAIT_CAPABILITIES:
5028                 ret = port->tcpc->set_pd_rx(port->tcpc, true);
5029                 if (ret < 0) {
5030                         tcpm_set_state(port, SNK_READY, 0);
5031                         break;
5032                 }
5033                 /*
5034                  * If VBUS has never been low, and we time out waiting
5035                  * for source cap, try a soft reset first, in case we
5036                  * were already in a stable contract before this boot.
5037                  * Do this only once.
5038                  */
5039                 if (port->vbus_never_low) {
5040                         port->vbus_never_low = false;
5041                         tcpm_set_state(port, SNK_SOFT_RESET,
5042                                        PD_T_SINK_WAIT_CAP);
5043                 } else {
5044                         tcpm_set_state(port, hard_reset_state(port),
5045                                        PD_T_SINK_WAIT_CAP);
5046                 }
5047                 break;
5048         case SNK_NEGOTIATE_CAPABILITIES:
5049                 port->pd_capable = true;
5050                 tcpm_set_partner_usb_comm_capable(port,
5051                                                   !!(port->source_caps[0] & PDO_FIXED_USB_COMM));
5052                 port->hard_reset_count = 0;
5053                 ret = tcpm_pd_send_request(port);
5054                 if (ret < 0) {
5055                         /* Restore back to the original state */
5056                         tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
5057                                                                port->pps_data.active,
5058                                                                port->supply_voltage);
5059                         /* Let the Source send capabilities again. */
5060                         tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
5061                 } else {
5062                         tcpm_set_state_cond(port, hard_reset_state(port),
5063                                             PD_T_SENDER_RESPONSE);
5064                 }
5065                 break;
5066         case SNK_NEGOTIATE_PPS_CAPABILITIES:
5067                 ret = tcpm_pd_send_pps_request(port);
5068                 if (ret < 0) {
5069                         /* Restore back to the original state */
5070                         tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
5071                                                                port->pps_data.active,
5072                                                                port->supply_voltage);
5073                         port->pps_status = ret;
5074                         /*
5075                          * If this was called due to updates to sink
5076                          * capabilities, and pps is no longer valid, we should
5077                          * safely fall back to a standard PDO.
5078                          */
5079                         if (port->update_sink_caps)
5080                                 tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
5081                         else
5082                                 tcpm_set_state(port, SNK_READY, 0);
5083                 } else {
5084                         tcpm_set_state_cond(port, hard_reset_state(port),
5085                                             PD_T_SENDER_RESPONSE);
5086                 }
5087                 break;
5088         case SNK_TRANSITION_SINK:
5089                 /* From the USB PD spec:
5090                  * "The Sink Shall transition to Sink Standby before a positive or
5091                  * negative voltage transition of VBUS. During Sink Standby
5092                  * the Sink Shall reduce its power draw to pSnkStdby."
5093                  *
5094                  * This is not applicable to PPS though as the port can continue
5095                  * to draw negotiated power without switching to standby.
5096                  */
5097                 if (port->supply_voltage != port->req_supply_voltage && !port->pps_data.active &&
5098                     port->current_limit * port->supply_voltage / 1000 > PD_P_SNK_STDBY_MW) {
5099                         u32 stdby_ma = PD_P_SNK_STDBY_MW * 1000 / port->supply_voltage;
5100
5101                         tcpm_log(port, "Setting standby current %u mV @ %u mA",
5102                                  port->supply_voltage, stdby_ma);
5103                         tcpm_set_current_limit(port, stdby_ma, port->supply_voltage);
5104                 }
5105                 fallthrough;
5106         case SNK_TRANSITION_SINK_VBUS:
5107                 tcpm_set_state(port, hard_reset_state(port),
5108                                PD_T_PS_TRANSITION);
5109                 break;
5110         case SNK_READY:
5111                 port->try_snk_count = 0;
5112                 port->update_sink_caps = false;
5113                 if (port->explicit_contract) {
5114                         typec_set_pwr_opmode(port->typec_port,
5115                                              TYPEC_PWR_MODE_PD);
5116                         port->pwr_opmode = TYPEC_PWR_MODE_PD;
5117                 }
5118
5119                 if (!port->pd_capable && port->slow_charger_loop)
5120                         tcpm_set_current_limit(port, tcpm_get_current_limit(port), 5000);
5121                 tcpm_swap_complete(port, 0);
5122                 tcpm_typec_connect(port);
5123                 if (port->pd_capable && port->source_caps[0] & PDO_FIXED_DUAL_ROLE)
5124                         mod_enable_frs_delayed_work(port, 0);
5125                 tcpm_pps_complete(port, port->pps_status);
5126
5127                 if (port->ams != NONE_AMS)
5128                         tcpm_ams_finish(port);
5129                 if (port->next_ams != NONE_AMS) {
5130                         port->ams = port->next_ams;
5131                         port->next_ams = NONE_AMS;
5132                 }
5133
5134                 /*
5135                  * If previous AMS is interrupted, switch to the upcoming
5136                  * state.
5137                  */
5138                 if (port->upcoming_state != INVALID_STATE) {
5139                         upcoming_state = port->upcoming_state;
5140                         port->upcoming_state = INVALID_STATE;
5141                         tcpm_set_state(port, upcoming_state, 0);
5142                         break;
5143                 }
5144
5145                 /*
5146                  * 6.4.4.3.1 Discover Identity
5147                  * "The Discover Identity Command Shall only be sent to SOP when there is an
5148                  * Explicit Contract."
5149                  *
5150                  * Discover Identity on SOP' should be discovered prior to the
5151                  * ready state, but if done after a Vconn Swap following Discover
5152                  * Identity on SOP then the discovery process can be run here
5153                  * as well.
5154                  */
5155                 if (port->explicit_contract) {
5156                         if (port->send_discover_prime) {
5157                                 port->tx_sop_type = TCPC_TX_SOP_PRIME;
5158                         } else {
5159                                 port->tx_sop_type = TCPC_TX_SOP;
5160                                 tcpm_set_initial_svdm_version(port);
5161                         }
5162                         mod_send_discover_delayed_work(port, 0);
5163                 } else {
5164                         port->send_discover = false;
5165                         port->send_discover_prime = false;
5166                 }
5167
5168                 power_supply_changed(port->psy);
5169                 break;
5170
5171         /* Accessory states */
5172         case ACC_UNATTACHED:
5173                 tcpm_acc_detach(port);
5174                 tcpm_set_state(port, SRC_UNATTACHED, 0);
5175                 break;
5176         case DEBUG_ACC_ATTACHED:
5177         case AUDIO_ACC_ATTACHED:
5178                 ret = tcpm_acc_attach(port);
5179                 if (ret < 0)
5180                         tcpm_set_state(port, ACC_UNATTACHED, 0);
5181                 break;
5182         case AUDIO_ACC_DEBOUNCE:
5183                 tcpm_set_state(port, ACC_UNATTACHED, PD_T_CC_DEBOUNCE);
5184                 break;
5185
5186         /* Hard_Reset states */
5187         case HARD_RESET_SEND:
5188                 if (port->ams != NONE_AMS)
5189                         tcpm_ams_finish(port);
5190                 /*
5191                  * State machine will be directed to HARD_RESET_START,
5192                  * thus set upcoming_state to INVALID_STATE.
5193                  */
5194                 port->upcoming_state = INVALID_STATE;
5195                 tcpm_ams_start(port, HARD_RESET);
5196                 break;
5197         case HARD_RESET_START:
5198                 port->sink_cap_done = false;
5199                 if (port->tcpc->enable_frs)
5200                         port->tcpc->enable_frs(port->tcpc, false);
5201                 port->hard_reset_count++;
5202                 port->tcpc->set_pd_rx(port->tcpc, false);
5203                 tcpm_unregister_altmodes(port);
5204                 port->nr_sink_caps = 0;
5205                 port->send_discover = true;
5206                 port->send_discover_prime = false;
5207                 if (port->pwr_role == TYPEC_SOURCE)
5208                         tcpm_set_state(port, SRC_HARD_RESET_VBUS_OFF,
5209                                        PD_T_PS_HARD_RESET);
5210                 else
5211                         tcpm_set_state(port, SNK_HARD_RESET_SINK_OFF, 0);
5212                 break;
5213         case SRC_HARD_RESET_VBUS_OFF:
5214                 /*
5215                  * 7.1.5 Response to Hard Resets
5216                  * Hard Reset Signaling indicates a communication failure has occurred and the
5217                  * Source Shall stop driving VCONN, Shall remove Rp from the VCONN pin and Shall
5218                  * drive VBUS to vSafe0V as shown in Figure 7-9.
5219                  */
5220                 tcpm_set_vconn(port, false);
5221                 tcpm_set_vbus(port, false);
5222                 tcpm_set_roles(port, port->self_powered, TYPEC_SOURCE,
5223                                tcpm_data_role_for_source(port));
5224                 /*
5225                  * If tcpc fails to notify vbus off, TCPM will wait for PD_T_SAFE_0V +
5226                  * PD_T_SRC_RECOVER before turning vbus back on.
5227                  * From Table 7-12 Sequence Description for a Source Initiated Hard Reset:
5228                  * 4. Policy Engine waits tPSHardReset after sending Hard Reset Signaling and then
5229                  * tells the Device Policy Manager to instruct the power supply to perform a
5230                  * Hard Reset. The transition to vSafe0V Shall occur within tSafe0V (t2).
5231                  * 5. After tSrcRecover the Source applies power to VBUS in an attempt to
5232                  * re-establish communication with the Sink and resume USB Default Operation.
5233                  * The transition to vSafe5V Shall occur within tSrcTurnOn(t4).
5234                  */
5235                 tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SAFE_0V + PD_T_SRC_RECOVER);
5236                 break;
5237         case SRC_HARD_RESET_VBUS_ON:
5238                 tcpm_set_vconn(port, true);
5239                 tcpm_set_vbus(port, true);
5240                 if (port->ams == HARD_RESET)
5241                         tcpm_ams_finish(port);
5242                 if (port->pd_supported)
5243                         port->tcpc->set_pd_rx(port->tcpc, true);
5244                 tcpm_set_attached_state(port, true);
5245                 tcpm_set_state(port, SRC_UNATTACHED, PD_T_PS_SOURCE_ON);
5246                 break;
5247         case SNK_HARD_RESET_SINK_OFF:
5248                 /* Do not discharge/disconnect during hard reseet */
5249                 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
5250                 memset(&port->pps_data, 0, sizeof(port->pps_data));
5251                 tcpm_set_vconn(port, false);
5252                 if (port->pd_capable)
5253                         tcpm_set_charge(port, false);
5254                 tcpm_set_roles(port, port->self_powered, TYPEC_SINK,
5255                                tcpm_data_role_for_sink(port));
5256                 /*
5257                  * VBUS may or may not toggle, depending on the adapter.
5258                  * If it doesn't toggle, transition to SNK_HARD_RESET_SINK_ON
5259                  * directly after timeout.
5260                  */
5261                 tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, PD_T_SAFE_0V);
5262                 break;
5263         case SNK_HARD_RESET_WAIT_VBUS:
5264                 if (port->ams == HARD_RESET)
5265                         tcpm_ams_finish(port);
5266                 /* Assume we're disconnected if VBUS doesn't come back. */
5267                 tcpm_set_state(port, SNK_UNATTACHED,
5268                                PD_T_SRC_RECOVER_MAX + PD_T_SRC_TURN_ON);
5269                 break;
5270         case SNK_HARD_RESET_SINK_ON:
5271                 /* Note: There is no guarantee that VBUS is on in this state */
5272                 /*
5273                  * XXX:
5274                  * The specification suggests that dual mode ports in sink
5275                  * mode should transition to state PE_SRC_Transition_to_default.
5276                  * See USB power delivery specification chapter 8.3.3.6.1.3.
5277                  * This would mean to
5278                  * - turn off VCONN, reset power supply
5279                  * - request hardware reset
5280                  * - turn on VCONN
5281                  * - Transition to state PE_Src_Startup
5282                  * SNK only ports shall transition to state Snk_Startup
5283                  * (see chapter 8.3.3.3.8).
5284                  * Similar, dual-mode ports in source mode should transition
5285                  * to PE_SNK_Transition_to_default.
5286                  */
5287                 if (port->pd_capable) {
5288                         tcpm_set_current_limit(port,
5289                                                tcpm_get_current_limit(port),
5290                                                5000);
5291                         /* Not sink vbus if operational current is 0mA */
5292                         tcpm_set_charge(port, !!pdo_max_current(port->snk_pdo[0]));
5293                 }
5294                 if (port->ams == HARD_RESET)
5295                         tcpm_ams_finish(port);
5296                 tcpm_set_attached_state(port, true);
5297                 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, VSAFE5V);
5298                 tcpm_set_state(port, SNK_STARTUP, 0);
5299                 break;
5300
5301         /* Soft_Reset states */
5302         case SOFT_RESET:
5303                 port->message_id = 0;
5304                 port->rx_msgid = -1;
5305                 /* remove existing capabilities */
5306                 usb_power_delivery_unregister_capabilities(port->partner_source_caps);
5307                 port->partner_source_caps = NULL;
5308                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5309                 tcpm_ams_finish(port);
5310                 if (port->pwr_role == TYPEC_SOURCE) {
5311                         port->upcoming_state = SRC_SEND_CAPABILITIES;
5312                         tcpm_ams_start(port, POWER_NEGOTIATION);
5313                 } else {
5314                         tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
5315                 }
5316                 break;
5317         case SRC_SOFT_RESET_WAIT_SNK_TX:
5318         case SNK_SOFT_RESET:
5319                 if (port->ams != NONE_AMS)
5320                         tcpm_ams_finish(port);
5321                 port->upcoming_state = SOFT_RESET_SEND;
5322                 tcpm_ams_start(port, SOFT_RESET_AMS);
5323                 break;
5324         case SOFT_RESET_SEND:
5325                 /*
5326                  * Power Delivery 3.0 Section 6.3.13
5327                  *
5328                  * A Soft_Reset Message Shall be targeted at a specific entity
5329                  * depending on the type of SOP* packet used.
5330                  */
5331                 if (port->tx_sop_type == TCPC_TX_SOP_PRIME) {
5332                         port->message_id_prime = 0;
5333                         port->rx_msgid_prime = -1;
5334                         tcpm_pd_send_control(port, PD_CTRL_SOFT_RESET, TCPC_TX_SOP_PRIME);
5335                         tcpm_set_state_cond(port, ready_state(port), PD_T_SENDER_RESPONSE);
5336                 } else {
5337                         port->message_id = 0;
5338                         port->rx_msgid = -1;
5339                         /* remove existing capabilities */
5340                         usb_power_delivery_unregister_capabilities(port->partner_source_caps);
5341                         port->partner_source_caps = NULL;
5342                         if (tcpm_pd_send_control(port, PD_CTRL_SOFT_RESET, TCPC_TX_SOP))
5343                                 tcpm_set_state_cond(port, hard_reset_state(port), 0);
5344                         else
5345                                 tcpm_set_state_cond(port, hard_reset_state(port),
5346                                                     PD_T_SENDER_RESPONSE);
5347                 }
5348                 break;
5349
5350         /* DR_Swap states */
5351         case DR_SWAP_SEND:
5352                 tcpm_pd_send_control(port, PD_CTRL_DR_SWAP, TCPC_TX_SOP);
5353                 if (port->data_role == TYPEC_DEVICE || port->negotiated_rev > PD_REV20) {
5354                         port->send_discover = true;
5355                         port->send_discover_prime = false;
5356                 }
5357                 tcpm_set_state_cond(port, DR_SWAP_SEND_TIMEOUT,
5358                                     PD_T_SENDER_RESPONSE);
5359                 break;
5360         case DR_SWAP_ACCEPT:
5361                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5362                 if (port->data_role == TYPEC_DEVICE || port->negotiated_rev > PD_REV20) {
5363                         port->send_discover = true;
5364                         port->send_discover_prime = false;
5365                 }
5366                 tcpm_set_state_cond(port, DR_SWAP_CHANGE_DR, 0);
5367                 break;
5368         case DR_SWAP_SEND_TIMEOUT:
5369                 tcpm_swap_complete(port, -ETIMEDOUT);
5370                 port->send_discover = false;
5371                 port->send_discover_prime = false;
5372                 tcpm_ams_finish(port);
5373                 tcpm_set_state(port, ready_state(port), 0);
5374                 break;
5375         case DR_SWAP_CHANGE_DR:
5376                 tcpm_unregister_altmodes(port);
5377                 if (port->data_role == TYPEC_HOST)
5378                         tcpm_set_roles(port, true, port->pwr_role,
5379                                        TYPEC_DEVICE);
5380                 else
5381                         tcpm_set_roles(port, true, port->pwr_role,
5382                                        TYPEC_HOST);
5383                 tcpm_ams_finish(port);
5384                 tcpm_set_state(port, ready_state(port), 0);
5385                 break;
5386
5387         case FR_SWAP_SEND:
5388                 if (tcpm_pd_send_control(port, PD_CTRL_FR_SWAP, TCPC_TX_SOP)) {
5389                         tcpm_set_state(port, ERROR_RECOVERY, 0);
5390                         break;
5391                 }
5392                 tcpm_set_state_cond(port, FR_SWAP_SEND_TIMEOUT, PD_T_SENDER_RESPONSE);
5393                 break;
5394         case FR_SWAP_SEND_TIMEOUT:
5395                 tcpm_set_state(port, ERROR_RECOVERY, 0);
5396                 break;
5397         case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5398                 tcpm_set_state(port, ERROR_RECOVERY, PD_T_PS_SOURCE_OFF);
5399                 break;
5400         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5401                 if (port->vbus_source)
5402                         tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
5403                 else
5404                         tcpm_set_state(port, ERROR_RECOVERY, PD_T_RECEIVER_RESPONSE);
5405                 break;
5406         case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5407                 tcpm_set_pwr_role(port, TYPEC_SOURCE);
5408                 if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP)) {
5409                         tcpm_set_state(port, ERROR_RECOVERY, 0);
5410                         break;
5411                 }
5412                 tcpm_set_cc(port, tcpm_rp_cc(port));
5413                 tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
5414                 break;
5415
5416         /* PR_Swap states */
5417         case PR_SWAP_ACCEPT:
5418                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5419                 tcpm_set_state(port, PR_SWAP_START, 0);
5420                 break;
5421         case PR_SWAP_SEND:
5422                 tcpm_pd_send_control(port, PD_CTRL_PR_SWAP, TCPC_TX_SOP);
5423                 tcpm_set_state_cond(port, PR_SWAP_SEND_TIMEOUT,
5424                                     PD_T_SENDER_RESPONSE);
5425                 break;
5426         case PR_SWAP_SEND_TIMEOUT:
5427                 tcpm_swap_complete(port, -ETIMEDOUT);
5428                 tcpm_set_state(port, ready_state(port), 0);
5429                 break;
5430         case PR_SWAP_START:
5431                 tcpm_apply_rc(port);
5432                 if (port->pwr_role == TYPEC_SOURCE)
5433                         tcpm_set_state(port, PR_SWAP_SRC_SNK_TRANSITION_OFF,
5434                                        PD_T_SRC_TRANSITION);
5435                 else
5436                         tcpm_set_state(port, PR_SWAP_SNK_SRC_SINK_OFF, 0);
5437                 break;
5438         case PR_SWAP_SRC_SNK_TRANSITION_OFF:
5439                 /*
5440                  * Prevent vbus discharge circuit from turning on during PR_SWAP
5441                  * as this is not a disconnect.
5442                  */
5443                 tcpm_set_vbus(port, false);
5444                 port->explicit_contract = false;
5445                 /* allow time for Vbus discharge, must be < tSrcSwapStdby */
5446                 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF,
5447                                PD_T_SRCSWAPSTDBY);
5448                 break;
5449         case PR_SWAP_SRC_SNK_SOURCE_OFF:
5450                 tcpm_set_cc(port, TYPEC_CC_RD);
5451                 /* allow CC debounce */
5452                 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED,
5453                                PD_T_CC_DEBOUNCE);
5454                 break;
5455         case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
5456                 /*
5457                  * USB-PD standard, 6.2.1.4, Port Power Role:
5458                  * "During the Power Role Swap Sequence, for the initial Source
5459                  * Port, the Port Power Role field shall be set to Sink in the
5460                  * PS_RDY Message indicating that the initial Source’s power
5461                  * supply is turned off"
5462                  */
5463                 tcpm_set_pwr_role(port, TYPEC_SINK);
5464                 if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP)) {
5465                         tcpm_set_state(port, ERROR_RECOVERY, 0);
5466                         break;
5467                 }
5468                 tcpm_set_state(port, ERROR_RECOVERY, PD_T_PS_SOURCE_ON_PRS);
5469                 break;
5470         case PR_SWAP_SRC_SNK_SINK_ON:
5471                 tcpm_enable_auto_vbus_discharge(port, true);
5472                 /* Set the vbus disconnect threshold for implicit contract */
5473                 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, VSAFE5V);
5474                 tcpm_set_state(port, SNK_STARTUP, 0);
5475                 break;
5476         case PR_SWAP_SNK_SRC_SINK_OFF:
5477                 /* will be source, remove existing capabilities */
5478                 usb_power_delivery_unregister_capabilities(port->partner_source_caps);
5479                 port->partner_source_caps = NULL;
5480                 /*
5481                  * Prevent vbus discharge circuit from turning on during PR_SWAP
5482                  * as this is not a disconnect.
5483                  */
5484                 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB,
5485                                                        port->pps_data.active, 0);
5486                 tcpm_set_charge(port, false);
5487                 tcpm_set_state(port, hard_reset_state(port),
5488                                PD_T_PS_SOURCE_OFF);
5489                 break;
5490         case PR_SWAP_SNK_SRC_SOURCE_ON:
5491                 tcpm_enable_auto_vbus_discharge(port, true);
5492                 tcpm_set_cc(port, tcpm_rp_cc(port));
5493                 tcpm_set_vbus(port, true);
5494                 /*
5495                  * allow time VBUS ramp-up, must be < tNewSrc
5496                  * Also, this window overlaps with CC debounce as well.
5497                  * So, Wait for the max of two which is PD_T_NEWSRC
5498                  */
5499                 tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP,
5500                                PD_T_NEWSRC);
5501                 break;
5502         case PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP:
5503                 /*
5504                  * USB PD standard, 6.2.1.4:
5505                  * "Subsequent Messages initiated by the Policy Engine,
5506                  * such as the PS_RDY Message sent to indicate that Vbus
5507                  * is ready, will have the Port Power Role field set to
5508                  * Source."
5509                  */
5510                 tcpm_set_pwr_role(port, TYPEC_SOURCE);
5511                 tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP);
5512                 tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
5513                 break;
5514
5515         case VCONN_SWAP_ACCEPT:
5516                 tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5517                 tcpm_ams_finish(port);
5518                 tcpm_set_state(port, VCONN_SWAP_START, 0);
5519                 break;
5520         case VCONN_SWAP_SEND:
5521                 tcpm_pd_send_control(port, PD_CTRL_VCONN_SWAP, TCPC_TX_SOP);
5522                 tcpm_set_state(port, VCONN_SWAP_SEND_TIMEOUT,
5523                                PD_T_SENDER_RESPONSE);
5524                 break;
5525         case VCONN_SWAP_SEND_TIMEOUT:
5526                 tcpm_swap_complete(port, -ETIMEDOUT);
5527                 tcpm_set_state(port, ready_state(port), 0);
5528                 break;
5529         case VCONN_SWAP_START:
5530                 if (port->vconn_role == TYPEC_SOURCE)
5531                         tcpm_set_state(port, VCONN_SWAP_WAIT_FOR_VCONN, 0);
5532                 else
5533                         tcpm_set_state(port, VCONN_SWAP_TURN_ON_VCONN, 0);
5534                 break;
5535         case VCONN_SWAP_WAIT_FOR_VCONN:
5536                 tcpm_set_state(port, hard_reset_state(port),
5537                                PD_T_VCONN_SOURCE_ON);
5538                 break;
5539         case VCONN_SWAP_TURN_ON_VCONN:
5540                 ret = tcpm_set_vconn(port, true);
5541                 tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP);
5542                 /*
5543                  * USB PD 3.0 Section 6.4.4.3.1
5544                  *
5545                  * Note that a Cable Plug or VPD will not be ready for PD
5546                  * Communication until tVCONNStable after VCONN has been applied
5547                  */
5548                 if (!ret)
5549                         tcpm_set_state(port, VCONN_SWAP_SEND_SOFT_RESET,
5550                                        PD_T_VCONN_STABLE);
5551                 else
5552                         tcpm_set_state(port, ready_state(port), 0);
5553                 break;
5554         case VCONN_SWAP_TURN_OFF_VCONN:
5555                 tcpm_set_vconn(port, false);
5556                 tcpm_set_state(port, ready_state(port), 0);
5557                 break;
5558         case VCONN_SWAP_SEND_SOFT_RESET:
5559                 tcpm_swap_complete(port, port->swap_status);
5560                 if (tcpm_can_communicate_sop_prime(port)) {
5561                         port->tx_sop_type = TCPC_TX_SOP_PRIME;
5562                         port->upcoming_state = SOFT_RESET_SEND;
5563                         tcpm_ams_start(port, SOFT_RESET_AMS);
5564                 } else {
5565                         tcpm_set_state(port, ready_state(port), 0);
5566                 }
5567                 break;
5568
5569         case DR_SWAP_CANCEL:
5570         case PR_SWAP_CANCEL:
5571         case VCONN_SWAP_CANCEL:
5572                 tcpm_swap_complete(port, port->swap_status);
5573                 if (port->pwr_role == TYPEC_SOURCE)
5574                         tcpm_set_state(port, SRC_READY, 0);
5575                 else
5576                         tcpm_set_state(port, SNK_READY, 0);
5577                 break;
5578         case FR_SWAP_CANCEL:
5579                 if (port->pwr_role == TYPEC_SOURCE)
5580                         tcpm_set_state(port, SRC_READY, 0);
5581                 else
5582                         tcpm_set_state(port, SNK_READY, 0);
5583                 break;
5584
5585         case BIST_RX:
5586                 switch (BDO_MODE_MASK(port->bist_request)) {
5587                 case BDO_MODE_CARRIER2:
5588                         tcpm_pd_transmit(port, TCPC_TX_BIST_MODE_2, NULL);
5589                         tcpm_set_state(port, unattached_state(port),
5590                                        PD_T_BIST_CONT_MODE);
5591                         break;
5592                 case BDO_MODE_TESTDATA:
5593                         if (port->tcpc->set_bist_data) {
5594                                 tcpm_log(port, "Enable BIST MODE TESTDATA");
5595                                 port->tcpc->set_bist_data(port->tcpc, true);
5596                         }
5597                         break;
5598                 default:
5599                         break;
5600                 }
5601                 break;
5602         case GET_STATUS_SEND:
5603                 tcpm_pd_send_control(port, PD_CTRL_GET_STATUS, TCPC_TX_SOP);
5604                 tcpm_set_state(port, GET_STATUS_SEND_TIMEOUT,
5605                                PD_T_SENDER_RESPONSE);
5606                 break;
5607         case GET_STATUS_SEND_TIMEOUT:
5608                 tcpm_set_state(port, ready_state(port), 0);
5609                 break;
5610         case GET_PPS_STATUS_SEND:
5611                 tcpm_pd_send_control(port, PD_CTRL_GET_PPS_STATUS, TCPC_TX_SOP);
5612                 tcpm_set_state(port, GET_PPS_STATUS_SEND_TIMEOUT,
5613                                PD_T_SENDER_RESPONSE);
5614                 break;
5615         case GET_PPS_STATUS_SEND_TIMEOUT:
5616                 tcpm_set_state(port, ready_state(port), 0);
5617                 break;
5618         case GET_SINK_CAP:
5619                 tcpm_pd_send_control(port, PD_CTRL_GET_SINK_CAP, TCPC_TX_SOP);
5620                 tcpm_set_state(port, GET_SINK_CAP_TIMEOUT, PD_T_SENDER_RESPONSE);
5621                 break;
5622         case GET_SINK_CAP_TIMEOUT:
5623                 port->sink_cap_done = true;
5624                 tcpm_set_state(port, ready_state(port), 0);
5625                 break;
5626         case ERROR_RECOVERY:
5627                 tcpm_swap_complete(port, -EPROTO);
5628                 tcpm_pps_complete(port, -EPROTO);
5629                 tcpm_set_state(port, PORT_RESET, 0);
5630                 break;
5631         case PORT_RESET:
5632                 tcpm_reset_port(port);
5633                 port->pd_events = 0;
5634                 if (port->self_powered)
5635                         tcpm_set_cc(port, TYPEC_CC_OPEN);
5636                 else
5637                         tcpm_set_cc(port, tcpm_default_state(port) == SNK_UNATTACHED ?
5638                                     TYPEC_CC_RD : tcpm_rp_cc(port));
5639                 tcpm_set_state(port, PORT_RESET_WAIT_OFF,
5640                                PD_T_ERROR_RECOVERY);
5641                 break;
5642         case PORT_RESET_WAIT_OFF:
5643                 tcpm_set_state(port,
5644                                tcpm_default_state(port),
5645                                port->vbus_present ? PD_T_PS_SOURCE_OFF : 0);
5646                 break;
5647
5648         /* AMS intermediate state */
5649         case AMS_START:
5650                 if (port->upcoming_state == INVALID_STATE) {
5651                         tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
5652                                        SRC_READY : SNK_READY, 0);
5653                         break;
5654                 }
5655
5656                 upcoming_state = port->upcoming_state;
5657                 port->upcoming_state = INVALID_STATE;
5658                 tcpm_set_state(port, upcoming_state, 0);
5659                 break;
5660
5661         /* Chunk state */
5662         case CHUNK_NOT_SUPP:
5663                 tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP, TCPC_TX_SOP);
5664                 tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ? SRC_READY : SNK_READY, 0);
5665                 break;
5666
5667         /* Cable states */
5668         case SRC_VDM_IDENTITY_REQUEST:
5669                 port->send_discover_prime = true;
5670                 port->tx_sop_type = TCPC_TX_SOP_PRIME;
5671                 mod_send_discover_delayed_work(port, 0);
5672                 port->upcoming_state = SRC_SEND_CAPABILITIES;
5673                 break;
5674
5675         default:
5676                 WARN(1, "Unexpected port state %d\n", port->state);
5677                 break;
5678         }
5679 }
5680
5681 static void tcpm_state_machine_work(struct kthread_work *work)
5682 {
5683         struct tcpm_port *port = container_of(work, struct tcpm_port, state_machine);
5684         enum tcpm_state prev_state;
5685
5686         mutex_lock(&port->lock);
5687         port->state_machine_running = true;
5688
5689         if (port->queued_message && tcpm_send_queued_message(port))
5690                 goto done;
5691
5692         /* If we were queued due to a delayed state change, update it now */
5693         if (port->delayed_state) {
5694                 tcpm_log(port, "state change %s -> %s [delayed %ld ms]",
5695                          tcpm_states[port->state],
5696                          tcpm_states[port->delayed_state], port->delay_ms);
5697                 port->prev_state = port->state;
5698                 port->state = port->delayed_state;
5699                 port->delayed_state = INVALID_STATE;
5700         }
5701
5702         /*
5703          * Continue running as long as we have (non-delayed) state changes
5704          * to make.
5705          */
5706         do {
5707                 prev_state = port->state;
5708                 run_state_machine(port);
5709                 if (port->queued_message)
5710                         tcpm_send_queued_message(port);
5711         } while (port->state != prev_state && !port->delayed_state);
5712
5713 done:
5714         port->state_machine_running = false;
5715         mutex_unlock(&port->lock);
5716 }
5717
5718 static void _tcpm_cc_change(struct tcpm_port *port, enum typec_cc_status cc1,
5719                             enum typec_cc_status cc2)
5720 {
5721         enum typec_cc_status old_cc1, old_cc2;
5722         enum tcpm_state new_state;
5723
5724         old_cc1 = port->cc1;
5725         old_cc2 = port->cc2;
5726         port->cc1 = cc1;
5727         port->cc2 = cc2;
5728
5729         tcpm_log_force(port,
5730                        "CC1: %u -> %u, CC2: %u -> %u [state %s, polarity %d, %s]",
5731                        old_cc1, cc1, old_cc2, cc2, tcpm_states[port->state],
5732                        port->polarity,
5733                        tcpm_port_is_disconnected(port) ? "disconnected"
5734                                                        : "connected");
5735
5736         switch (port->state) {
5737         case TOGGLING:
5738                 if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
5739                     tcpm_port_is_source(port))
5740                         tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
5741                 else if (tcpm_port_is_sink(port))
5742                         tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
5743                 break;
5744         case CHECK_CONTAMINANT:
5745                 /* Wait for Toggling to be resumed */
5746                 break;
5747         case SRC_UNATTACHED:
5748         case ACC_UNATTACHED:
5749                 if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
5750                     tcpm_port_is_source(port))
5751                         tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
5752                 break;
5753         case SRC_ATTACH_WAIT:
5754                 if (tcpm_port_is_disconnected(port) ||
5755                     tcpm_port_is_audio_detached(port))
5756                         tcpm_set_state(port, SRC_UNATTACHED, 0);
5757                 else if (cc1 != old_cc1 || cc2 != old_cc2)
5758                         tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
5759                 break;
5760         case SRC_ATTACHED:
5761         case SRC_STARTUP:
5762         case SRC_SEND_CAPABILITIES:
5763         case SRC_READY:
5764                 if (tcpm_port_is_disconnected(port) ||
5765                     !tcpm_port_is_source(port)) {
5766                         if (port->port_type == TYPEC_PORT_SRC)
5767                                 tcpm_set_state(port, SRC_UNATTACHED, tcpm_wait_for_discharge(port));
5768                         else
5769                                 tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
5770                 }
5771                 break;
5772         case SNK_UNATTACHED:
5773                 if (tcpm_port_is_sink(port))
5774                         tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
5775                 break;
5776         case SNK_ATTACH_WAIT:
5777                 if ((port->cc1 == TYPEC_CC_OPEN &&
5778                      port->cc2 != TYPEC_CC_OPEN) ||
5779                     (port->cc1 != TYPEC_CC_OPEN &&
5780                      port->cc2 == TYPEC_CC_OPEN))
5781                         new_state = SNK_DEBOUNCED;
5782                 else if (tcpm_port_is_disconnected(port))
5783                         new_state = SNK_UNATTACHED;
5784                 else
5785                         break;
5786                 if (new_state != port->delayed_state)
5787                         tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
5788                 break;
5789         case SNK_DEBOUNCED:
5790                 if (tcpm_port_is_disconnected(port))
5791                         new_state = SNK_UNATTACHED;
5792                 else if (port->vbus_present)
5793                         new_state = tcpm_try_src(port) ? SRC_TRY : SNK_ATTACHED;
5794                 else
5795                         new_state = SNK_UNATTACHED;
5796                 if (new_state != port->delayed_state)
5797                         tcpm_set_state(port, SNK_DEBOUNCED, 0);
5798                 break;
5799         case SNK_READY:
5800                 /*
5801                  * EXIT condition is based primarily on vbus disconnect and CC is secondary.
5802                  * "A port that has entered into USB PD communications with the Source and
5803                  * has seen the CC voltage exceed vRd-USB may monitor the CC pin to detect
5804                  * cable disconnect in addition to monitoring VBUS.
5805                  *
5806                  * A port that is monitoring the CC voltage for disconnect (but is not in
5807                  * the process of a USB PD PR_Swap or USB PD FR_Swap) shall transition to
5808                  * Unattached.SNK within tSinkDisconnect after the CC voltage remains below
5809                  * vRd-USB for tPDDebounce."
5810                  *
5811                  * When set_auto_vbus_discharge_threshold is enabled, CC pins go
5812                  * away before vbus decays to disconnect threshold. Allow
5813                  * disconnect to be driven by vbus disconnect when auto vbus
5814                  * discharge is enabled.
5815                  */
5816                 if (!port->auto_vbus_discharge_enabled && tcpm_port_is_disconnected(port))
5817                         tcpm_set_state(port, unattached_state(port), 0);
5818                 else if (!port->pd_capable &&
5819                          (cc1 != old_cc1 || cc2 != old_cc2))
5820                         tcpm_set_current_limit(port,
5821                                                tcpm_get_current_limit(port),
5822                                                5000);
5823                 break;
5824
5825         case AUDIO_ACC_ATTACHED:
5826                 if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
5827                         tcpm_set_state(port, AUDIO_ACC_DEBOUNCE, 0);
5828                 break;
5829         case AUDIO_ACC_DEBOUNCE:
5830                 if (tcpm_port_is_audio(port))
5831                         tcpm_set_state(port, AUDIO_ACC_ATTACHED, 0);
5832                 break;
5833
5834         case DEBUG_ACC_ATTACHED:
5835                 if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
5836                         tcpm_set_state(port, ACC_UNATTACHED, 0);
5837                 break;
5838
5839         case SNK_TRY:
5840                 /* Do nothing, waiting for timeout */
5841                 break;
5842
5843         case SNK_DISCOVERY:
5844                 /* CC line is unstable, wait for debounce */
5845                 if (tcpm_port_is_disconnected(port))
5846                         tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE, 0);
5847                 break;
5848         case SNK_DISCOVERY_DEBOUNCE:
5849                 break;
5850
5851         case SRC_TRYWAIT:
5852                 /* Hand over to state machine if needed */
5853                 if (!port->vbus_present && tcpm_port_is_source(port))
5854                         tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
5855                 break;
5856         case SRC_TRYWAIT_DEBOUNCE:
5857                 if (port->vbus_present || !tcpm_port_is_source(port))
5858                         tcpm_set_state(port, SRC_TRYWAIT, 0);
5859                 break;
5860         case SNK_TRY_WAIT_DEBOUNCE:
5861                 if (!tcpm_port_is_sink(port)) {
5862                         port->max_wait = 0;
5863                         tcpm_set_state(port, SRC_TRYWAIT, 0);
5864                 }
5865                 break;
5866         case SRC_TRY_WAIT:
5867                 if (tcpm_port_is_source(port))
5868                         tcpm_set_state(port, SRC_TRY_DEBOUNCE, 0);
5869                 break;
5870         case SRC_TRY_DEBOUNCE:
5871                 tcpm_set_state(port, SRC_TRY_WAIT, 0);
5872                 break;
5873         case SNK_TRYWAIT_DEBOUNCE:
5874                 if (tcpm_port_is_sink(port))
5875                         tcpm_set_state(port, SNK_TRYWAIT_VBUS, 0);
5876                 break;
5877         case SNK_TRYWAIT_VBUS:
5878                 if (!tcpm_port_is_sink(port))
5879                         tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
5880                 break;
5881         case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
5882                 if (!tcpm_port_is_sink(port))
5883                         tcpm_set_state(port, SRC_TRYWAIT, PD_T_TRY_CC_DEBOUNCE);
5884                 else
5885                         tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS, 0);
5886                 break;
5887         case SNK_TRYWAIT:
5888                 /* Do nothing, waiting for tCCDebounce */
5889                 break;
5890         case PR_SWAP_SNK_SRC_SINK_OFF:
5891         case PR_SWAP_SRC_SNK_TRANSITION_OFF:
5892         case PR_SWAP_SRC_SNK_SOURCE_OFF:
5893         case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
5894         case PR_SWAP_SNK_SRC_SOURCE_ON:
5895                 /*
5896                  * CC state change is expected in PR_SWAP
5897                  * Ignore it.
5898                  */
5899                 break;
5900         case FR_SWAP_SEND:
5901         case FR_SWAP_SEND_TIMEOUT:
5902         case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5903         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5904         case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5905                 /* Do nothing, CC change expected */
5906                 break;
5907
5908         case PORT_RESET:
5909         case PORT_RESET_WAIT_OFF:
5910                 /*
5911                  * State set back to default mode once the timer completes.
5912                  * Ignore CC changes here.
5913                  */
5914                 break;
5915         default:
5916                 /*
5917                  * While acting as sink and auto vbus discharge is enabled, Allow disconnect
5918                  * to be driven by vbus disconnect.
5919                  */
5920                 if (tcpm_port_is_disconnected(port) && !(port->pwr_role == TYPEC_SINK &&
5921                                                          port->auto_vbus_discharge_enabled))
5922                         tcpm_set_state(port, unattached_state(port), 0);
5923                 break;
5924         }
5925 }
5926
5927 static void _tcpm_pd_vbus_on(struct tcpm_port *port)
5928 {
5929         tcpm_log_force(port, "VBUS on");
5930         port->vbus_present = true;
5931         /*
5932          * When vbus_present is true i.e. Voltage at VBUS is greater than VSAFE5V implicitly
5933          * states that vbus is not at VSAFE0V, hence clear the vbus_vsafe0v flag here.
5934          */
5935         port->vbus_vsafe0v = false;
5936
5937         switch (port->state) {
5938         case SNK_TRANSITION_SINK_VBUS:
5939                 port->explicit_contract = true;
5940                 tcpm_set_state(port, SNK_READY, 0);
5941                 break;
5942         case SNK_DISCOVERY:
5943                 tcpm_set_state(port, SNK_DISCOVERY, 0);
5944                 break;
5945
5946         case SNK_DEBOUNCED:
5947                 tcpm_set_state(port, tcpm_try_src(port) ? SRC_TRY
5948                                                         : SNK_ATTACHED,
5949                                        0);
5950                 break;
5951         case SNK_HARD_RESET_WAIT_VBUS:
5952                 tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, 0);
5953                 break;
5954         case SRC_ATTACHED:
5955                 tcpm_set_state(port, SRC_STARTUP, 0);
5956                 break;
5957         case SRC_HARD_RESET_VBUS_ON:
5958                 tcpm_set_state(port, SRC_STARTUP, 0);
5959                 break;
5960
5961         case SNK_TRY:
5962                 /* Do nothing, waiting for timeout */
5963                 break;
5964         case SRC_TRYWAIT:
5965                 /* Do nothing, Waiting for Rd to be detected */
5966                 break;
5967         case SRC_TRYWAIT_DEBOUNCE:
5968                 tcpm_set_state(port, SRC_TRYWAIT, 0);
5969                 break;
5970         case SNK_TRY_WAIT_DEBOUNCE:
5971                 /* Do nothing, waiting for PD_DEBOUNCE to do be done */
5972                 break;
5973         case SNK_TRYWAIT:
5974                 /* Do nothing, waiting for tCCDebounce */
5975                 break;
5976         case SNK_TRYWAIT_VBUS:
5977                 if (tcpm_port_is_sink(port))
5978                         tcpm_set_state(port, SNK_ATTACHED, 0);
5979                 break;
5980         case SNK_TRYWAIT_DEBOUNCE:
5981                 /* Do nothing, waiting for Rp */
5982                 break;
5983         case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
5984                 if (port->vbus_present && tcpm_port_is_sink(port))
5985                         tcpm_set_state(port, SNK_ATTACHED, 0);
5986                 break;
5987         case SRC_TRY_WAIT:
5988         case SRC_TRY_DEBOUNCE:
5989                 /* Do nothing, waiting for sink detection */
5990                 break;
5991         case FR_SWAP_SEND:
5992         case FR_SWAP_SEND_TIMEOUT:
5993         case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5994         case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5995                 if (port->tcpc->frs_sourcing_vbus)
5996                         port->tcpc->frs_sourcing_vbus(port->tcpc);
5997                 break;
5998         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5999                 if (port->tcpc->frs_sourcing_vbus)
6000                         port->tcpc->frs_sourcing_vbus(port->tcpc);
6001                 tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
6002                 break;
6003
6004         case PORT_RESET:
6005         case PORT_RESET_WAIT_OFF:
6006                 /*
6007                  * State set back to default mode once the timer completes.
6008                  * Ignore vbus changes here.
6009                  */
6010                 break;
6011
6012         default:
6013                 break;
6014         }
6015 }
6016
6017 static void _tcpm_pd_vbus_off(struct tcpm_port *port)
6018 {
6019         tcpm_log_force(port, "VBUS off");
6020         port->vbus_present = false;
6021         port->vbus_never_low = false;
6022         switch (port->state) {
6023         case SNK_HARD_RESET_SINK_OFF:
6024                 tcpm_set_state(port, SNK_HARD_RESET_WAIT_VBUS, 0);
6025                 break;
6026         case HARD_RESET_SEND:
6027                 break;
6028         case SNK_TRY:
6029                 /* Do nothing, waiting for timeout */
6030                 break;
6031         case SRC_TRYWAIT:
6032                 /* Hand over to state machine if needed */
6033                 if (tcpm_port_is_source(port))
6034                         tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
6035                 break;
6036         case SNK_TRY_WAIT_DEBOUNCE:
6037                 /* Do nothing, waiting for PD_DEBOUNCE to do be done */
6038                 break;
6039         case SNK_TRYWAIT:
6040         case SNK_TRYWAIT_VBUS:
6041         case SNK_TRYWAIT_DEBOUNCE:
6042                 break;
6043         case SNK_ATTACH_WAIT:
6044         case SNK_DEBOUNCED:
6045                 /* Do nothing, as TCPM is still waiting for vbus to reaach VSAFE5V to connect */
6046                 break;
6047
6048         case SNK_NEGOTIATE_CAPABILITIES:
6049                 break;
6050
6051         case PR_SWAP_SRC_SNK_TRANSITION_OFF:
6052                 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF, 0);
6053                 break;
6054
6055         case PR_SWAP_SNK_SRC_SINK_OFF:
6056                 /* Do nothing, expected */
6057                 break;
6058
6059         case PR_SWAP_SNK_SRC_SOURCE_ON:
6060                 /*
6061                  * Do nothing when vbus off notification is received.
6062                  * TCPM can wait for PD_T_NEWSRC in PR_SWAP_SNK_SRC_SOURCE_ON
6063                  * for the vbus source to ramp up.
6064                  */
6065                 break;
6066
6067         case PORT_RESET_WAIT_OFF:
6068                 tcpm_set_state(port, tcpm_default_state(port), 0);
6069                 break;
6070
6071         case SRC_TRY_WAIT:
6072         case SRC_TRY_DEBOUNCE:
6073                 /* Do nothing, waiting for sink detection */
6074                 break;
6075
6076         case SRC_STARTUP:
6077         case SRC_SEND_CAPABILITIES:
6078         case SRC_SEND_CAPABILITIES_TIMEOUT:
6079         case SRC_NEGOTIATE_CAPABILITIES:
6080         case SRC_TRANSITION_SUPPLY:
6081         case SRC_READY:
6082         case SRC_WAIT_NEW_CAPABILITIES:
6083                 /*
6084                  * Force to unattached state to re-initiate connection.
6085                  * DRP port should move to Unattached.SNK instead of Unattached.SRC if
6086                  * sink removed. Although sink removal here is due to source's vbus collapse,
6087                  * treat it the same way for consistency.
6088                  */
6089                 if (port->port_type == TYPEC_PORT_SRC)
6090                         tcpm_set_state(port, SRC_UNATTACHED, tcpm_wait_for_discharge(port));
6091                 else
6092                         tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
6093                 break;
6094
6095         case PORT_RESET:
6096                 /*
6097                  * State set back to default mode once the timer completes.
6098                  * Ignore vbus changes here.
6099                  */
6100                 break;
6101
6102         case FR_SWAP_SEND:
6103         case FR_SWAP_SEND_TIMEOUT:
6104         case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
6105         case FR_SWAP_SNK_SRC_NEW_SINK_READY:
6106         case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
6107                 /* Do nothing, vbus drop expected */
6108                 break;
6109
6110         case SNK_HARD_RESET_WAIT_VBUS:
6111                 /* Do nothing, its OK to receive vbus off events */
6112                 break;
6113
6114         default:
6115                 if (port->pwr_role == TYPEC_SINK && port->attached)
6116                         tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
6117                 break;
6118         }
6119 }
6120
6121 static void _tcpm_pd_vbus_vsafe0v(struct tcpm_port *port)
6122 {
6123         tcpm_log_force(port, "VBUS VSAFE0V");
6124         port->vbus_vsafe0v = true;
6125         switch (port->state) {
6126         case SRC_HARD_RESET_VBUS_OFF:
6127                 /*
6128                  * After establishing the vSafe0V voltage condition on VBUS, the Source Shall wait
6129                  * tSrcRecover before re-applying VCONN and restoring VBUS to vSafe5V.
6130                  */
6131                 tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SRC_RECOVER);
6132                 break;
6133         case SRC_ATTACH_WAIT:
6134                 if (tcpm_port_is_source(port))
6135                         tcpm_set_state(port, tcpm_try_snk(port) ? SNK_TRY : SRC_ATTACHED,
6136                                        PD_T_CC_DEBOUNCE);
6137                 break;
6138         case SRC_STARTUP:
6139         case SRC_SEND_CAPABILITIES:
6140         case SRC_SEND_CAPABILITIES_TIMEOUT:
6141         case SRC_NEGOTIATE_CAPABILITIES:
6142         case SRC_TRANSITION_SUPPLY:
6143         case SRC_READY:
6144         case SRC_WAIT_NEW_CAPABILITIES:
6145                 if (port->auto_vbus_discharge_enabled) {
6146                         if (port->port_type == TYPEC_PORT_SRC)
6147                                 tcpm_set_state(port, SRC_UNATTACHED, 0);
6148                         else
6149                                 tcpm_set_state(port, SNK_UNATTACHED, 0);
6150                 }
6151                 break;
6152         case PR_SWAP_SNK_SRC_SINK_OFF:
6153         case PR_SWAP_SNK_SRC_SOURCE_ON:
6154                 /* Do nothing, vsafe0v is expected during transition */
6155                 break;
6156         case SNK_ATTACH_WAIT:
6157         case SNK_DEBOUNCED:
6158                 /*Do nothing, still waiting for VSAFE5V for connect */
6159                 break;
6160         case SNK_HARD_RESET_WAIT_VBUS:
6161                 /* Do nothing, its OK to receive vbus off events */
6162                 break;
6163         default:
6164                 if (port->pwr_role == TYPEC_SINK && port->auto_vbus_discharge_enabled)
6165                         tcpm_set_state(port, SNK_UNATTACHED, 0);
6166                 break;
6167         }
6168 }
6169
6170 static void _tcpm_pd_hard_reset(struct tcpm_port *port)
6171 {
6172         tcpm_log_force(port, "Received hard reset");
6173         if (port->bist_request == BDO_MODE_TESTDATA && port->tcpc->set_bist_data)
6174                 port->tcpc->set_bist_data(port->tcpc, false);
6175
6176         switch (port->state) {
6177         case TOGGLING:
6178         case ERROR_RECOVERY:
6179         case PORT_RESET:
6180         case PORT_RESET_WAIT_OFF:
6181                 return;
6182         default:
6183                 break;
6184         }
6185
6186         if (port->ams != NONE_AMS)
6187                 port->ams = NONE_AMS;
6188         if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
6189                 port->ams = HARD_RESET;
6190         /*
6191          * If we keep receiving hard reset requests, executing the hard reset
6192          * must have failed. Revert to error recovery if that happens.
6193          */
6194         tcpm_set_state(port,
6195                        port->hard_reset_count < PD_N_HARD_RESET_COUNT ?
6196                                 HARD_RESET_START : ERROR_RECOVERY,
6197                        0);
6198 }
6199
6200 static void tcpm_pd_event_handler(struct kthread_work *work)
6201 {
6202         struct tcpm_port *port = container_of(work, struct tcpm_port,
6203                                               event_work);
6204         u32 events;
6205
6206         mutex_lock(&port->lock);
6207
6208         spin_lock(&port->pd_event_lock);
6209         while (port->pd_events) {
6210                 events = port->pd_events;
6211                 port->pd_events = 0;
6212                 spin_unlock(&port->pd_event_lock);
6213                 if (events & TCPM_RESET_EVENT)
6214                         _tcpm_pd_hard_reset(port);
6215                 if (events & TCPM_VBUS_EVENT) {
6216                         bool vbus;
6217
6218                         vbus = port->tcpc->get_vbus(port->tcpc);
6219                         if (vbus) {
6220                                 _tcpm_pd_vbus_on(port);
6221                         } else {
6222                                 _tcpm_pd_vbus_off(port);
6223                                 /*
6224                                  * When TCPC does not support detecting vsafe0v voltage level,
6225                                  * treat vbus absent as vsafe0v. Else invoke is_vbus_vsafe0v
6226                                  * to see if vbus has discharge to VSAFE0V.
6227                                  */
6228                                 if (!port->tcpc->is_vbus_vsafe0v ||
6229                                     port->tcpc->is_vbus_vsafe0v(port->tcpc))
6230                                         _tcpm_pd_vbus_vsafe0v(port);
6231                         }
6232                 }
6233                 if (events & TCPM_CC_EVENT) {
6234                         enum typec_cc_status cc1, cc2;
6235
6236                         if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
6237                                 _tcpm_cc_change(port, cc1, cc2);
6238                 }
6239                 if (events & TCPM_FRS_EVENT) {
6240                         if (port->state == SNK_READY) {
6241                                 int ret;
6242
6243                                 port->upcoming_state = FR_SWAP_SEND;
6244                                 ret = tcpm_ams_start(port, FAST_ROLE_SWAP);
6245                                 if (ret == -EAGAIN)
6246                                         port->upcoming_state = INVALID_STATE;
6247                         } else {
6248                                 tcpm_log(port, "Discarding FRS_SIGNAL! Not in sink ready");
6249                         }
6250                 }
6251                 if (events & TCPM_SOURCING_VBUS) {
6252                         tcpm_log(port, "sourcing vbus");
6253                         /*
6254                          * In fast role swap case TCPC autonomously sources vbus. Set vbus_source
6255                          * true as TCPM wouldn't have called tcpm_set_vbus.
6256                          *
6257                          * When vbus is sourced on the command on TCPM i.e. TCPM called
6258                          * tcpm_set_vbus to source vbus, vbus_source would already be true.
6259                          */
6260                         port->vbus_source = true;
6261                         _tcpm_pd_vbus_on(port);
6262                 }
6263                 if (events & TCPM_PORT_CLEAN) {
6264                         tcpm_log(port, "port clean");
6265                         if (port->state == CHECK_CONTAMINANT) {
6266                                 if (tcpm_start_toggling(port, tcpm_rp_cc(port)))
6267                                         tcpm_set_state(port, TOGGLING, 0);
6268                                 else
6269                                         tcpm_set_state(port, tcpm_default_state(port), 0);
6270                         }
6271                 }
6272                 if (events & TCPM_PORT_ERROR) {
6273                         tcpm_log(port, "port triggering error recovery");
6274                         tcpm_set_state(port, ERROR_RECOVERY, 0);
6275                 }
6276
6277                 spin_lock(&port->pd_event_lock);
6278         }
6279         spin_unlock(&port->pd_event_lock);
6280         mutex_unlock(&port->lock);
6281 }
6282
6283 void tcpm_cc_change(struct tcpm_port *port)
6284 {
6285         spin_lock(&port->pd_event_lock);
6286         port->pd_events |= TCPM_CC_EVENT;
6287         spin_unlock(&port->pd_event_lock);
6288         kthread_queue_work(port->wq, &port->event_work);
6289 }
6290 EXPORT_SYMBOL_GPL(tcpm_cc_change);
6291
6292 void tcpm_vbus_change(struct tcpm_port *port)
6293 {
6294         spin_lock(&port->pd_event_lock);
6295         port->pd_events |= TCPM_VBUS_EVENT;
6296         spin_unlock(&port->pd_event_lock);
6297         kthread_queue_work(port->wq, &port->event_work);
6298 }
6299 EXPORT_SYMBOL_GPL(tcpm_vbus_change);
6300
6301 void tcpm_pd_hard_reset(struct tcpm_port *port)
6302 {
6303         spin_lock(&port->pd_event_lock);
6304         port->pd_events = TCPM_RESET_EVENT;
6305         spin_unlock(&port->pd_event_lock);
6306         kthread_queue_work(port->wq, &port->event_work);
6307 }
6308 EXPORT_SYMBOL_GPL(tcpm_pd_hard_reset);
6309
6310 void tcpm_sink_frs(struct tcpm_port *port)
6311 {
6312         spin_lock(&port->pd_event_lock);
6313         port->pd_events |= TCPM_FRS_EVENT;
6314         spin_unlock(&port->pd_event_lock);
6315         kthread_queue_work(port->wq, &port->event_work);
6316 }
6317 EXPORT_SYMBOL_GPL(tcpm_sink_frs);
6318
6319 void tcpm_sourcing_vbus(struct tcpm_port *port)
6320 {
6321         spin_lock(&port->pd_event_lock);
6322         port->pd_events |= TCPM_SOURCING_VBUS;
6323         spin_unlock(&port->pd_event_lock);
6324         kthread_queue_work(port->wq, &port->event_work);
6325 }
6326 EXPORT_SYMBOL_GPL(tcpm_sourcing_vbus);
6327
6328 void tcpm_port_clean(struct tcpm_port *port)
6329 {
6330         spin_lock(&port->pd_event_lock);
6331         port->pd_events |= TCPM_PORT_CLEAN;
6332         spin_unlock(&port->pd_event_lock);
6333         kthread_queue_work(port->wq, &port->event_work);
6334 }
6335 EXPORT_SYMBOL_GPL(tcpm_port_clean);
6336
6337 bool tcpm_port_is_toggling(struct tcpm_port *port)
6338 {
6339         return port->port_type == TYPEC_PORT_DRP && port->state == TOGGLING;
6340 }
6341 EXPORT_SYMBOL_GPL(tcpm_port_is_toggling);
6342
6343 void tcpm_port_error_recovery(struct tcpm_port *port)
6344 {
6345         spin_lock(&port->pd_event_lock);
6346         port->pd_events |= TCPM_PORT_ERROR;
6347         spin_unlock(&port->pd_event_lock);
6348         kthread_queue_work(port->wq, &port->event_work);
6349 }
6350 EXPORT_SYMBOL_GPL(tcpm_port_error_recovery);
6351
6352 static void tcpm_enable_frs_work(struct kthread_work *work)
6353 {
6354         struct tcpm_port *port = container_of(work, struct tcpm_port, enable_frs);
6355         int ret;
6356
6357         mutex_lock(&port->lock);
6358         /* Not FRS capable */
6359         if (!port->connected || port->port_type != TYPEC_PORT_DRP ||
6360             port->pwr_opmode != TYPEC_PWR_MODE_PD ||
6361             !port->tcpc->enable_frs ||
6362             /* Sink caps queried */
6363             port->sink_cap_done || port->negotiated_rev < PD_REV30)
6364                 goto unlock;
6365
6366         /* Send when the state machine is idle */
6367         if (port->state != SNK_READY || port->vdm_sm_running || port->send_discover ||
6368             port->send_discover_prime)
6369                 goto resched;
6370
6371         port->upcoming_state = GET_SINK_CAP;
6372         ret = tcpm_ams_start(port, GET_SINK_CAPABILITIES);
6373         if (ret == -EAGAIN) {
6374                 port->upcoming_state = INVALID_STATE;
6375         } else {
6376                 port->sink_cap_done = true;
6377                 goto unlock;
6378         }
6379 resched:
6380         mod_enable_frs_delayed_work(port, GET_SINK_CAP_RETRY_MS);
6381 unlock:
6382         mutex_unlock(&port->lock);
6383 }
6384
6385 static void tcpm_send_discover_work(struct kthread_work *work)
6386 {
6387         struct tcpm_port *port = container_of(work, struct tcpm_port, send_discover_work);
6388
6389         mutex_lock(&port->lock);
6390         /* No need to send DISCOVER_IDENTITY anymore */
6391         if (!port->send_discover && !port->send_discover_prime)
6392                 goto unlock;
6393
6394         if (port->data_role == TYPEC_DEVICE && port->negotiated_rev < PD_REV30) {
6395                 port->send_discover = false;
6396                 port->send_discover_prime = false;
6397                 goto unlock;
6398         }
6399
6400         /* Retry if the port is not idle */
6401         if ((port->state != SRC_READY && port->state != SNK_READY &&
6402              port->state != SRC_VDM_IDENTITY_REQUEST) || port->vdm_sm_running) {
6403                 mod_send_discover_delayed_work(port, SEND_DISCOVER_RETRY_MS);
6404                 goto unlock;
6405         }
6406
6407         tcpm_send_vdm(port, USB_SID_PD, CMD_DISCOVER_IDENT, NULL, 0, port->tx_sop_type);
6408
6409 unlock:
6410         mutex_unlock(&port->lock);
6411 }
6412
6413 static int tcpm_dr_set(struct typec_port *p, enum typec_data_role data)
6414 {
6415         struct tcpm_port *port = typec_get_drvdata(p);
6416         int ret;
6417
6418         mutex_lock(&port->swap_lock);
6419         mutex_lock(&port->lock);
6420
6421         if (port->typec_caps.data != TYPEC_PORT_DRD) {
6422                 ret = -EINVAL;
6423                 goto port_unlock;
6424         }
6425         if (port->state != SRC_READY && port->state != SNK_READY) {
6426                 ret = -EAGAIN;
6427                 goto port_unlock;
6428         }
6429
6430         if (port->data_role == data) {
6431                 ret = 0;
6432                 goto port_unlock;
6433         }
6434
6435         /*
6436          * XXX
6437          * 6.3.9: If an alternate mode is active, a request to swap
6438          * alternate modes shall trigger a port reset.
6439          * Reject data role swap request in this case.
6440          */
6441
6442         if (!port->pd_capable) {
6443                 /*
6444                  * If the partner is not PD capable, reset the port to
6445                  * trigger a role change. This can only work if a preferred
6446                  * role is configured, and if it matches the requested role.
6447                  */
6448                 if (port->try_role == TYPEC_NO_PREFERRED_ROLE ||
6449                     port->try_role == port->pwr_role) {
6450                         ret = -EINVAL;
6451                         goto port_unlock;
6452                 }
6453                 port->non_pd_role_swap = true;
6454                 tcpm_set_state(port, PORT_RESET, 0);
6455         } else {
6456                 port->upcoming_state = DR_SWAP_SEND;
6457                 ret = tcpm_ams_start(port, DATA_ROLE_SWAP);
6458                 if (ret == -EAGAIN) {
6459                         port->upcoming_state = INVALID_STATE;
6460                         goto port_unlock;
6461                 }
6462         }
6463
6464         port->swap_status = 0;
6465         port->swap_pending = true;
6466         reinit_completion(&port->swap_complete);
6467         mutex_unlock(&port->lock);
6468
6469         if (!wait_for_completion_timeout(&port->swap_complete,
6470                                 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
6471                 ret = -ETIMEDOUT;
6472         else
6473                 ret = port->swap_status;
6474
6475         port->non_pd_role_swap = false;
6476         goto swap_unlock;
6477
6478 port_unlock:
6479         mutex_unlock(&port->lock);
6480 swap_unlock:
6481         mutex_unlock(&port->swap_lock);
6482         return ret;
6483 }
6484
6485 static int tcpm_pr_set(struct typec_port *p, enum typec_role role)
6486 {
6487         struct tcpm_port *port = typec_get_drvdata(p);
6488         int ret;
6489
6490         mutex_lock(&port->swap_lock);
6491         mutex_lock(&port->lock);
6492
6493         if (port->port_type != TYPEC_PORT_DRP) {
6494                 ret = -EINVAL;
6495                 goto port_unlock;
6496         }
6497         if (port->state != SRC_READY && port->state != SNK_READY) {
6498                 ret = -EAGAIN;
6499                 goto port_unlock;
6500         }
6501
6502         if (role == port->pwr_role) {
6503                 ret = 0;
6504                 goto port_unlock;
6505         }
6506
6507         port->upcoming_state = PR_SWAP_SEND;
6508         ret = tcpm_ams_start(port, POWER_ROLE_SWAP);
6509         if (ret == -EAGAIN) {
6510                 port->upcoming_state = INVALID_STATE;
6511                 goto port_unlock;
6512         }
6513
6514         port->swap_status = 0;
6515         port->swap_pending = true;
6516         reinit_completion(&port->swap_complete);
6517         mutex_unlock(&port->lock);
6518
6519         if (!wait_for_completion_timeout(&port->swap_complete,
6520                                 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
6521                 ret = -ETIMEDOUT;
6522         else
6523                 ret = port->swap_status;
6524
6525         goto swap_unlock;
6526
6527 port_unlock:
6528         mutex_unlock(&port->lock);
6529 swap_unlock:
6530         mutex_unlock(&port->swap_lock);
6531         return ret;
6532 }
6533
6534 static int tcpm_vconn_set(struct typec_port *p, enum typec_role role)
6535 {
6536         struct tcpm_port *port = typec_get_drvdata(p);
6537         int ret;
6538
6539         mutex_lock(&port->swap_lock);
6540         mutex_lock(&port->lock);
6541
6542         if (port->state != SRC_READY && port->state != SNK_READY) {
6543                 ret = -EAGAIN;
6544                 goto port_unlock;
6545         }
6546
6547         if (role == port->vconn_role) {
6548                 ret = 0;
6549                 goto port_unlock;
6550         }
6551
6552         port->upcoming_state = VCONN_SWAP_SEND;
6553         ret = tcpm_ams_start(port, VCONN_SWAP);
6554         if (ret == -EAGAIN) {
6555                 port->upcoming_state = INVALID_STATE;
6556                 goto port_unlock;
6557         }
6558
6559         port->swap_status = 0;
6560         port->swap_pending = true;
6561         reinit_completion(&port->swap_complete);
6562         mutex_unlock(&port->lock);
6563
6564         if (!wait_for_completion_timeout(&port->swap_complete,
6565                                 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
6566                 ret = -ETIMEDOUT;
6567         else
6568                 ret = port->swap_status;
6569
6570         goto swap_unlock;
6571
6572 port_unlock:
6573         mutex_unlock(&port->lock);
6574 swap_unlock:
6575         mutex_unlock(&port->swap_lock);
6576         return ret;
6577 }
6578
6579 static int tcpm_try_role(struct typec_port *p, int role)
6580 {
6581         struct tcpm_port *port = typec_get_drvdata(p);
6582         struct tcpc_dev *tcpc = port->tcpc;
6583         int ret = 0;
6584
6585         mutex_lock(&port->lock);
6586         if (tcpc->try_role)
6587                 ret = tcpc->try_role(tcpc, role);
6588         if (!ret)
6589                 port->try_role = role;
6590         port->try_src_count = 0;
6591         port->try_snk_count = 0;
6592         mutex_unlock(&port->lock);
6593
6594         return ret;
6595 }
6596
6597 static int tcpm_pps_set_op_curr(struct tcpm_port *port, u16 req_op_curr)
6598 {
6599         unsigned int target_mw;
6600         int ret;
6601
6602         mutex_lock(&port->swap_lock);
6603         mutex_lock(&port->lock);
6604
6605         if (!port->pps_data.active) {
6606                 ret = -EOPNOTSUPP;
6607                 goto port_unlock;
6608         }
6609
6610         if (port->state != SNK_READY) {
6611                 ret = -EAGAIN;
6612                 goto port_unlock;
6613         }
6614
6615         if (req_op_curr > port->pps_data.max_curr) {
6616                 ret = -EINVAL;
6617                 goto port_unlock;
6618         }
6619
6620         target_mw = (req_op_curr * port->supply_voltage) / 1000;
6621         if (target_mw < port->operating_snk_mw) {
6622                 ret = -EINVAL;
6623                 goto port_unlock;
6624         }
6625
6626         port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6627         ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6628         if (ret == -EAGAIN) {
6629                 port->upcoming_state = INVALID_STATE;
6630                 goto port_unlock;
6631         }
6632
6633         /* Round down operating current to align with PPS valid steps */
6634         req_op_curr = req_op_curr - (req_op_curr % RDO_PROG_CURR_MA_STEP);
6635
6636         reinit_completion(&port->pps_complete);
6637         port->pps_data.req_op_curr = req_op_curr;
6638         port->pps_status = 0;
6639         port->pps_pending = true;
6640         mutex_unlock(&port->lock);
6641
6642         if (!wait_for_completion_timeout(&port->pps_complete,
6643                                 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
6644                 ret = -ETIMEDOUT;
6645         else
6646                 ret = port->pps_status;
6647
6648         goto swap_unlock;
6649
6650 port_unlock:
6651         mutex_unlock(&port->lock);
6652 swap_unlock:
6653         mutex_unlock(&port->swap_lock);
6654
6655         return ret;
6656 }
6657
6658 static int tcpm_pps_set_out_volt(struct tcpm_port *port, u16 req_out_volt)
6659 {
6660         unsigned int target_mw;
6661         int ret;
6662
6663         mutex_lock(&port->swap_lock);
6664         mutex_lock(&port->lock);
6665
6666         if (!port->pps_data.active) {
6667                 ret = -EOPNOTSUPP;
6668                 goto port_unlock;
6669         }
6670
6671         if (port->state != SNK_READY) {
6672                 ret = -EAGAIN;
6673                 goto port_unlock;
6674         }
6675
6676         target_mw = (port->current_limit * req_out_volt) / 1000;
6677         if (target_mw < port->operating_snk_mw) {
6678                 ret = -EINVAL;
6679                 goto port_unlock;
6680         }
6681
6682         port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6683         ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6684         if (ret == -EAGAIN) {
6685                 port->upcoming_state = INVALID_STATE;
6686                 goto port_unlock;
6687         }
6688
6689         /* Round down output voltage to align with PPS valid steps */
6690         req_out_volt = req_out_volt - (req_out_volt % RDO_PROG_VOLT_MV_STEP);
6691
6692         reinit_completion(&port->pps_complete);
6693         port->pps_data.req_out_volt = req_out_volt;
6694         port->pps_status = 0;
6695         port->pps_pending = true;
6696         mutex_unlock(&port->lock);
6697
6698         if (!wait_for_completion_timeout(&port->pps_complete,
6699                                 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
6700                 ret = -ETIMEDOUT;
6701         else
6702                 ret = port->pps_status;
6703
6704         goto swap_unlock;
6705
6706 port_unlock:
6707         mutex_unlock(&port->lock);
6708 swap_unlock:
6709         mutex_unlock(&port->swap_lock);
6710
6711         return ret;
6712 }
6713
6714 static int tcpm_pps_activate(struct tcpm_port *port, bool activate)
6715 {
6716         int ret = 0;
6717
6718         mutex_lock(&port->swap_lock);
6719         mutex_lock(&port->lock);
6720
6721         if (!port->pps_data.supported) {
6722                 ret = -EOPNOTSUPP;
6723                 goto port_unlock;
6724         }
6725
6726         /* Trying to deactivate PPS when already deactivated so just bail */
6727         if (!port->pps_data.active && !activate)
6728                 goto port_unlock;
6729
6730         if (port->state != SNK_READY) {
6731                 ret = -EAGAIN;
6732                 goto port_unlock;
6733         }
6734
6735         if (activate)
6736                 port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6737         else
6738                 port->upcoming_state = SNK_NEGOTIATE_CAPABILITIES;
6739         ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6740         if (ret == -EAGAIN) {
6741                 port->upcoming_state = INVALID_STATE;
6742                 goto port_unlock;
6743         }
6744
6745         reinit_completion(&port->pps_complete);
6746         port->pps_status = 0;
6747         port->pps_pending = true;
6748
6749         /* Trigger PPS request or move back to standard PDO contract */
6750         if (activate) {
6751                 port->pps_data.req_out_volt = port->supply_voltage;
6752                 port->pps_data.req_op_curr = port->current_limit;
6753         }
6754         mutex_unlock(&port->lock);
6755
6756         if (!wait_for_completion_timeout(&port->pps_complete,
6757                                 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
6758                 ret = -ETIMEDOUT;
6759         else
6760                 ret = port->pps_status;
6761
6762         goto swap_unlock;
6763
6764 port_unlock:
6765         mutex_unlock(&port->lock);
6766 swap_unlock:
6767         mutex_unlock(&port->swap_lock);
6768
6769         return ret;
6770 }
6771
6772 static void tcpm_init(struct tcpm_port *port)
6773 {
6774         enum typec_cc_status cc1, cc2;
6775
6776         port->tcpc->init(port->tcpc);
6777
6778         tcpm_reset_port(port);
6779
6780         /*
6781          * XXX
6782          * Should possibly wait for VBUS to settle if it was enabled locally
6783          * since tcpm_reset_port() will disable VBUS.
6784          */
6785         port->vbus_present = port->tcpc->get_vbus(port->tcpc);
6786         if (port->vbus_present)
6787                 port->vbus_never_low = true;
6788
6789         /*
6790          * 1. When vbus_present is true, voltage on VBUS is already at VSAFE5V.
6791          * So implicitly vbus_vsafe0v = false.
6792          *
6793          * 2. When vbus_present is false and TCPC does NOT support querying
6794          * vsafe0v status, then, it's best to assume vbus is at VSAFE0V i.e.
6795          * vbus_vsafe0v is true.
6796          *
6797          * 3. When vbus_present is false and TCPC does support querying vsafe0v,
6798          * then, query tcpc for vsafe0v status.
6799          */
6800         if (port->vbus_present)
6801                 port->vbus_vsafe0v = false;
6802         else if (!port->tcpc->is_vbus_vsafe0v)
6803                 port->vbus_vsafe0v = true;
6804         else
6805                 port->vbus_vsafe0v = port->tcpc->is_vbus_vsafe0v(port->tcpc);
6806
6807         tcpm_set_state(port, tcpm_default_state(port), 0);
6808
6809         if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
6810                 _tcpm_cc_change(port, cc1, cc2);
6811
6812         /*
6813          * Some adapters need a clean slate at startup, and won't recover
6814          * otherwise. So do not try to be fancy and force a clean disconnect.
6815          */
6816         tcpm_set_state(port, PORT_RESET, 0);
6817 }
6818
6819 static int tcpm_port_type_set(struct typec_port *p, enum typec_port_type type)
6820 {
6821         struct tcpm_port *port = typec_get_drvdata(p);
6822
6823         mutex_lock(&port->lock);
6824         if (type == port->port_type)
6825                 goto port_unlock;
6826
6827         port->port_type = type;
6828
6829         if (!port->connected) {
6830                 tcpm_set_state(port, PORT_RESET, 0);
6831         } else if (type == TYPEC_PORT_SNK) {
6832                 if (!(port->pwr_role == TYPEC_SINK &&
6833                       port->data_role == TYPEC_DEVICE))
6834                         tcpm_set_state(port, PORT_RESET, 0);
6835         } else if (type == TYPEC_PORT_SRC) {
6836                 if (!(port->pwr_role == TYPEC_SOURCE &&
6837                       port->data_role == TYPEC_HOST))
6838                         tcpm_set_state(port, PORT_RESET, 0);
6839         }
6840
6841 port_unlock:
6842         mutex_unlock(&port->lock);
6843         return 0;
6844 }
6845
6846 static struct pd_data *tcpm_find_pd_data(struct tcpm_port *port, struct usb_power_delivery *pd)
6847 {
6848         int i;
6849
6850         for (i = 0; port->pd_list[i]; i++) {
6851                 if (port->pd_list[i]->pd == pd)
6852                         return port->pd_list[i];
6853         }
6854
6855         return ERR_PTR(-ENODATA);
6856 }
6857
6858 static struct usb_power_delivery **tcpm_pd_get(struct typec_port *p)
6859 {
6860         struct tcpm_port *port = typec_get_drvdata(p);
6861
6862         return port->pds;
6863 }
6864
6865 static int tcpm_pd_set(struct typec_port *p, struct usb_power_delivery *pd)
6866 {
6867         struct tcpm_port *port = typec_get_drvdata(p);
6868         struct pd_data *data;
6869         int i, ret = 0;
6870
6871         mutex_lock(&port->lock);
6872
6873         if (port->selected_pd == pd)
6874                 goto unlock;
6875
6876         data = tcpm_find_pd_data(port, pd);
6877         if (IS_ERR(data)) {
6878                 ret = PTR_ERR(data);
6879                 goto unlock;
6880         }
6881
6882         if (data->sink_desc.pdo[0]) {
6883                 for (i = 0; i < PDO_MAX_OBJECTS && data->sink_desc.pdo[i]; i++)
6884                         port->snk_pdo[i] = data->sink_desc.pdo[i];
6885                 port->nr_snk_pdo = i;
6886                 port->operating_snk_mw = data->operating_snk_mw;
6887         }
6888
6889         if (data->source_desc.pdo[0]) {
6890                 for (i = 0; i < PDO_MAX_OBJECTS && data->source_desc.pdo[i]; i++)
6891                         port->src_pdo[i] = data->source_desc.pdo[i];
6892                 port->nr_src_pdo = i;
6893         }
6894
6895         switch (port->state) {
6896         case SRC_UNATTACHED:
6897         case SRC_ATTACH_WAIT:
6898         case SRC_TRYWAIT:
6899                 tcpm_set_cc(port, tcpm_rp_cc(port));
6900                 break;
6901         case SRC_SEND_CAPABILITIES:
6902         case SRC_SEND_CAPABILITIES_TIMEOUT:
6903         case SRC_NEGOTIATE_CAPABILITIES:
6904         case SRC_READY:
6905         case SRC_WAIT_NEW_CAPABILITIES:
6906                 port->caps_count = 0;
6907                 port->upcoming_state = SRC_SEND_CAPABILITIES;
6908                 ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6909                 if (ret == -EAGAIN) {
6910                         port->upcoming_state = INVALID_STATE;
6911                         goto unlock;
6912                 }
6913                 break;
6914         case SNK_NEGOTIATE_CAPABILITIES:
6915         case SNK_NEGOTIATE_PPS_CAPABILITIES:
6916         case SNK_READY:
6917         case SNK_TRANSITION_SINK:
6918         case SNK_TRANSITION_SINK_VBUS:
6919                 if (port->pps_data.active)
6920                         port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6921                 else if (port->pd_capable)
6922                         port->upcoming_state = SNK_NEGOTIATE_CAPABILITIES;
6923                 else
6924                         break;
6925
6926                 port->update_sink_caps = true;
6927
6928                 ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6929                 if (ret == -EAGAIN) {
6930                         port->upcoming_state = INVALID_STATE;
6931                         goto unlock;
6932                 }
6933                 break;
6934         default:
6935                 break;
6936         }
6937
6938         port->port_source_caps = data->source_cap;
6939         port->port_sink_caps = data->sink_cap;
6940         typec_port_set_usb_power_delivery(p, NULL);
6941         port->selected_pd = pd;
6942         typec_port_set_usb_power_delivery(p, port->selected_pd);
6943 unlock:
6944         mutex_unlock(&port->lock);
6945         return ret;
6946 }
6947
6948 static const struct typec_operations tcpm_ops = {
6949         .try_role = tcpm_try_role,
6950         .dr_set = tcpm_dr_set,
6951         .pr_set = tcpm_pr_set,
6952         .vconn_set = tcpm_vconn_set,
6953         .port_type_set = tcpm_port_type_set,
6954         .pd_get = tcpm_pd_get,
6955         .pd_set = tcpm_pd_set
6956 };
6957
6958 void tcpm_tcpc_reset(struct tcpm_port *port)
6959 {
6960         mutex_lock(&port->lock);
6961         /* XXX: Maintain PD connection if possible? */
6962         tcpm_init(port);
6963         mutex_unlock(&port->lock);
6964 }
6965 EXPORT_SYMBOL_GPL(tcpm_tcpc_reset);
6966
6967 static void tcpm_port_unregister_pd(struct tcpm_port *port)
6968 {
6969         int i;
6970
6971         port->port_sink_caps = NULL;
6972         port->port_source_caps = NULL;
6973         for (i = 0; i < port->pd_count; i++) {
6974                 usb_power_delivery_unregister_capabilities(port->pd_list[i]->sink_cap);
6975                 usb_power_delivery_unregister_capabilities(port->pd_list[i]->source_cap);
6976                 devm_kfree(port->dev, port->pd_list[i]);
6977                 port->pd_list[i] = NULL;
6978                 usb_power_delivery_unregister(port->pds[i]);
6979                 port->pds[i] = NULL;
6980         }
6981 }
6982
6983 static int tcpm_port_register_pd(struct tcpm_port *port)
6984 {
6985         struct usb_power_delivery_desc desc = { port->typec_caps.pd_revision };
6986         struct usb_power_delivery_capabilities *cap;
6987         int ret, i;
6988
6989         if (!port->nr_src_pdo && !port->nr_snk_pdo)
6990                 return 0;
6991
6992         for (i = 0; i < port->pd_count; i++) {
6993                 port->pds[i] = usb_power_delivery_register(port->dev, &desc);
6994                 if (IS_ERR(port->pds[i])) {
6995                         ret = PTR_ERR(port->pds[i]);
6996                         goto err_unregister;
6997                 }
6998                 port->pd_list[i]->pd = port->pds[i];
6999
7000                 if (port->pd_list[i]->source_desc.pdo[0]) {
7001                         cap = usb_power_delivery_register_capabilities(port->pds[i],
7002                                                                 &port->pd_list[i]->source_desc);
7003                         if (IS_ERR(cap)) {
7004                                 ret = PTR_ERR(cap);
7005                                 goto err_unregister;
7006                         }
7007                         port->pd_list[i]->source_cap = cap;
7008                 }
7009
7010                 if (port->pd_list[i]->sink_desc.pdo[0]) {
7011                         cap = usb_power_delivery_register_capabilities(port->pds[i],
7012                                                                 &port->pd_list[i]->sink_desc);
7013                         if (IS_ERR(cap)) {
7014                                 ret = PTR_ERR(cap);
7015                                 goto err_unregister;
7016                         }
7017                         port->pd_list[i]->sink_cap = cap;
7018                 }
7019         }
7020
7021         port->port_source_caps = port->pd_list[0]->source_cap;
7022         port->port_sink_caps = port->pd_list[0]->sink_cap;
7023         port->selected_pd = port->pds[0];
7024         return 0;
7025
7026 err_unregister:
7027         tcpm_port_unregister_pd(port);
7028
7029         return ret;
7030 }
7031
7032 static int tcpm_fw_get_caps(struct tcpm_port *port, struct fwnode_handle *fwnode)
7033 {
7034         struct fwnode_handle *capabilities, *child, *caps = NULL;
7035         unsigned int nr_src_pdo, nr_snk_pdo;
7036         const char *opmode_str;
7037         u32 *src_pdo, *snk_pdo;
7038         u32 uw, frs_current;
7039         int ret = 0, i;
7040         int mode;
7041
7042         if (!fwnode)
7043                 return -EINVAL;
7044
7045         /*
7046          * This fwnode has a "compatible" property, but is never populated as a
7047          * struct device. Instead we simply parse it to read the properties.
7048          * This it breaks fw_devlink=on. To maintain backward compatibility
7049          * with existing DT files, we work around this by deleting any
7050          * fwnode_links to/from this fwnode.
7051          */
7052         fw_devlink_purge_absent_suppliers(fwnode);
7053
7054         ret = typec_get_fw_cap(&port->typec_caps, fwnode);
7055         if (ret < 0)
7056                 return ret;
7057
7058         mode = 0;
7059
7060         if (fwnode_property_read_bool(fwnode, "accessory-mode-audio"))
7061                 port->typec_caps.accessory[mode++] = TYPEC_ACCESSORY_AUDIO;
7062
7063         if (fwnode_property_read_bool(fwnode, "accessory-mode-debug"))
7064                 port->typec_caps.accessory[mode++] = TYPEC_ACCESSORY_DEBUG;
7065
7066         port->port_type = port->typec_caps.type;
7067         port->pd_supported = !fwnode_property_read_bool(fwnode, "pd-disable");
7068         port->slow_charger_loop = fwnode_property_read_bool(fwnode, "slow-charger-loop");
7069         port->self_powered = fwnode_property_read_bool(fwnode, "self-powered");
7070
7071         if (!port->pd_supported) {
7072                 ret = fwnode_property_read_string(fwnode, "typec-power-opmode", &opmode_str);
7073                 if (ret)
7074                         return ret;
7075                 ret = typec_find_pwr_opmode(opmode_str);
7076                 if (ret < 0)
7077                         return ret;
7078                 port->src_rp = tcpm_pwr_opmode_to_rp(ret);
7079                 return 0;
7080         }
7081
7082         /* The following code are applicable to pd-capable ports, i.e. pd_supported is true. */
7083
7084         /* FRS can only be supported by DRP ports */
7085         if (port->port_type == TYPEC_PORT_DRP) {
7086                 ret = fwnode_property_read_u32(fwnode, "new-source-frs-typec-current",
7087                                                &frs_current);
7088                 if (!ret && frs_current <= FRS_5V_3A)
7089                         port->new_source_frs_current = frs_current;
7090
7091                 if (ret)
7092                         ret = 0;
7093         }
7094
7095         /* For the backward compatibility, "capabilities" node is optional. */
7096         capabilities = fwnode_get_named_child_node(fwnode, "capabilities");
7097         if (!capabilities) {
7098                 port->pd_count = 1;
7099         } else {
7100                 fwnode_for_each_child_node(capabilities, child)
7101                         port->pd_count++;
7102
7103                 if (!port->pd_count) {
7104                         ret = -ENODATA;
7105                         goto put_capabilities;
7106                 }
7107         }
7108
7109         port->pds = devm_kcalloc(port->dev, port->pd_count, sizeof(struct usb_power_delivery *),
7110                                  GFP_KERNEL);
7111         if (!port->pds) {
7112                 ret = -ENOMEM;
7113                 goto put_capabilities;
7114         }
7115
7116         port->pd_list = devm_kcalloc(port->dev, port->pd_count, sizeof(struct pd_data *),
7117                                      GFP_KERNEL);
7118         if (!port->pd_list) {
7119                 ret = -ENOMEM;
7120                 goto put_capabilities;
7121         }
7122
7123         for (i = 0; i < port->pd_count; i++) {
7124                 port->pd_list[i] = devm_kzalloc(port->dev, sizeof(struct pd_data), GFP_KERNEL);
7125                 if (!port->pd_list[i]) {
7126                         ret = -ENOMEM;
7127                         goto put_capabilities;
7128                 }
7129
7130                 src_pdo = port->pd_list[i]->source_desc.pdo;
7131                 port->pd_list[i]->source_desc.role = TYPEC_SOURCE;
7132                 snk_pdo = port->pd_list[i]->sink_desc.pdo;
7133                 port->pd_list[i]->sink_desc.role = TYPEC_SINK;
7134
7135                 /* If "capabilities" is NULL, fall back to single pd cap population. */
7136                 if (!capabilities)
7137                         caps = fwnode;
7138                 else
7139                         caps = fwnode_get_next_child_node(capabilities, caps);
7140
7141                 if (port->port_type != TYPEC_PORT_SNK) {
7142                         ret = fwnode_property_count_u32(caps, "source-pdos");
7143                         if (ret == 0) {
7144                                 ret = -EINVAL;
7145                                 goto put_caps;
7146                         }
7147                         if (ret < 0)
7148                                 goto put_caps;
7149
7150                         nr_src_pdo = min(ret, PDO_MAX_OBJECTS);
7151                         ret = fwnode_property_read_u32_array(caps, "source-pdos", src_pdo,
7152                                                              nr_src_pdo);
7153                         if (ret)
7154                                 goto put_caps;
7155
7156                         ret = tcpm_validate_caps(port, src_pdo, nr_src_pdo);
7157                         if (ret)
7158                                 goto put_caps;
7159
7160                         if (i == 0) {
7161                                 port->nr_src_pdo = nr_src_pdo;
7162                                 memcpy_and_pad(port->src_pdo, sizeof(u32) * PDO_MAX_OBJECTS,
7163                                                port->pd_list[0]->source_desc.pdo,
7164                                                sizeof(u32) * nr_src_pdo,
7165                                                0);
7166                         }
7167                 }
7168
7169                 if (port->port_type != TYPEC_PORT_SRC) {
7170                         ret = fwnode_property_count_u32(caps, "sink-pdos");
7171                         if (ret == 0) {
7172                                 ret = -EINVAL;
7173                                 goto put_caps;
7174                         }
7175
7176                         if (ret < 0)
7177                                 goto put_caps;
7178
7179                         nr_snk_pdo = min(ret, PDO_MAX_OBJECTS);
7180                         ret = fwnode_property_read_u32_array(caps, "sink-pdos", snk_pdo,
7181                                                              nr_snk_pdo);
7182                         if (ret)
7183                                 goto put_caps;
7184
7185                         ret = tcpm_validate_caps(port, snk_pdo, nr_snk_pdo);
7186                         if (ret)
7187                                 goto put_caps;
7188
7189                         if (fwnode_property_read_u32(caps, "op-sink-microwatt", &uw) < 0) {
7190                                 ret = -EINVAL;
7191                                 goto put_caps;
7192                         }
7193
7194                         port->pd_list[i]->operating_snk_mw = uw / 1000;
7195
7196                         if (i == 0) {
7197                                 port->nr_snk_pdo = nr_snk_pdo;
7198                                 memcpy_and_pad(port->snk_pdo, sizeof(u32) * PDO_MAX_OBJECTS,
7199                                                port->pd_list[0]->sink_desc.pdo,
7200                                                sizeof(u32) * nr_snk_pdo,
7201                                                0);
7202                                 port->operating_snk_mw = port->pd_list[0]->operating_snk_mw;
7203                         }
7204                 }
7205         }
7206
7207 put_caps:
7208         if (caps != fwnode)
7209                 fwnode_handle_put(caps);
7210 put_capabilities:
7211         fwnode_handle_put(capabilities);
7212         return ret;
7213 }
7214
7215 static int tcpm_fw_get_snk_vdos(struct tcpm_port *port, struct fwnode_handle *fwnode)
7216 {
7217         int ret;
7218
7219         /* sink-vdos is optional */
7220         ret = fwnode_property_count_u32(fwnode, "sink-vdos");
7221         if (ret < 0)
7222                 return 0;
7223
7224         port->nr_snk_vdo = min(ret, VDO_MAX_OBJECTS);
7225         if (port->nr_snk_vdo) {
7226                 ret = fwnode_property_read_u32_array(fwnode, "sink-vdos",
7227                                                      port->snk_vdo,
7228                                                      port->nr_snk_vdo);
7229                 if (ret < 0)
7230                         return ret;
7231         }
7232
7233         /* If sink-vdos is found, sink-vdos-v1 is expected for backward compatibility. */
7234         if (port->nr_snk_vdo) {
7235                 ret = fwnode_property_count_u32(fwnode, "sink-vdos-v1");
7236                 if (ret < 0)
7237                         return ret;
7238                 else if (ret == 0)
7239                         return -ENODATA;
7240
7241                 port->nr_snk_vdo_v1 = min(ret, VDO_MAX_OBJECTS);
7242                 ret = fwnode_property_read_u32_array(fwnode, "sink-vdos-v1",
7243                                                      port->snk_vdo_v1,
7244                                                      port->nr_snk_vdo_v1);
7245                 if (ret < 0)
7246                         return ret;
7247         }
7248
7249         return 0;
7250 }
7251
7252 /* Power Supply access to expose source power information */
7253 enum tcpm_psy_online_states {
7254         TCPM_PSY_OFFLINE = 0,
7255         TCPM_PSY_FIXED_ONLINE,
7256         TCPM_PSY_PROG_ONLINE,
7257 };
7258
7259 static enum power_supply_property tcpm_psy_props[] = {
7260         POWER_SUPPLY_PROP_USB_TYPE,
7261         POWER_SUPPLY_PROP_ONLINE,
7262         POWER_SUPPLY_PROP_VOLTAGE_MIN,
7263         POWER_SUPPLY_PROP_VOLTAGE_MAX,
7264         POWER_SUPPLY_PROP_VOLTAGE_NOW,
7265         POWER_SUPPLY_PROP_CURRENT_MAX,
7266         POWER_SUPPLY_PROP_CURRENT_NOW,
7267 };
7268
7269 static int tcpm_psy_get_online(struct tcpm_port *port,
7270                                union power_supply_propval *val)
7271 {
7272         if (port->vbus_charge) {
7273                 if (port->pps_data.active)
7274                         val->intval = TCPM_PSY_PROG_ONLINE;
7275                 else
7276                         val->intval = TCPM_PSY_FIXED_ONLINE;
7277         } else {
7278                 val->intval = TCPM_PSY_OFFLINE;
7279         }
7280
7281         return 0;
7282 }
7283
7284 static int tcpm_psy_get_voltage_min(struct tcpm_port *port,
7285                                     union power_supply_propval *val)
7286 {
7287         if (port->pps_data.active)
7288                 val->intval = port->pps_data.min_volt * 1000;
7289         else
7290                 val->intval = port->supply_voltage * 1000;
7291
7292         return 0;
7293 }
7294
7295 static int tcpm_psy_get_voltage_max(struct tcpm_port *port,
7296                                     union power_supply_propval *val)
7297 {
7298         if (port->pps_data.active)
7299                 val->intval = port->pps_data.max_volt * 1000;
7300         else
7301                 val->intval = port->supply_voltage * 1000;
7302
7303         return 0;
7304 }
7305
7306 static int tcpm_psy_get_voltage_now(struct tcpm_port *port,
7307                                     union power_supply_propval *val)
7308 {
7309         val->intval = port->supply_voltage * 1000;
7310
7311         return 0;
7312 }
7313
7314 static int tcpm_psy_get_current_max(struct tcpm_port *port,
7315                                     union power_supply_propval *val)
7316 {
7317         if (port->pps_data.active)
7318                 val->intval = port->pps_data.max_curr * 1000;
7319         else
7320                 val->intval = port->current_limit * 1000;
7321
7322         return 0;
7323 }
7324
7325 static int tcpm_psy_get_current_now(struct tcpm_port *port,
7326                                     union power_supply_propval *val)
7327 {
7328         val->intval = port->current_limit * 1000;
7329
7330         return 0;
7331 }
7332
7333 static int tcpm_psy_get_input_power_limit(struct tcpm_port *port,
7334                                           union power_supply_propval *val)
7335 {
7336         unsigned int src_mv, src_ma, max_src_uw = 0;
7337         unsigned int i, tmp;
7338
7339         for (i = 0; i < port->nr_source_caps; i++) {
7340                 u32 pdo = port->source_caps[i];
7341
7342                 if (pdo_type(pdo) == PDO_TYPE_FIXED) {
7343                         src_mv = pdo_fixed_voltage(pdo);
7344                         src_ma = pdo_max_current(pdo);
7345                         tmp = src_mv * src_ma;
7346                         max_src_uw = tmp > max_src_uw ? tmp : max_src_uw;
7347                 }
7348         }
7349
7350         val->intval = max_src_uw;
7351         return 0;
7352 }
7353
7354 static int tcpm_psy_get_prop(struct power_supply *psy,
7355                              enum power_supply_property psp,
7356                              union power_supply_propval *val)
7357 {
7358         struct tcpm_port *port = power_supply_get_drvdata(psy);
7359         int ret = 0;
7360
7361         switch (psp) {
7362         case POWER_SUPPLY_PROP_USB_TYPE:
7363                 val->intval = port->usb_type;
7364                 break;
7365         case POWER_SUPPLY_PROP_ONLINE:
7366                 ret = tcpm_psy_get_online(port, val);
7367                 break;
7368         case POWER_SUPPLY_PROP_VOLTAGE_MIN:
7369                 ret = tcpm_psy_get_voltage_min(port, val);
7370                 break;
7371         case POWER_SUPPLY_PROP_VOLTAGE_MAX:
7372                 ret = tcpm_psy_get_voltage_max(port, val);
7373                 break;
7374         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
7375                 ret = tcpm_psy_get_voltage_now(port, val);
7376                 break;
7377         case POWER_SUPPLY_PROP_CURRENT_MAX:
7378                 ret = tcpm_psy_get_current_max(port, val);
7379                 break;
7380         case POWER_SUPPLY_PROP_CURRENT_NOW:
7381                 ret = tcpm_psy_get_current_now(port, val);
7382                 break;
7383         case POWER_SUPPLY_PROP_INPUT_POWER_LIMIT:
7384                 tcpm_psy_get_input_power_limit(port, val);
7385                 break;
7386         default:
7387                 ret = -EINVAL;
7388                 break;
7389         }
7390
7391         return ret;
7392 }
7393
7394 static int tcpm_psy_set_online(struct tcpm_port *port,
7395                                const union power_supply_propval *val)
7396 {
7397         int ret;
7398
7399         switch (val->intval) {
7400         case TCPM_PSY_FIXED_ONLINE:
7401                 ret = tcpm_pps_activate(port, false);
7402                 break;
7403         case TCPM_PSY_PROG_ONLINE:
7404                 ret = tcpm_pps_activate(port, true);
7405                 break;
7406         default:
7407                 ret = -EINVAL;
7408                 break;
7409         }
7410
7411         return ret;
7412 }
7413
7414 static int tcpm_psy_set_prop(struct power_supply *psy,
7415                              enum power_supply_property psp,
7416                              const union power_supply_propval *val)
7417 {
7418         struct tcpm_port *port = power_supply_get_drvdata(psy);
7419         int ret;
7420
7421         /*
7422          * All the properties below are related to USB PD. The check needs to be
7423          * property specific when a non-pd related property is added.
7424          */
7425         if (!port->pd_supported)
7426                 return -EOPNOTSUPP;
7427
7428         switch (psp) {
7429         case POWER_SUPPLY_PROP_ONLINE:
7430                 ret = tcpm_psy_set_online(port, val);
7431                 break;
7432         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
7433                 ret = tcpm_pps_set_out_volt(port, val->intval / 1000);
7434                 break;
7435         case POWER_SUPPLY_PROP_CURRENT_NOW:
7436                 if (val->intval > port->pps_data.max_curr * 1000)
7437                         ret = -EINVAL;
7438                 else
7439                         ret = tcpm_pps_set_op_curr(port, val->intval / 1000);
7440                 break;
7441         default:
7442                 ret = -EINVAL;
7443                 break;
7444         }
7445         power_supply_changed(port->psy);
7446         return ret;
7447 }
7448
7449 static int tcpm_psy_prop_writeable(struct power_supply *psy,
7450                                    enum power_supply_property psp)
7451 {
7452         switch (psp) {
7453         case POWER_SUPPLY_PROP_ONLINE:
7454         case POWER_SUPPLY_PROP_VOLTAGE_NOW:
7455         case POWER_SUPPLY_PROP_CURRENT_NOW:
7456                 return 1;
7457         default:
7458                 return 0;
7459         }
7460 }
7461
7462 static enum power_supply_usb_type tcpm_psy_usb_types[] = {
7463         POWER_SUPPLY_USB_TYPE_C,
7464         POWER_SUPPLY_USB_TYPE_PD,
7465         POWER_SUPPLY_USB_TYPE_PD_PPS,
7466 };
7467
7468 static const char *tcpm_psy_name_prefix = "tcpm-source-psy-";
7469
7470 static int devm_tcpm_psy_register(struct tcpm_port *port)
7471 {
7472         struct power_supply_config psy_cfg = {};
7473         const char *port_dev_name = dev_name(port->dev);
7474         size_t psy_name_len = strlen(tcpm_psy_name_prefix) +
7475                                      strlen(port_dev_name) + 1;
7476         char *psy_name;
7477
7478         psy_cfg.drv_data = port;
7479         psy_cfg.fwnode = dev_fwnode(port->dev);
7480         psy_name = devm_kzalloc(port->dev, psy_name_len, GFP_KERNEL);
7481         if (!psy_name)
7482                 return -ENOMEM;
7483
7484         snprintf(psy_name, psy_name_len, "%s%s", tcpm_psy_name_prefix,
7485                  port_dev_name);
7486         port->psy_desc.name = psy_name;
7487         port->psy_desc.type = POWER_SUPPLY_TYPE_USB;
7488         port->psy_desc.usb_types = tcpm_psy_usb_types;
7489         port->psy_desc.num_usb_types = ARRAY_SIZE(tcpm_psy_usb_types);
7490         port->psy_desc.properties = tcpm_psy_props;
7491         port->psy_desc.num_properties = ARRAY_SIZE(tcpm_psy_props);
7492         port->psy_desc.get_property = tcpm_psy_get_prop;
7493         port->psy_desc.set_property = tcpm_psy_set_prop;
7494         port->psy_desc.property_is_writeable = tcpm_psy_prop_writeable;
7495
7496         port->usb_type = POWER_SUPPLY_USB_TYPE_C;
7497
7498         port->psy = devm_power_supply_register(port->dev, &port->psy_desc,
7499                                                &psy_cfg);
7500
7501         return PTR_ERR_OR_ZERO(port->psy);
7502 }
7503
7504 static enum hrtimer_restart state_machine_timer_handler(struct hrtimer *timer)
7505 {
7506         struct tcpm_port *port = container_of(timer, struct tcpm_port, state_machine_timer);
7507
7508         if (port->registered)
7509                 kthread_queue_work(port->wq, &port->state_machine);
7510         return HRTIMER_NORESTART;
7511 }
7512
7513 static enum hrtimer_restart vdm_state_machine_timer_handler(struct hrtimer *timer)
7514 {
7515         struct tcpm_port *port = container_of(timer, struct tcpm_port, vdm_state_machine_timer);
7516
7517         if (port->registered)
7518                 kthread_queue_work(port->wq, &port->vdm_state_machine);
7519         return HRTIMER_NORESTART;
7520 }
7521
7522 static enum hrtimer_restart enable_frs_timer_handler(struct hrtimer *timer)
7523 {
7524         struct tcpm_port *port = container_of(timer, struct tcpm_port, enable_frs_timer);
7525
7526         if (port->registered)
7527                 kthread_queue_work(port->wq, &port->enable_frs);
7528         return HRTIMER_NORESTART;
7529 }
7530
7531 static enum hrtimer_restart send_discover_timer_handler(struct hrtimer *timer)
7532 {
7533         struct tcpm_port *port = container_of(timer, struct tcpm_port, send_discover_timer);
7534
7535         if (port->registered)
7536                 kthread_queue_work(port->wq, &port->send_discover_work);
7537         return HRTIMER_NORESTART;
7538 }
7539
7540 struct tcpm_port *tcpm_register_port(struct device *dev, struct tcpc_dev *tcpc)
7541 {
7542         struct tcpm_port *port;
7543         int err;
7544
7545         if (!dev || !tcpc ||
7546             !tcpc->get_vbus || !tcpc->set_cc || !tcpc->get_cc ||
7547             !tcpc->set_polarity || !tcpc->set_vconn || !tcpc->set_vbus ||
7548             !tcpc->set_pd_rx || !tcpc->set_roles || !tcpc->pd_transmit)
7549                 return ERR_PTR(-EINVAL);
7550
7551         port = devm_kzalloc(dev, sizeof(*port), GFP_KERNEL);
7552         if (!port)
7553                 return ERR_PTR(-ENOMEM);
7554
7555         port->dev = dev;
7556         port->tcpc = tcpc;
7557
7558         mutex_init(&port->lock);
7559         mutex_init(&port->swap_lock);
7560
7561         port->wq = kthread_create_worker(0, dev_name(dev));
7562         if (IS_ERR(port->wq))
7563                 return ERR_CAST(port->wq);
7564         sched_set_fifo(port->wq->task);
7565
7566         kthread_init_work(&port->state_machine, tcpm_state_machine_work);
7567         kthread_init_work(&port->vdm_state_machine, vdm_state_machine_work);
7568         kthread_init_work(&port->event_work, tcpm_pd_event_handler);
7569         kthread_init_work(&port->enable_frs, tcpm_enable_frs_work);
7570         kthread_init_work(&port->send_discover_work, tcpm_send_discover_work);
7571         hrtimer_init(&port->state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7572         port->state_machine_timer.function = state_machine_timer_handler;
7573         hrtimer_init(&port->vdm_state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7574         port->vdm_state_machine_timer.function = vdm_state_machine_timer_handler;
7575         hrtimer_init(&port->enable_frs_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7576         port->enable_frs_timer.function = enable_frs_timer_handler;
7577         hrtimer_init(&port->send_discover_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7578         port->send_discover_timer.function = send_discover_timer_handler;
7579
7580         spin_lock_init(&port->pd_event_lock);
7581
7582         init_completion(&port->tx_complete);
7583         init_completion(&port->swap_complete);
7584         init_completion(&port->pps_complete);
7585         tcpm_debugfs_init(port);
7586
7587         err = tcpm_fw_get_caps(port, tcpc->fwnode);
7588         if (err < 0)
7589                 goto out_destroy_wq;
7590         err = tcpm_fw_get_snk_vdos(port, tcpc->fwnode);
7591         if (err < 0)
7592                 goto out_destroy_wq;
7593
7594         port->try_role = port->typec_caps.prefer_role;
7595
7596         port->typec_caps.revision = 0x0120;     /* Type-C spec release 1.2 */
7597         port->typec_caps.pd_revision = 0x0300;  /* USB-PD spec release 3.0 */
7598         port->typec_caps.svdm_version = SVDM_VER_2_0;
7599         port->typec_caps.driver_data = port;
7600         port->typec_caps.ops = &tcpm_ops;
7601         port->typec_caps.orientation_aware = 1;
7602
7603         port->partner_desc.identity = &port->partner_ident;
7604
7605         port->role_sw = usb_role_switch_get(port->dev);
7606         if (!port->role_sw)
7607                 port->role_sw = fwnode_usb_role_switch_get(tcpc->fwnode);
7608         if (IS_ERR(port->role_sw)) {
7609                 err = PTR_ERR(port->role_sw);
7610                 goto out_destroy_wq;
7611         }
7612
7613         err = devm_tcpm_psy_register(port);
7614         if (err)
7615                 goto out_role_sw_put;
7616         power_supply_changed(port->psy);
7617
7618         err = tcpm_port_register_pd(port);
7619         if (err)
7620                 goto out_role_sw_put;
7621
7622         if (port->pds)
7623                 port->typec_caps.pd = port->pds[0];
7624
7625         port->typec_port = typec_register_port(port->dev, &port->typec_caps);
7626         if (IS_ERR(port->typec_port)) {
7627                 err = PTR_ERR(port->typec_port);
7628                 goto out_unregister_pd;
7629         }
7630
7631         typec_port_register_altmodes(port->typec_port,
7632                                      &tcpm_altmode_ops, port,
7633                                      port->port_altmode, ALTMODE_DISCOVERY_MAX);
7634         typec_port_register_cable_ops(port->port_altmode, ARRAY_SIZE(port->port_altmode),
7635                                       &tcpm_cable_ops);
7636         port->registered = true;
7637
7638         mutex_lock(&port->lock);
7639         tcpm_init(port);
7640         mutex_unlock(&port->lock);
7641
7642         tcpm_log(port, "%s: registered", dev_name(dev));
7643         return port;
7644
7645 out_unregister_pd:
7646         tcpm_port_unregister_pd(port);
7647 out_role_sw_put:
7648         usb_role_switch_put(port->role_sw);
7649 out_destroy_wq:
7650         tcpm_debugfs_exit(port);
7651         kthread_destroy_worker(port->wq);
7652         return ERR_PTR(err);
7653 }
7654 EXPORT_SYMBOL_GPL(tcpm_register_port);
7655
7656 void tcpm_unregister_port(struct tcpm_port *port)
7657 {
7658         int i;
7659
7660         port->registered = false;
7661         kthread_destroy_worker(port->wq);
7662
7663         hrtimer_cancel(&port->send_discover_timer);
7664         hrtimer_cancel(&port->enable_frs_timer);
7665         hrtimer_cancel(&port->vdm_state_machine_timer);
7666         hrtimer_cancel(&port->state_machine_timer);
7667
7668         tcpm_reset_port(port);
7669
7670         tcpm_port_unregister_pd(port);
7671
7672         for (i = 0; i < ARRAY_SIZE(port->port_altmode); i++)
7673                 typec_unregister_altmode(port->port_altmode[i]);
7674         typec_unregister_port(port->typec_port);
7675         usb_role_switch_put(port->role_sw);
7676         tcpm_debugfs_exit(port);
7677 }
7678 EXPORT_SYMBOL_GPL(tcpm_unregister_port);
7679
7680 MODULE_AUTHOR("Guenter Roeck <groeck@chromium.org>");
7681 MODULE_DESCRIPTION("USB Type-C Port Manager");
7682 MODULE_LICENSE("GPL");