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