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 
tcpm_default_state(struct tcpm_port * port)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 
tcpm_port_is_disconnected(struct tcpm_port * port)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 
tcpm_log_full(struct tcpm_port * port)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)
_tcpm_log(struct tcpm_port * port,const char * fmt,va_list args)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)
tcpm_log(struct tcpm_port * port,const char * fmt,...)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)
tcpm_log_force(struct tcpm_port * port,const char * fmt,...)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 
tcpm_log_source_caps(struct tcpm_port * port)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 
tcpm_debug_show(struct seq_file * s,void * v)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 
tcpm_debugfs_init(struct tcpm_port * port)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 
tcpm_debugfs_exit(struct tcpm_port * port)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)
tcpm_log(const struct tcpm_port * port,const char * fmt,...)846 static void tcpm_log(const struct tcpm_port *port, const char *fmt, ...) { }
847 __printf(2, 3)
tcpm_log_force(struct tcpm_port * port,const char * fmt,...)848 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...) { }
tcpm_log_source_caps(struct tcpm_port * port)849 static void tcpm_log_source_caps(struct tcpm_port *port) { }
tcpm_debugfs_init(const struct tcpm_port * port)850 static void tcpm_debugfs_init(const struct tcpm_port *port) { }
tcpm_debugfs_exit(const struct tcpm_port * port)851 static void tcpm_debugfs_exit(const struct tcpm_port *port) { }
852 
853 #endif
854 
tcpm_set_cc(struct tcpm_port * port,enum typec_cc_status cc)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 
tcpm_enable_auto_vbus_discharge(struct tcpm_port * port,bool enable)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 
tcpm_apply_rc(struct tcpm_port * port)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  */
tcpm_rp_cc(struct tcpm_port * port)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 
tcpm_ams_finish(struct tcpm_port * port)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 
tcpm_pd_transmit(struct tcpm_port * port,enum tcpm_transmit_type tx_sop_type,const struct pd_message * msg)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 
tcpm_pd_transmit_complete(struct tcpm_port * port,enum tcpm_transmit_status status)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 
tcpm_mux_set(struct tcpm_port * port,int state,enum usb_role usb_role,enum typec_orientation orientation)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 
tcpm_set_polarity(struct tcpm_port * port,enum typec_cc_polarity polarity)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 
tcpm_set_vconn(struct tcpm_port * port,bool enable)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 
tcpm_get_current_limit(struct tcpm_port * port)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 
tcpm_set_current_limit(struct tcpm_port * port,u32 max_ma,u32 mv)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 
tcpm_set_attached_state(struct tcpm_port * port,bool attached)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 
tcpm_set_roles(struct tcpm_port * port,bool attached,enum typec_role role,enum typec_data_role data)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 
tcpm_set_pwr_role(struct tcpm_port * port,enum typec_role role)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  */
tcpm_forge_legacy_pdo(struct tcpm_port * port,u32 pdo,enum typec_role role)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 
tcpm_pd_send_source_caps(struct tcpm_port * port)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 
tcpm_pd_send_sink_caps(struct tcpm_port * port)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 
mod_tcpm_delayed_work(struct tcpm_port * port,unsigned int delay_ms)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 
mod_vdm_delayed_work(struct tcpm_port * port,unsigned int delay_ms)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 
mod_enable_frs_delayed_work(struct tcpm_port * port,unsigned int delay_ms)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 
mod_send_discover_delayed_work(struct tcpm_port * port,unsigned int delay_ms)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 
tcpm_set_state(struct tcpm_port * port,enum tcpm_state state,unsigned int delay_ms)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 
tcpm_set_state_cond(struct tcpm_port * port,enum tcpm_state state,unsigned int delay_ms)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 
tcpm_queue_message(struct tcpm_port * port,enum pd_msg_request message)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 
tcpm_vdm_ams(struct tcpm_port * port)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 
tcpm_ams_interruptible(struct tcpm_port * port)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 
tcpm_ams_start(struct tcpm_port * port,enum tcpm_ams ams)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  */
tcpm_queue_vdm(struct tcpm_port * port,const u32 header,const u32 * data,int cnt,enum tcpm_transmit_type tx_sop_type)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 
tcpm_queue_vdm_unlocked(struct tcpm_port * port,const u32 header,const u32 * data,int cnt,enum tcpm_transmit_type tx_sop_type)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 
svdm_consume_identity(struct tcpm_port * port,const u32 * p,int cnt)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 
svdm_consume_identity_sop_prime(struct tcpm_port * port,const u32 * p,int cnt)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 
svdm_consume_svids(struct tcpm_port * port,const u32 * p,int cnt,enum tcpm_transmit_type rx_sop_type)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 
svdm_consume_modes(struct tcpm_port * port,const u32 * p,int cnt,enum tcpm_transmit_type rx_sop_type)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 
tcpm_register_partner_altmodes(struct tcpm_port * port)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 
tcpm_register_plug_altmodes(struct tcpm_port * port)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  */
tcpm_can_communicate_sop_prime(struct tcpm_port * port)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 
tcpm_attempt_vconn_swap_discovery(struct tcpm_port * port)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 
tcpm_cable_vdm_supported(struct tcpm_port * port)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 
tcpm_pd_svdm(struct tcpm_port * port,struct typec_altmode * adev,const u32 * p,int cnt,u32 * response,enum adev_actions * adev_action,enum tcpm_transmit_type rx_sop_type,enum tcpm_transmit_type * response_tx_sop_type)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 
tcpm_handle_vdm_request(struct tcpm_port * port,const __le32 * payload,int cnt,enum tcpm_transmit_type rx_sop_type)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 
tcpm_send_vdm(struct tcpm_port * port,u32 vid,int cmd,const u32 * data,int count,enum tcpm_transmit_type tx_sop_type)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 
vdm_ready_timeout(u32 vdm_hdr)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 
vdm_run_state_machine(struct tcpm_port * port)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 
vdm_state_machine_work(struct kthread_work * work)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 
tcpm_caps_err(struct tcpm_port * port,const u32 * pdo,unsigned int nr_pdo)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 
tcpm_validate_caps(struct tcpm_port * port,const u32 * pdo,unsigned int nr_pdo)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 
tcpm_altmode_enter(struct typec_altmode * altmode,u32 * vdo)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 
tcpm_altmode_exit(struct typec_altmode * altmode)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 
tcpm_altmode_vdm(struct typec_altmode * altmode,u32 header,const u32 * data,int count)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 
tcpm_cable_altmode_enter(struct typec_altmode * altmode,enum typec_plug_index sop,u32 * vdo)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 
tcpm_cable_altmode_exit(struct typec_altmode * altmode,enum typec_plug_index sop)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 
tcpm_cable_altmode_vdm(struct typec_altmode * altmode,enum typec_plug_index sop,u32 header,const u32 * data,int count)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  */
ready_state(struct tcpm_port * port)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 
tcpm_handle_alert(struct tcpm_port * port,const __le32 * payload,int cnt)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 
tcpm_set_auto_vbus_discharge_threshold(struct tcpm_port * port,enum typec_pwr_opmode mode,bool pps_active,u32 requested_vbus_voltage)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 
tcpm_pd_handle_state(struct tcpm_port * port,enum tcpm_state state,enum tcpm_ams ams,unsigned int delay_ms)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 
tcpm_pd_handle_msg(struct tcpm_port * port,enum pd_msg_request message,enum tcpm_ams ams)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 
tcpm_register_source_caps(struct tcpm_port * port)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 
tcpm_register_sink_caps(struct tcpm_port * port)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 
tcpm_pd_data_request(struct tcpm_port * port,const struct pd_message * msg,enum tcpm_transmit_type rx_sop_type)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 
tcpm_pps_complete(struct tcpm_port * port,int result)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 
tcpm_pd_ctrl_request(struct tcpm_port * port,const struct pd_message * msg,enum tcpm_transmit_type rx_sop_type)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 
tcpm_pd_ext_msg_request(struct tcpm_port * port,const struct pd_message * msg)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 
tcpm_pd_rx_handler(struct kthread_work * work)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 
tcpm_pd_receive(struct tcpm_port * port,const struct pd_message * msg,enum tcpm_transmit_type rx_sop_type)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 
tcpm_pd_send_control(struct tcpm_port * port,enum pd_ctrl_msg_type type,enum tcpm_transmit_type tx_sop_type)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  */
tcpm_send_queued_message(struct tcpm_port * port)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 
tcpm_pd_check_request(struct tcpm_port * port)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 
tcpm_pd_select_pdo(struct tcpm_port * port,int * sink_pdo,int * src_pdo)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 
tcpm_pd_select_pps_apdo(struct tcpm_port * port)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 
tcpm_pd_build_request(struct tcpm_port * port,u32 * rdo)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 
tcpm_pd_send_request(struct tcpm_port * port)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 
tcpm_pd_build_pps_request(struct tcpm_port * port,u32 * rdo)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 
tcpm_pd_send_pps_request(struct tcpm_port * port)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 
tcpm_set_vbus(struct tcpm_port * port,bool enable)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 
tcpm_set_charge(struct tcpm_port * port,bool charge)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 
tcpm_start_toggling(struct tcpm_port * port,enum typec_cc_status cc)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 
tcpm_init_vbus(struct tcpm_port * port)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 
tcpm_init_vconn(struct tcpm_port * port)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 
tcpm_typec_connect(struct tcpm_port * port)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 
tcpm_src_attach(struct tcpm_port * port)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 
tcpm_typec_disconnect(struct tcpm_port * port)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 
tcpm_unregister_altmodes(struct tcpm_port * port)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 
tcpm_set_partner_usb_comm_capable(struct tcpm_port * port,bool capable)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 
tcpm_reset_port(struct tcpm_port * port)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 
tcpm_detach(struct tcpm_port * port)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 
tcpm_src_detach(struct tcpm_port * port)4445 static void tcpm_src_detach(struct tcpm_port *port)
4446 {
4447 	tcpm_detach(port);
4448 }
4449 
tcpm_snk_attach(struct tcpm_port * port)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 
tcpm_snk_detach(struct tcpm_port * port)4479 static void tcpm_snk_detach(struct tcpm_port *port)
4480 {
4481 	tcpm_detach(port);
4482 }
4483 
tcpm_acc_attach(struct tcpm_port * port)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 
tcpm_acc_detach(struct tcpm_port * port)4505 static void tcpm_acc_detach(struct tcpm_port *port)
4506 {
4507 	tcpm_detach(port);
4508 }
4509 
hard_reset_state(struct tcpm_port * port)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 ||
4519 	    port->state == SNK_WAIT_CAPABILITIES_TIMEOUT)
4520 		return SNK_READY;
4521 	return SNK_UNATTACHED;
4522 }
4523 
unattached_state(struct tcpm_port * port)4524 static inline enum tcpm_state unattached_state(struct tcpm_port *port)
4525 {
4526 	if (port->port_type == TYPEC_PORT_DRP) {
4527 		if (port->pwr_role == TYPEC_SOURCE)
4528 			return SRC_UNATTACHED;
4529 		else
4530 			return SNK_UNATTACHED;
4531 	} else if (port->port_type == TYPEC_PORT_SRC) {
4532 		return SRC_UNATTACHED;
4533 	}
4534 
4535 	return SNK_UNATTACHED;
4536 }
4537 
tcpm_swap_complete(struct tcpm_port * port,int result)4538 static void tcpm_swap_complete(struct tcpm_port *port, int result)
4539 {
4540 	if (port->swap_pending) {
4541 		port->swap_status = result;
4542 		port->swap_pending = false;
4543 		port->non_pd_role_swap = false;
4544 		complete(&port->swap_complete);
4545 	}
4546 }
4547 
tcpm_get_pwr_opmode(enum typec_cc_status cc)4548 static enum typec_pwr_opmode tcpm_get_pwr_opmode(enum typec_cc_status cc)
4549 {
4550 	switch (cc) {
4551 	case TYPEC_CC_RP_1_5:
4552 		return TYPEC_PWR_MODE_1_5A;
4553 	case TYPEC_CC_RP_3_0:
4554 		return TYPEC_PWR_MODE_3_0A;
4555 	case TYPEC_CC_RP_DEF:
4556 	default:
4557 		return TYPEC_PWR_MODE_USB;
4558 	}
4559 }
4560 
tcpm_pwr_opmode_to_rp(enum typec_pwr_opmode opmode)4561 static enum typec_cc_status tcpm_pwr_opmode_to_rp(enum typec_pwr_opmode opmode)
4562 {
4563 	switch (opmode) {
4564 	case TYPEC_PWR_MODE_USB:
4565 		return TYPEC_CC_RP_DEF;
4566 	case TYPEC_PWR_MODE_1_5A:
4567 		return TYPEC_CC_RP_1_5;
4568 	case TYPEC_PWR_MODE_3_0A:
4569 	case TYPEC_PWR_MODE_PD:
4570 	default:
4571 		return TYPEC_CC_RP_3_0;
4572 	}
4573 }
4574 
tcpm_set_initial_svdm_version(struct tcpm_port * port)4575 static void tcpm_set_initial_svdm_version(struct tcpm_port *port)
4576 {
4577 	if (!port->partner)
4578 		return;
4579 
4580 	switch (port->negotiated_rev) {
4581 	case PD_REV30:
4582 		break;
4583 	/*
4584 	 * 6.4.4.2.3 Structured VDM Version
4585 	 * 2.0 states "At this time, there is only one version (1.0) defined.
4586 	 * This field Shall be set to zero to indicate Version 1.0."
4587 	 * 3.0 states "This field Shall be set to 01b to indicate Version 2.0."
4588 	 * To ensure that we follow the Power Delivery revision we are currently
4589 	 * operating on, downgrade the SVDM version to the highest one supported
4590 	 * by the Power Delivery revision.
4591 	 */
4592 	case PD_REV20:
4593 		typec_partner_set_svdm_version(port->partner, SVDM_VER_1_0);
4594 		break;
4595 	default:
4596 		typec_partner_set_svdm_version(port->partner, SVDM_VER_1_0);
4597 		break;
4598 	}
4599 }
4600 
run_state_machine(struct tcpm_port * port)4601 static void run_state_machine(struct tcpm_port *port)
4602 {
4603 	int ret;
4604 	enum typec_pwr_opmode opmode;
4605 	unsigned int msecs;
4606 	enum tcpm_state upcoming_state;
4607 
4608 	if (port->tcpc->check_contaminant && port->state != CHECK_CONTAMINANT)
4609 		port->potential_contaminant = ((port->enter_state == SRC_ATTACH_WAIT &&
4610 						port->state == SRC_UNATTACHED) ||
4611 					       (port->enter_state == SNK_ATTACH_WAIT &&
4612 						port->state == SNK_UNATTACHED) ||
4613 					       (port->enter_state == SNK_DEBOUNCED &&
4614 						port->state == SNK_UNATTACHED));
4615 
4616 	port->enter_state = port->state;
4617 	switch (port->state) {
4618 	case TOGGLING:
4619 		break;
4620 	case CHECK_CONTAMINANT:
4621 		port->tcpc->check_contaminant(port->tcpc);
4622 		break;
4623 	/* SRC states */
4624 	case SRC_UNATTACHED:
4625 		if (!port->non_pd_role_swap)
4626 			tcpm_swap_complete(port, -ENOTCONN);
4627 		tcpm_src_detach(port);
4628 		if (port->potential_contaminant) {
4629 			tcpm_set_state(port, CHECK_CONTAMINANT, 0);
4630 			break;
4631 		}
4632 		if (tcpm_start_toggling(port, tcpm_rp_cc(port))) {
4633 			tcpm_set_state(port, TOGGLING, 0);
4634 			break;
4635 		}
4636 		tcpm_set_cc(port, tcpm_rp_cc(port));
4637 		if (port->port_type == TYPEC_PORT_DRP)
4638 			tcpm_set_state(port, SNK_UNATTACHED, PD_T_DRP_SNK);
4639 		break;
4640 	case SRC_ATTACH_WAIT:
4641 		if (tcpm_port_is_debug(port))
4642 			tcpm_set_state(port, DEBUG_ACC_ATTACHED,
4643 				       PD_T_CC_DEBOUNCE);
4644 		else if (tcpm_port_is_audio(port))
4645 			tcpm_set_state(port, AUDIO_ACC_ATTACHED,
4646 				       PD_T_CC_DEBOUNCE);
4647 		else if (tcpm_port_is_source(port) && port->vbus_vsafe0v)
4648 			tcpm_set_state(port,
4649 				       tcpm_try_snk(port) ? SNK_TRY
4650 							  : SRC_ATTACHED,
4651 				       PD_T_CC_DEBOUNCE);
4652 		break;
4653 
4654 	case SNK_TRY:
4655 		port->try_snk_count++;
4656 		/*
4657 		 * Requirements:
4658 		 * - Do not drive vconn or vbus
4659 		 * - Terminate CC pins (both) to Rd
4660 		 * Action:
4661 		 * - Wait for tDRPTry (PD_T_DRP_TRY).
4662 		 *   Until then, ignore any state changes.
4663 		 */
4664 		tcpm_set_cc(port, TYPEC_CC_RD);
4665 		tcpm_set_state(port, SNK_TRY_WAIT, PD_T_DRP_TRY);
4666 		break;
4667 	case SNK_TRY_WAIT:
4668 		if (tcpm_port_is_sink(port)) {
4669 			tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE, 0);
4670 		} else {
4671 			tcpm_set_state(port, SRC_TRYWAIT, 0);
4672 			port->max_wait = 0;
4673 		}
4674 		break;
4675 	case SNK_TRY_WAIT_DEBOUNCE:
4676 		tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS,
4677 			       PD_T_TRY_CC_DEBOUNCE);
4678 		break;
4679 	case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
4680 		if (port->vbus_present && tcpm_port_is_sink(port))
4681 			tcpm_set_state(port, SNK_ATTACHED, 0);
4682 		else
4683 			port->max_wait = 0;
4684 		break;
4685 	case SRC_TRYWAIT:
4686 		tcpm_set_cc(port, tcpm_rp_cc(port));
4687 		if (port->max_wait == 0) {
4688 			port->max_wait = jiffies +
4689 					 msecs_to_jiffies(PD_T_DRP_TRY);
4690 			tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
4691 				       PD_T_DRP_TRY);
4692 		} else {
4693 			if (time_is_after_jiffies(port->max_wait))
4694 				tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
4695 					       jiffies_to_msecs(port->max_wait -
4696 								jiffies));
4697 			else
4698 				tcpm_set_state(port, SNK_UNATTACHED, 0);
4699 		}
4700 		break;
4701 	case SRC_TRYWAIT_DEBOUNCE:
4702 		tcpm_set_state(port, SRC_ATTACHED, PD_T_CC_DEBOUNCE);
4703 		break;
4704 	case SRC_TRYWAIT_UNATTACHED:
4705 		tcpm_set_state(port, SNK_UNATTACHED, 0);
4706 		break;
4707 
4708 	case SRC_ATTACHED:
4709 		ret = tcpm_src_attach(port);
4710 		tcpm_set_state(port, SRC_UNATTACHED,
4711 			       ret < 0 ? 0 : PD_T_PS_SOURCE_ON);
4712 		break;
4713 	case SRC_STARTUP:
4714 		opmode =  tcpm_get_pwr_opmode(tcpm_rp_cc(port));
4715 		typec_set_pwr_opmode(port->typec_port, opmode);
4716 		port->pwr_opmode = TYPEC_PWR_MODE_USB;
4717 		port->caps_count = 0;
4718 		port->negotiated_rev = PD_MAX_REV;
4719 		port->negotiated_rev_prime = PD_MAX_REV;
4720 		port->message_id = 0;
4721 		port->message_id_prime = 0;
4722 		port->rx_msgid = -1;
4723 		port->rx_msgid_prime = -1;
4724 		port->explicit_contract = false;
4725 		/* SNK -> SRC POWER/FAST_ROLE_SWAP finished */
4726 		if (port->ams == POWER_ROLE_SWAP ||
4727 		    port->ams == FAST_ROLE_SWAP)
4728 			tcpm_ams_finish(port);
4729 		if (!port->pd_supported) {
4730 			tcpm_set_state(port, SRC_READY, 0);
4731 			break;
4732 		}
4733 		port->upcoming_state = SRC_SEND_CAPABILITIES;
4734 		tcpm_ams_start(port, POWER_NEGOTIATION);
4735 		break;
4736 	case SRC_SEND_CAPABILITIES:
4737 		port->caps_count++;
4738 		if (port->caps_count > PD_N_CAPS_COUNT) {
4739 			tcpm_set_state(port, SRC_READY, 0);
4740 			break;
4741 		}
4742 		ret = tcpm_pd_send_source_caps(port);
4743 		if (ret < 0) {
4744 			if (tcpm_can_communicate_sop_prime(port) &&
4745 			    IS_ERR_OR_NULL(port->cable))
4746 				tcpm_set_state(port, SRC_VDM_IDENTITY_REQUEST, 0);
4747 			else
4748 				tcpm_set_state(port, SRC_SEND_CAPABILITIES,
4749 					       PD_T_SEND_SOURCE_CAP);
4750 		} else {
4751 			/*
4752 			 * Per standard, we should clear the reset counter here.
4753 			 * However, that can result in state machine hang-ups.
4754 			 * Reset it only in READY state to improve stability.
4755 			 */
4756 			/* port->hard_reset_count = 0; */
4757 			port->caps_count = 0;
4758 			port->pd_capable = true;
4759 			tcpm_set_state_cond(port, SRC_SEND_CAPABILITIES_TIMEOUT,
4760 					    PD_T_SEND_SOURCE_CAP);
4761 		}
4762 		break;
4763 	case SRC_SEND_CAPABILITIES_TIMEOUT:
4764 		/*
4765 		 * Error recovery for a PD_DATA_SOURCE_CAP reply timeout.
4766 		 *
4767 		 * PD 2.0 sinks are supposed to accept src-capabilities with a
4768 		 * 3.0 header and simply ignore any src PDOs which the sink does
4769 		 * not understand such as PPS but some 2.0 sinks instead ignore
4770 		 * the entire PD_DATA_SOURCE_CAP message, causing contract
4771 		 * negotiation to fail.
4772 		 *
4773 		 * After PD_N_HARD_RESET_COUNT hard-reset attempts, we try
4774 		 * sending src-capabilities with a lower PD revision to
4775 		 * make these broken sinks work.
4776 		 */
4777 		if (port->hard_reset_count < PD_N_HARD_RESET_COUNT) {
4778 			tcpm_set_state(port, HARD_RESET_SEND, 0);
4779 		} else if (port->negotiated_rev > PD_REV20) {
4780 			port->negotiated_rev--;
4781 			port->hard_reset_count = 0;
4782 			tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
4783 		} else {
4784 			tcpm_set_state(port, hard_reset_state(port), 0);
4785 		}
4786 		break;
4787 	case SRC_NEGOTIATE_CAPABILITIES:
4788 		ret = tcpm_pd_check_request(port);
4789 		if (ret < 0) {
4790 			tcpm_pd_send_control(port, PD_CTRL_REJECT, TCPC_TX_SOP);
4791 			if (!port->explicit_contract) {
4792 				tcpm_set_state(port,
4793 					       SRC_WAIT_NEW_CAPABILITIES, 0);
4794 			} else {
4795 				tcpm_set_state(port, SRC_READY, 0);
4796 			}
4797 		} else {
4798 			tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
4799 			tcpm_set_partner_usb_comm_capable(port,
4800 							  !!(port->sink_request & RDO_USB_COMM));
4801 			tcpm_set_state(port, SRC_TRANSITION_SUPPLY,
4802 				       PD_T_SRC_TRANSITION);
4803 		}
4804 		break;
4805 	case SRC_TRANSITION_SUPPLY:
4806 		/* XXX: regulator_set_voltage(vbus, ...) */
4807 		tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP);
4808 		port->explicit_contract = true;
4809 		typec_set_pwr_opmode(port->typec_port, TYPEC_PWR_MODE_PD);
4810 		port->pwr_opmode = TYPEC_PWR_MODE_PD;
4811 		tcpm_set_state_cond(port, SRC_READY, 0);
4812 		break;
4813 	case SRC_READY:
4814 #if 1
4815 		port->hard_reset_count = 0;
4816 #endif
4817 		port->try_src_count = 0;
4818 
4819 		tcpm_swap_complete(port, 0);
4820 		tcpm_typec_connect(port);
4821 
4822 		if (port->ams != NONE_AMS)
4823 			tcpm_ams_finish(port);
4824 		if (port->next_ams != NONE_AMS) {
4825 			port->ams = port->next_ams;
4826 			port->next_ams = NONE_AMS;
4827 		}
4828 
4829 		/*
4830 		 * If previous AMS is interrupted, switch to the upcoming
4831 		 * state.
4832 		 */
4833 		if (port->upcoming_state != INVALID_STATE) {
4834 			upcoming_state = port->upcoming_state;
4835 			port->upcoming_state = INVALID_STATE;
4836 			tcpm_set_state(port, upcoming_state, 0);
4837 			break;
4838 		}
4839 
4840 		/*
4841 		 * 6.4.4.3.1 Discover Identity
4842 		 * "The Discover Identity Command Shall only be sent to SOP when there is an
4843 		 * Explicit Contract."
4844 		 *
4845 		 * Discover Identity on SOP' should be discovered prior to the
4846 		 * ready state, but if done after a Vconn Swap following Discover
4847 		 * Identity on SOP then the discovery process can be run here
4848 		 * as well.
4849 		 */
4850 		if (port->explicit_contract) {
4851 			if (port->send_discover_prime) {
4852 				port->tx_sop_type = TCPC_TX_SOP_PRIME;
4853 			} else {
4854 				port->tx_sop_type = TCPC_TX_SOP;
4855 				tcpm_set_initial_svdm_version(port);
4856 			}
4857 			mod_send_discover_delayed_work(port, 0);
4858 		} else {
4859 			port->send_discover = false;
4860 			port->send_discover_prime = false;
4861 		}
4862 
4863 		/*
4864 		 * 6.3.5
4865 		 * Sending ping messages is not necessary if
4866 		 * - the source operates at vSafe5V
4867 		 * or
4868 		 * - The system is not operating in PD mode
4869 		 * or
4870 		 * - Both partners are connected using a Type-C connector
4871 		 *
4872 		 * There is no actual need to send PD messages since the local
4873 		 * port type-c and the spec does not clearly say whether PD is
4874 		 * possible when type-c is connected to Type-A/B
4875 		 */
4876 		break;
4877 	case SRC_WAIT_NEW_CAPABILITIES:
4878 		/* Nothing to do... */
4879 		break;
4880 
4881 	/* SNK states */
4882 	case SNK_UNATTACHED:
4883 		if (!port->non_pd_role_swap)
4884 			tcpm_swap_complete(port, -ENOTCONN);
4885 		tcpm_pps_complete(port, -ENOTCONN);
4886 		tcpm_snk_detach(port);
4887 		if (port->potential_contaminant) {
4888 			tcpm_set_state(port, CHECK_CONTAMINANT, 0);
4889 			break;
4890 		}
4891 		if (tcpm_start_toggling(port, TYPEC_CC_RD)) {
4892 			tcpm_set_state(port, TOGGLING, 0);
4893 			break;
4894 		}
4895 		tcpm_set_cc(port, TYPEC_CC_RD);
4896 		if (port->port_type == TYPEC_PORT_DRP)
4897 			tcpm_set_state(port, SRC_UNATTACHED, PD_T_DRP_SRC);
4898 		break;
4899 	case SNK_ATTACH_WAIT:
4900 		if ((port->cc1 == TYPEC_CC_OPEN &&
4901 		     port->cc2 != TYPEC_CC_OPEN) ||
4902 		    (port->cc1 != TYPEC_CC_OPEN &&
4903 		     port->cc2 == TYPEC_CC_OPEN))
4904 			tcpm_set_state(port, SNK_DEBOUNCED,
4905 				       PD_T_CC_DEBOUNCE);
4906 		else if (tcpm_port_is_disconnected(port))
4907 			tcpm_set_state(port, SNK_UNATTACHED,
4908 				       PD_T_PD_DEBOUNCE);
4909 		break;
4910 	case SNK_DEBOUNCED:
4911 		if (tcpm_port_is_disconnected(port))
4912 			tcpm_set_state(port, SNK_UNATTACHED,
4913 				       PD_T_PD_DEBOUNCE);
4914 		else if (port->vbus_present)
4915 			tcpm_set_state(port,
4916 				       tcpm_try_src(port) ? SRC_TRY
4917 							  : SNK_ATTACHED,
4918 				       0);
4919 		break;
4920 	case SRC_TRY:
4921 		port->try_src_count++;
4922 		tcpm_set_cc(port, tcpm_rp_cc(port));
4923 		port->max_wait = 0;
4924 		tcpm_set_state(port, SRC_TRY_WAIT, 0);
4925 		break;
4926 	case SRC_TRY_WAIT:
4927 		if (port->max_wait == 0) {
4928 			port->max_wait = jiffies +
4929 					 msecs_to_jiffies(PD_T_DRP_TRY);
4930 			msecs = PD_T_DRP_TRY;
4931 		} else {
4932 			if (time_is_after_jiffies(port->max_wait))
4933 				msecs = jiffies_to_msecs(port->max_wait -
4934 							 jiffies);
4935 			else
4936 				msecs = 0;
4937 		}
4938 		tcpm_set_state(port, SNK_TRYWAIT, msecs);
4939 		break;
4940 	case SRC_TRY_DEBOUNCE:
4941 		tcpm_set_state(port, SRC_ATTACHED, PD_T_PD_DEBOUNCE);
4942 		break;
4943 	case SNK_TRYWAIT:
4944 		tcpm_set_cc(port, TYPEC_CC_RD);
4945 		tcpm_set_state(port, SNK_TRYWAIT_VBUS, PD_T_CC_DEBOUNCE);
4946 		break;
4947 	case SNK_TRYWAIT_VBUS:
4948 		/*
4949 		 * TCPM stays in this state indefinitely until VBUS
4950 		 * is detected as long as Rp is not detected for
4951 		 * more than a time period of tPDDebounce.
4952 		 */
4953 		if (port->vbus_present && tcpm_port_is_sink(port)) {
4954 			tcpm_set_state(port, SNK_ATTACHED, 0);
4955 			break;
4956 		}
4957 		if (!tcpm_port_is_sink(port))
4958 			tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
4959 		break;
4960 	case SNK_TRYWAIT_DEBOUNCE:
4961 		tcpm_set_state(port, SNK_UNATTACHED, PD_T_PD_DEBOUNCE);
4962 		break;
4963 	case SNK_ATTACHED:
4964 		ret = tcpm_snk_attach(port);
4965 		if (ret < 0)
4966 			tcpm_set_state(port, SNK_UNATTACHED, 0);
4967 		else
4968 			tcpm_set_state(port, SNK_STARTUP, 0);
4969 		break;
4970 	case SNK_STARTUP:
4971 		opmode =  tcpm_get_pwr_opmode(port->polarity ?
4972 					      port->cc2 : port->cc1);
4973 		typec_set_pwr_opmode(port->typec_port, opmode);
4974 		port->pwr_opmode = TYPEC_PWR_MODE_USB;
4975 		port->negotiated_rev = PD_MAX_REV;
4976 		port->negotiated_rev_prime = PD_MAX_REV;
4977 		port->message_id = 0;
4978 		port->message_id_prime = 0;
4979 		port->rx_msgid = -1;
4980 		port->rx_msgid_prime = -1;
4981 		port->explicit_contract = false;
4982 
4983 		if (port->ams == POWER_ROLE_SWAP ||
4984 		    port->ams == FAST_ROLE_SWAP)
4985 			/* SRC -> SNK POWER/FAST_ROLE_SWAP finished */
4986 			tcpm_ams_finish(port);
4987 
4988 		tcpm_set_state(port, SNK_DISCOVERY, 0);
4989 		break;
4990 	case SNK_DISCOVERY:
4991 		if (port->vbus_present) {
4992 			u32 current_lim = tcpm_get_current_limit(port);
4993 
4994 			if (port->slow_charger_loop && (current_lim > PD_P_SNK_STDBY_MW / 5))
4995 				current_lim = PD_P_SNK_STDBY_MW / 5;
4996 			tcpm_set_current_limit(port, current_lim, 5000);
4997 			/* Not sink vbus if operational current is 0mA */
4998 			tcpm_set_charge(port, !port->pd_supported ||
4999 					pdo_max_current(port->snk_pdo[0]));
5000 
5001 			if (!port->pd_supported)
5002 				tcpm_set_state(port, SNK_READY, 0);
5003 			else
5004 				tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
5005 			break;
5006 		}
5007 		/*
5008 		 * For DRP, timeouts differ. Also, handling is supposed to be
5009 		 * different and much more complex (dead battery detection;
5010 		 * see USB power delivery specification, section 8.3.3.6.1.5.1).
5011 		 */
5012 		tcpm_set_state(port, hard_reset_state(port),
5013 			       port->port_type == TYPEC_PORT_DRP ?
5014 					PD_T_DB_DETECT : PD_T_NO_RESPONSE);
5015 		break;
5016 	case SNK_DISCOVERY_DEBOUNCE:
5017 		tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE_DONE,
5018 			       PD_T_CC_DEBOUNCE);
5019 		break;
5020 	case SNK_DISCOVERY_DEBOUNCE_DONE:
5021 		if (!tcpm_port_is_disconnected(port) &&
5022 		    tcpm_port_is_sink(port) &&
5023 		    ktime_after(port->delayed_runtime, ktime_get())) {
5024 			tcpm_set_state(port, SNK_DISCOVERY,
5025 				       ktime_to_ms(ktime_sub(port->delayed_runtime, ktime_get())));
5026 			break;
5027 		}
5028 		tcpm_set_state(port, unattached_state(port), 0);
5029 		break;
5030 	case SNK_WAIT_CAPABILITIES:
5031 		ret = port->tcpc->set_pd_rx(port->tcpc, true);
5032 		if (ret < 0) {
5033 			tcpm_set_state(port, SNK_READY, 0);
5034 			break;
5035 		}
5036 		/*
5037 		 * If VBUS has never been low, and we time out waiting
5038 		 * for source cap, try a soft reset first, in case we
5039 		 * were already in a stable contract before this boot.
5040 		 * Do this only once.
5041 		 */
5042 		if (port->vbus_never_low) {
5043 			port->vbus_never_low = false;
5044 			tcpm_set_state(port, SNK_SOFT_RESET,
5045 				       PD_T_SINK_WAIT_CAP);
5046 		} else {
5047 			if (!port->self_powered)
5048 				upcoming_state = SNK_WAIT_CAPABILITIES_TIMEOUT;
5049 			else
5050 				upcoming_state = hard_reset_state(port);
5051 			tcpm_set_state(port, upcoming_state, PD_T_SINK_WAIT_CAP);
5052 		}
5053 		break;
5054 	case SNK_WAIT_CAPABILITIES_TIMEOUT:
5055 		/*
5056 		 * There are some USB PD sources in the field, which do not
5057 		 * properly implement the specification and fail to start
5058 		 * sending Source Capability messages after a soft reset. The
5059 		 * specification suggests to do a hard reset when no Source
5060 		 * capability message is received within PD_T_SINK_WAIT_CAP,
5061 		 * but that might effectively kil the machine's power source.
5062 		 *
5063 		 * This slightly diverges from the specification and tries to
5064 		 * recover from this by explicitly asking for the capabilities
5065 		 * using the Get_Source_Cap control message before falling back
5066 		 * to a hard reset. The control message should also be supported
5067 		 * and handled by all USB PD source and dual role devices
5068 		 * according to the specification.
5069 		 */
5070 		if (tcpm_pd_send_control(port, PD_CTRL_GET_SOURCE_CAP, TCPC_TX_SOP))
5071 			tcpm_set_state_cond(port, hard_reset_state(port), 0);
5072 		else
5073 			tcpm_set_state(port, hard_reset_state(port), PD_T_SINK_WAIT_CAP);
5074 		break;
5075 	case SNK_NEGOTIATE_CAPABILITIES:
5076 		port->pd_capable = true;
5077 		tcpm_set_partner_usb_comm_capable(port,
5078 						  !!(port->source_caps[0] & PDO_FIXED_USB_COMM));
5079 		port->hard_reset_count = 0;
5080 		ret = tcpm_pd_send_request(port);
5081 		if (ret < 0) {
5082 			/* Restore back to the original state */
5083 			tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
5084 							       port->pps_data.active,
5085 							       port->supply_voltage);
5086 			/* Let the Source send capabilities again. */
5087 			tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
5088 		} else {
5089 			tcpm_set_state_cond(port, hard_reset_state(port),
5090 					    PD_T_SENDER_RESPONSE);
5091 		}
5092 		break;
5093 	case SNK_NEGOTIATE_PPS_CAPABILITIES:
5094 		ret = tcpm_pd_send_pps_request(port);
5095 		if (ret < 0) {
5096 			/* Restore back to the original state */
5097 			tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
5098 							       port->pps_data.active,
5099 							       port->supply_voltage);
5100 			port->pps_status = ret;
5101 			/*
5102 			 * If this was called due to updates to sink
5103 			 * capabilities, and pps is no longer valid, we should
5104 			 * safely fall back to a standard PDO.
5105 			 */
5106 			if (port->update_sink_caps)
5107 				tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
5108 			else
5109 				tcpm_set_state(port, SNK_READY, 0);
5110 		} else {
5111 			tcpm_set_state_cond(port, hard_reset_state(port),
5112 					    PD_T_SENDER_RESPONSE);
5113 		}
5114 		break;
5115 	case SNK_TRANSITION_SINK:
5116 		/* From the USB PD spec:
5117 		 * "The Sink Shall transition to Sink Standby before a positive or
5118 		 * negative voltage transition of VBUS. During Sink Standby
5119 		 * the Sink Shall reduce its power draw to pSnkStdby."
5120 		 *
5121 		 * This is not applicable to PPS though as the port can continue
5122 		 * to draw negotiated power without switching to standby.
5123 		 */
5124 		if (port->supply_voltage != port->req_supply_voltage && !port->pps_data.active &&
5125 		    port->current_limit * port->supply_voltage / 1000 > PD_P_SNK_STDBY_MW) {
5126 			u32 stdby_ma = PD_P_SNK_STDBY_MW * 1000 / port->supply_voltage;
5127 
5128 			tcpm_log(port, "Setting standby current %u mV @ %u mA",
5129 				 port->supply_voltage, stdby_ma);
5130 			tcpm_set_current_limit(port, stdby_ma, port->supply_voltage);
5131 		}
5132 		fallthrough;
5133 	case SNK_TRANSITION_SINK_VBUS:
5134 		tcpm_set_state(port, hard_reset_state(port),
5135 			       PD_T_PS_TRANSITION);
5136 		break;
5137 	case SNK_READY:
5138 		port->try_snk_count = 0;
5139 		port->update_sink_caps = false;
5140 		if (port->explicit_contract) {
5141 			typec_set_pwr_opmode(port->typec_port,
5142 					     TYPEC_PWR_MODE_PD);
5143 			port->pwr_opmode = TYPEC_PWR_MODE_PD;
5144 		}
5145 
5146 		if (!port->pd_capable && port->slow_charger_loop)
5147 			tcpm_set_current_limit(port, tcpm_get_current_limit(port), 5000);
5148 		tcpm_swap_complete(port, 0);
5149 		tcpm_typec_connect(port);
5150 		if (port->pd_capable && port->source_caps[0] & PDO_FIXED_DUAL_ROLE)
5151 			mod_enable_frs_delayed_work(port, 0);
5152 		tcpm_pps_complete(port, port->pps_status);
5153 
5154 		if (port->ams != NONE_AMS)
5155 			tcpm_ams_finish(port);
5156 		if (port->next_ams != NONE_AMS) {
5157 			port->ams = port->next_ams;
5158 			port->next_ams = NONE_AMS;
5159 		}
5160 
5161 		/*
5162 		 * If previous AMS is interrupted, switch to the upcoming
5163 		 * state.
5164 		 */
5165 		if (port->upcoming_state != INVALID_STATE) {
5166 			upcoming_state = port->upcoming_state;
5167 			port->upcoming_state = INVALID_STATE;
5168 			tcpm_set_state(port, upcoming_state, 0);
5169 			break;
5170 		}
5171 
5172 		/*
5173 		 * 6.4.4.3.1 Discover Identity
5174 		 * "The Discover Identity Command Shall only be sent to SOP when there is an
5175 		 * Explicit Contract."
5176 		 *
5177 		 * Discover Identity on SOP' should be discovered prior to the
5178 		 * ready state, but if done after a Vconn Swap following Discover
5179 		 * Identity on SOP then the discovery process can be run here
5180 		 * as well.
5181 		 */
5182 		if (port->explicit_contract) {
5183 			if (port->send_discover_prime) {
5184 				port->tx_sop_type = TCPC_TX_SOP_PRIME;
5185 			} else {
5186 				port->tx_sop_type = TCPC_TX_SOP;
5187 				tcpm_set_initial_svdm_version(port);
5188 			}
5189 			mod_send_discover_delayed_work(port, 0);
5190 		} else {
5191 			port->send_discover = false;
5192 			port->send_discover_prime = false;
5193 		}
5194 
5195 		power_supply_changed(port->psy);
5196 		break;
5197 
5198 	/* Accessory states */
5199 	case ACC_UNATTACHED:
5200 		tcpm_acc_detach(port);
5201 		tcpm_set_state(port, SRC_UNATTACHED, 0);
5202 		break;
5203 	case DEBUG_ACC_ATTACHED:
5204 	case AUDIO_ACC_ATTACHED:
5205 		ret = tcpm_acc_attach(port);
5206 		if (ret < 0)
5207 			tcpm_set_state(port, ACC_UNATTACHED, 0);
5208 		break;
5209 	case AUDIO_ACC_DEBOUNCE:
5210 		tcpm_set_state(port, ACC_UNATTACHED, PD_T_CC_DEBOUNCE);
5211 		break;
5212 
5213 	/* Hard_Reset states */
5214 	case HARD_RESET_SEND:
5215 		if (port->ams != NONE_AMS)
5216 			tcpm_ams_finish(port);
5217 		if (!port->self_powered && port->port_type == TYPEC_PORT_SNK)
5218 			dev_err(port->dev, "Initiating hard-reset, which might result in machine power-loss.\n");
5219 		/*
5220 		 * State machine will be directed to HARD_RESET_START,
5221 		 * thus set upcoming_state to INVALID_STATE.
5222 		 */
5223 		port->upcoming_state = INVALID_STATE;
5224 		tcpm_ams_start(port, HARD_RESET);
5225 		break;
5226 	case HARD_RESET_START:
5227 		port->sink_cap_done = false;
5228 		if (port->tcpc->enable_frs)
5229 			port->tcpc->enable_frs(port->tcpc, false);
5230 		port->hard_reset_count++;
5231 		port->tcpc->set_pd_rx(port->tcpc, false);
5232 		tcpm_unregister_altmodes(port);
5233 		port->nr_sink_caps = 0;
5234 		port->send_discover = true;
5235 		port->send_discover_prime = false;
5236 		if (port->pwr_role == TYPEC_SOURCE)
5237 			tcpm_set_state(port, SRC_HARD_RESET_VBUS_OFF,
5238 				       PD_T_PS_HARD_RESET);
5239 		else
5240 			tcpm_set_state(port, SNK_HARD_RESET_SINK_OFF, 0);
5241 		break;
5242 	case SRC_HARD_RESET_VBUS_OFF:
5243 		/*
5244 		 * 7.1.5 Response to Hard Resets
5245 		 * Hard Reset Signaling indicates a communication failure has occurred and the
5246 		 * Source Shall stop driving VCONN, Shall remove Rp from the VCONN pin and Shall
5247 		 * drive VBUS to vSafe0V as shown in Figure 7-9.
5248 		 */
5249 		tcpm_set_vconn(port, false);
5250 		tcpm_set_vbus(port, false);
5251 		tcpm_set_roles(port, port->self_powered, TYPEC_SOURCE,
5252 			       tcpm_data_role_for_source(port));
5253 		/*
5254 		 * If tcpc fails to notify vbus off, TCPM will wait for PD_T_SAFE_0V +
5255 		 * PD_T_SRC_RECOVER before turning vbus back on.
5256 		 * From Table 7-12 Sequence Description for a Source Initiated Hard Reset:
5257 		 * 4. Policy Engine waits tPSHardReset after sending Hard Reset Signaling and then
5258 		 * tells the Device Policy Manager to instruct the power supply to perform a
5259 		 * Hard Reset. The transition to vSafe0V Shall occur within tSafe0V (t2).
5260 		 * 5. After tSrcRecover the Source applies power to VBUS in an attempt to
5261 		 * re-establish communication with the Sink and resume USB Default Operation.
5262 		 * The transition to vSafe5V Shall occur within tSrcTurnOn(t4).
5263 		 */
5264 		tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SAFE_0V + PD_T_SRC_RECOVER);
5265 		break;
5266 	case SRC_HARD_RESET_VBUS_ON:
5267 		tcpm_set_vconn(port, true);
5268 		tcpm_set_vbus(port, true);
5269 		if (port->ams == HARD_RESET)
5270 			tcpm_ams_finish(port);
5271 		if (port->pd_supported)
5272 			port->tcpc->set_pd_rx(port->tcpc, true);
5273 		tcpm_set_attached_state(port, true);
5274 		tcpm_set_state(port, SRC_UNATTACHED, PD_T_PS_SOURCE_ON);
5275 		break;
5276 	case SNK_HARD_RESET_SINK_OFF:
5277 		/* Do not discharge/disconnect during hard reseet */
5278 		tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
5279 		memset(&port->pps_data, 0, sizeof(port->pps_data));
5280 		tcpm_set_vconn(port, false);
5281 		if (port->pd_capable)
5282 			tcpm_set_charge(port, false);
5283 		tcpm_set_roles(port, port->self_powered, TYPEC_SINK,
5284 			       tcpm_data_role_for_sink(port));
5285 		/*
5286 		 * VBUS may or may not toggle, depending on the adapter.
5287 		 * If it doesn't toggle, transition to SNK_HARD_RESET_SINK_ON
5288 		 * directly after timeout.
5289 		 */
5290 		tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, PD_T_SAFE_0V);
5291 		break;
5292 	case SNK_HARD_RESET_WAIT_VBUS:
5293 		if (port->ams == HARD_RESET)
5294 			tcpm_ams_finish(port);
5295 		/* Assume we're disconnected if VBUS doesn't come back. */
5296 		tcpm_set_state(port, SNK_UNATTACHED,
5297 			       PD_T_SRC_RECOVER_MAX + PD_T_SRC_TURN_ON);
5298 		break;
5299 	case SNK_HARD_RESET_SINK_ON:
5300 		/* Note: There is no guarantee that VBUS is on in this state */
5301 		/*
5302 		 * XXX:
5303 		 * The specification suggests that dual mode ports in sink
5304 		 * mode should transition to state PE_SRC_Transition_to_default.
5305 		 * See USB power delivery specification chapter 8.3.3.6.1.3.
5306 		 * This would mean to
5307 		 * - turn off VCONN, reset power supply
5308 		 * - request hardware reset
5309 		 * - turn on VCONN
5310 		 * - Transition to state PE_Src_Startup
5311 		 * SNK only ports shall transition to state Snk_Startup
5312 		 * (see chapter 8.3.3.3.8).
5313 		 * Similar, dual-mode ports in source mode should transition
5314 		 * to PE_SNK_Transition_to_default.
5315 		 */
5316 		if (port->pd_capable) {
5317 			tcpm_set_current_limit(port,
5318 					       tcpm_get_current_limit(port),
5319 					       5000);
5320 			/* Not sink vbus if operational current is 0mA */
5321 			tcpm_set_charge(port, !!pdo_max_current(port->snk_pdo[0]));
5322 		}
5323 		if (port->ams == HARD_RESET)
5324 			tcpm_ams_finish(port);
5325 		tcpm_set_attached_state(port, true);
5326 		tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, VSAFE5V);
5327 		tcpm_set_state(port, SNK_STARTUP, 0);
5328 		break;
5329 
5330 	/* Soft_Reset states */
5331 	case SOFT_RESET:
5332 		port->message_id = 0;
5333 		port->rx_msgid = -1;
5334 		/* remove existing capabilities */
5335 		usb_power_delivery_unregister_capabilities(port->partner_source_caps);
5336 		port->partner_source_caps = NULL;
5337 		tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5338 		tcpm_ams_finish(port);
5339 		if (port->pwr_role == TYPEC_SOURCE) {
5340 			port->upcoming_state = SRC_SEND_CAPABILITIES;
5341 			tcpm_ams_start(port, POWER_NEGOTIATION);
5342 		} else {
5343 			tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
5344 		}
5345 		break;
5346 	case SRC_SOFT_RESET_WAIT_SNK_TX:
5347 	case SNK_SOFT_RESET:
5348 		if (port->ams != NONE_AMS)
5349 			tcpm_ams_finish(port);
5350 		port->upcoming_state = SOFT_RESET_SEND;
5351 		tcpm_ams_start(port, SOFT_RESET_AMS);
5352 		break;
5353 	case SOFT_RESET_SEND:
5354 		/*
5355 		 * Power Delivery 3.0 Section 6.3.13
5356 		 *
5357 		 * A Soft_Reset Message Shall be targeted at a specific entity
5358 		 * depending on the type of SOP* packet used.
5359 		 */
5360 		if (port->tx_sop_type == TCPC_TX_SOP_PRIME) {
5361 			port->message_id_prime = 0;
5362 			port->rx_msgid_prime = -1;
5363 			tcpm_pd_send_control(port, PD_CTRL_SOFT_RESET, TCPC_TX_SOP_PRIME);
5364 			tcpm_set_state_cond(port, ready_state(port), PD_T_SENDER_RESPONSE);
5365 		} else {
5366 			port->message_id = 0;
5367 			port->rx_msgid = -1;
5368 			/* remove existing capabilities */
5369 			usb_power_delivery_unregister_capabilities(port->partner_source_caps);
5370 			port->partner_source_caps = NULL;
5371 			if (tcpm_pd_send_control(port, PD_CTRL_SOFT_RESET, TCPC_TX_SOP))
5372 				tcpm_set_state_cond(port, hard_reset_state(port), 0);
5373 			else
5374 				tcpm_set_state_cond(port, hard_reset_state(port),
5375 						    PD_T_SENDER_RESPONSE);
5376 		}
5377 		break;
5378 
5379 	/* DR_Swap states */
5380 	case DR_SWAP_SEND:
5381 		tcpm_pd_send_control(port, PD_CTRL_DR_SWAP, TCPC_TX_SOP);
5382 		if (port->data_role == TYPEC_DEVICE || port->negotiated_rev > PD_REV20) {
5383 			port->send_discover = true;
5384 			port->send_discover_prime = false;
5385 		}
5386 		tcpm_set_state_cond(port, DR_SWAP_SEND_TIMEOUT,
5387 				    PD_T_SENDER_RESPONSE);
5388 		break;
5389 	case DR_SWAP_ACCEPT:
5390 		tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5391 		if (port->data_role == TYPEC_DEVICE || port->negotiated_rev > PD_REV20) {
5392 			port->send_discover = true;
5393 			port->send_discover_prime = false;
5394 		}
5395 		tcpm_set_state_cond(port, DR_SWAP_CHANGE_DR, 0);
5396 		break;
5397 	case DR_SWAP_SEND_TIMEOUT:
5398 		tcpm_swap_complete(port, -ETIMEDOUT);
5399 		port->send_discover = false;
5400 		port->send_discover_prime = false;
5401 		tcpm_ams_finish(port);
5402 		tcpm_set_state(port, ready_state(port), 0);
5403 		break;
5404 	case DR_SWAP_CHANGE_DR:
5405 		tcpm_unregister_altmodes(port);
5406 		if (port->data_role == TYPEC_HOST)
5407 			tcpm_set_roles(port, true, port->pwr_role,
5408 				       TYPEC_DEVICE);
5409 		else
5410 			tcpm_set_roles(port, true, port->pwr_role,
5411 				       TYPEC_HOST);
5412 		tcpm_ams_finish(port);
5413 		tcpm_set_state(port, ready_state(port), 0);
5414 		break;
5415 
5416 	case FR_SWAP_SEND:
5417 		if (tcpm_pd_send_control(port, PD_CTRL_FR_SWAP, TCPC_TX_SOP)) {
5418 			tcpm_set_state(port, ERROR_RECOVERY, 0);
5419 			break;
5420 		}
5421 		tcpm_set_state_cond(port, FR_SWAP_SEND_TIMEOUT, PD_T_SENDER_RESPONSE);
5422 		break;
5423 	case FR_SWAP_SEND_TIMEOUT:
5424 		tcpm_set_state(port, ERROR_RECOVERY, 0);
5425 		break;
5426 	case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5427 		tcpm_set_state(port, ERROR_RECOVERY, PD_T_PS_SOURCE_OFF);
5428 		break;
5429 	case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5430 		if (port->vbus_source)
5431 			tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
5432 		else
5433 			tcpm_set_state(port, ERROR_RECOVERY, PD_T_RECEIVER_RESPONSE);
5434 		break;
5435 	case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5436 		tcpm_set_pwr_role(port, TYPEC_SOURCE);
5437 		if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP)) {
5438 			tcpm_set_state(port, ERROR_RECOVERY, 0);
5439 			break;
5440 		}
5441 		tcpm_set_cc(port, tcpm_rp_cc(port));
5442 		tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
5443 		break;
5444 
5445 	/* PR_Swap states */
5446 	case PR_SWAP_ACCEPT:
5447 		tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5448 		tcpm_set_state(port, PR_SWAP_START, 0);
5449 		break;
5450 	case PR_SWAP_SEND:
5451 		tcpm_pd_send_control(port, PD_CTRL_PR_SWAP, TCPC_TX_SOP);
5452 		tcpm_set_state_cond(port, PR_SWAP_SEND_TIMEOUT,
5453 				    PD_T_SENDER_RESPONSE);
5454 		break;
5455 	case PR_SWAP_SEND_TIMEOUT:
5456 		tcpm_swap_complete(port, -ETIMEDOUT);
5457 		tcpm_set_state(port, ready_state(port), 0);
5458 		break;
5459 	case PR_SWAP_START:
5460 		tcpm_apply_rc(port);
5461 		if (port->pwr_role == TYPEC_SOURCE)
5462 			tcpm_set_state(port, PR_SWAP_SRC_SNK_TRANSITION_OFF,
5463 				       PD_T_SRC_TRANSITION);
5464 		else
5465 			tcpm_set_state(port, PR_SWAP_SNK_SRC_SINK_OFF, 0);
5466 		break;
5467 	case PR_SWAP_SRC_SNK_TRANSITION_OFF:
5468 		/*
5469 		 * Prevent vbus discharge circuit from turning on during PR_SWAP
5470 		 * as this is not a disconnect.
5471 		 */
5472 		tcpm_set_vbus(port, false);
5473 		port->explicit_contract = false;
5474 		/* allow time for Vbus discharge, must be < tSrcSwapStdby */
5475 		tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF,
5476 			       PD_T_SRCSWAPSTDBY);
5477 		break;
5478 	case PR_SWAP_SRC_SNK_SOURCE_OFF:
5479 		tcpm_set_cc(port, TYPEC_CC_RD);
5480 		/* allow CC debounce */
5481 		tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED,
5482 			       PD_T_CC_DEBOUNCE);
5483 		break;
5484 	case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
5485 		/*
5486 		 * USB-PD standard, 6.2.1.4, Port Power Role:
5487 		 * "During the Power Role Swap Sequence, for the initial Source
5488 		 * Port, the Port Power Role field shall be set to Sink in the
5489 		 * PS_RDY Message indicating that the initial Source’s power
5490 		 * supply is turned off"
5491 		 */
5492 		tcpm_set_pwr_role(port, TYPEC_SINK);
5493 		if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP)) {
5494 			tcpm_set_state(port, ERROR_RECOVERY, 0);
5495 			break;
5496 		}
5497 		tcpm_set_state(port, ERROR_RECOVERY, PD_T_PS_SOURCE_ON_PRS);
5498 		break;
5499 	case PR_SWAP_SRC_SNK_SINK_ON:
5500 		tcpm_enable_auto_vbus_discharge(port, true);
5501 		/* Set the vbus disconnect threshold for implicit contract */
5502 		tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, VSAFE5V);
5503 		tcpm_set_state(port, SNK_STARTUP, 0);
5504 		break;
5505 	case PR_SWAP_SNK_SRC_SINK_OFF:
5506 		/* will be source, remove existing capabilities */
5507 		usb_power_delivery_unregister_capabilities(port->partner_source_caps);
5508 		port->partner_source_caps = NULL;
5509 		/*
5510 		 * Prevent vbus discharge circuit from turning on during PR_SWAP
5511 		 * as this is not a disconnect.
5512 		 */
5513 		tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB,
5514 						       port->pps_data.active, 0);
5515 		tcpm_set_charge(port, false);
5516 		tcpm_set_state(port, hard_reset_state(port),
5517 			       PD_T_PS_SOURCE_OFF);
5518 		break;
5519 	case PR_SWAP_SNK_SRC_SOURCE_ON:
5520 		tcpm_enable_auto_vbus_discharge(port, true);
5521 		tcpm_set_cc(port, tcpm_rp_cc(port));
5522 		tcpm_set_vbus(port, true);
5523 		/*
5524 		 * allow time VBUS ramp-up, must be < tNewSrc
5525 		 * Also, this window overlaps with CC debounce as well.
5526 		 * So, Wait for the max of two which is PD_T_NEWSRC
5527 		 */
5528 		tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP,
5529 			       PD_T_NEWSRC);
5530 		break;
5531 	case PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP:
5532 		/*
5533 		 * USB PD standard, 6.2.1.4:
5534 		 * "Subsequent Messages initiated by the Policy Engine,
5535 		 * such as the PS_RDY Message sent to indicate that Vbus
5536 		 * is ready, will have the Port Power Role field set to
5537 		 * Source."
5538 		 */
5539 		tcpm_set_pwr_role(port, TYPEC_SOURCE);
5540 		tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP);
5541 		tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
5542 		break;
5543 
5544 	case VCONN_SWAP_ACCEPT:
5545 		tcpm_pd_send_control(port, PD_CTRL_ACCEPT, TCPC_TX_SOP);
5546 		tcpm_ams_finish(port);
5547 		tcpm_set_state(port, VCONN_SWAP_START, 0);
5548 		break;
5549 	case VCONN_SWAP_SEND:
5550 		tcpm_pd_send_control(port, PD_CTRL_VCONN_SWAP, TCPC_TX_SOP);
5551 		tcpm_set_state(port, VCONN_SWAP_SEND_TIMEOUT,
5552 			       PD_T_SENDER_RESPONSE);
5553 		break;
5554 	case VCONN_SWAP_SEND_TIMEOUT:
5555 		tcpm_swap_complete(port, -ETIMEDOUT);
5556 		tcpm_set_state(port, ready_state(port), 0);
5557 		break;
5558 	case VCONN_SWAP_START:
5559 		if (port->vconn_role == TYPEC_SOURCE)
5560 			tcpm_set_state(port, VCONN_SWAP_WAIT_FOR_VCONN, 0);
5561 		else
5562 			tcpm_set_state(port, VCONN_SWAP_TURN_ON_VCONN, 0);
5563 		break;
5564 	case VCONN_SWAP_WAIT_FOR_VCONN:
5565 		tcpm_set_state(port, hard_reset_state(port),
5566 			       PD_T_VCONN_SOURCE_ON);
5567 		break;
5568 	case VCONN_SWAP_TURN_ON_VCONN:
5569 		ret = tcpm_set_vconn(port, true);
5570 		tcpm_pd_send_control(port, PD_CTRL_PS_RDY, TCPC_TX_SOP);
5571 		/*
5572 		 * USB PD 3.0 Section 6.4.4.3.1
5573 		 *
5574 		 * Note that a Cable Plug or VPD will not be ready for PD
5575 		 * Communication until tVCONNStable after VCONN has been applied
5576 		 */
5577 		if (!ret)
5578 			tcpm_set_state(port, VCONN_SWAP_SEND_SOFT_RESET,
5579 				       PD_T_VCONN_STABLE);
5580 		else
5581 			tcpm_set_state(port, ready_state(port), 0);
5582 		break;
5583 	case VCONN_SWAP_TURN_OFF_VCONN:
5584 		tcpm_set_vconn(port, false);
5585 		tcpm_set_state(port, ready_state(port), 0);
5586 		break;
5587 	case VCONN_SWAP_SEND_SOFT_RESET:
5588 		tcpm_swap_complete(port, port->swap_status);
5589 		if (tcpm_can_communicate_sop_prime(port)) {
5590 			port->tx_sop_type = TCPC_TX_SOP_PRIME;
5591 			port->upcoming_state = SOFT_RESET_SEND;
5592 			tcpm_ams_start(port, SOFT_RESET_AMS);
5593 		} else {
5594 			tcpm_set_state(port, ready_state(port), 0);
5595 		}
5596 		break;
5597 
5598 	case DR_SWAP_CANCEL:
5599 	case PR_SWAP_CANCEL:
5600 	case VCONN_SWAP_CANCEL:
5601 		tcpm_swap_complete(port, port->swap_status);
5602 		if (port->pwr_role == TYPEC_SOURCE)
5603 			tcpm_set_state(port, SRC_READY, 0);
5604 		else
5605 			tcpm_set_state(port, SNK_READY, 0);
5606 		break;
5607 	case FR_SWAP_CANCEL:
5608 		if (port->pwr_role == TYPEC_SOURCE)
5609 			tcpm_set_state(port, SRC_READY, 0);
5610 		else
5611 			tcpm_set_state(port, SNK_READY, 0);
5612 		break;
5613 
5614 	case BIST_RX:
5615 		switch (BDO_MODE_MASK(port->bist_request)) {
5616 		case BDO_MODE_CARRIER2:
5617 			tcpm_pd_transmit(port, TCPC_TX_BIST_MODE_2, NULL);
5618 			tcpm_set_state(port, unattached_state(port),
5619 				       PD_T_BIST_CONT_MODE);
5620 			break;
5621 		case BDO_MODE_TESTDATA:
5622 			if (port->tcpc->set_bist_data) {
5623 				tcpm_log(port, "Enable BIST MODE TESTDATA");
5624 				port->tcpc->set_bist_data(port->tcpc, true);
5625 			}
5626 			break;
5627 		default:
5628 			break;
5629 		}
5630 		break;
5631 	case GET_STATUS_SEND:
5632 		tcpm_pd_send_control(port, PD_CTRL_GET_STATUS, TCPC_TX_SOP);
5633 		tcpm_set_state(port, GET_STATUS_SEND_TIMEOUT,
5634 			       PD_T_SENDER_RESPONSE);
5635 		break;
5636 	case GET_STATUS_SEND_TIMEOUT:
5637 		tcpm_set_state(port, ready_state(port), 0);
5638 		break;
5639 	case GET_PPS_STATUS_SEND:
5640 		tcpm_pd_send_control(port, PD_CTRL_GET_PPS_STATUS, TCPC_TX_SOP);
5641 		tcpm_set_state(port, GET_PPS_STATUS_SEND_TIMEOUT,
5642 			       PD_T_SENDER_RESPONSE);
5643 		break;
5644 	case GET_PPS_STATUS_SEND_TIMEOUT:
5645 		tcpm_set_state(port, ready_state(port), 0);
5646 		break;
5647 	case GET_SINK_CAP:
5648 		tcpm_pd_send_control(port, PD_CTRL_GET_SINK_CAP, TCPC_TX_SOP);
5649 		tcpm_set_state(port, GET_SINK_CAP_TIMEOUT, PD_T_SENDER_RESPONSE);
5650 		break;
5651 	case GET_SINK_CAP_TIMEOUT:
5652 		port->sink_cap_done = true;
5653 		tcpm_set_state(port, ready_state(port), 0);
5654 		break;
5655 	case ERROR_RECOVERY:
5656 		tcpm_swap_complete(port, -EPROTO);
5657 		tcpm_pps_complete(port, -EPROTO);
5658 		tcpm_set_state(port, PORT_RESET, 0);
5659 		break;
5660 	case PORT_RESET:
5661 		tcpm_reset_port(port);
5662 		if (port->self_powered)
5663 			tcpm_set_cc(port, TYPEC_CC_OPEN);
5664 		else
5665 			tcpm_set_cc(port, tcpm_default_state(port) == SNK_UNATTACHED ?
5666 				    TYPEC_CC_RD : tcpm_rp_cc(port));
5667 		tcpm_set_state(port, PORT_RESET_WAIT_OFF,
5668 			       PD_T_ERROR_RECOVERY);
5669 		break;
5670 	case PORT_RESET_WAIT_OFF:
5671 		tcpm_set_state(port,
5672 			       tcpm_default_state(port),
5673 			       port->vbus_present ? PD_T_PS_SOURCE_OFF : 0);
5674 		break;
5675 
5676 	/* AMS intermediate state */
5677 	case AMS_START:
5678 		if (port->upcoming_state == INVALID_STATE) {
5679 			tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
5680 				       SRC_READY : SNK_READY, 0);
5681 			break;
5682 		}
5683 
5684 		upcoming_state = port->upcoming_state;
5685 		port->upcoming_state = INVALID_STATE;
5686 		tcpm_set_state(port, upcoming_state, 0);
5687 		break;
5688 
5689 	/* Chunk state */
5690 	case CHUNK_NOT_SUPP:
5691 		tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP, TCPC_TX_SOP);
5692 		tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ? SRC_READY : SNK_READY, 0);
5693 		break;
5694 
5695 	/* Cable states */
5696 	case SRC_VDM_IDENTITY_REQUEST:
5697 		port->send_discover_prime = true;
5698 		port->tx_sop_type = TCPC_TX_SOP_PRIME;
5699 		mod_send_discover_delayed_work(port, 0);
5700 		port->upcoming_state = SRC_SEND_CAPABILITIES;
5701 		break;
5702 
5703 	default:
5704 		WARN(1, "Unexpected port state %d\n", port->state);
5705 		break;
5706 	}
5707 }
5708 
tcpm_state_machine_work(struct kthread_work * work)5709 static void tcpm_state_machine_work(struct kthread_work *work)
5710 {
5711 	struct tcpm_port *port = container_of(work, struct tcpm_port, state_machine);
5712 	enum tcpm_state prev_state;
5713 
5714 	mutex_lock(&port->lock);
5715 	port->state_machine_running = true;
5716 
5717 	if (port->queued_message && tcpm_send_queued_message(port))
5718 		goto done;
5719 
5720 	/* If we were queued due to a delayed state change, update it now */
5721 	if (port->delayed_state) {
5722 		tcpm_log(port, "state change %s -> %s [delayed %ld ms]",
5723 			 tcpm_states[port->state],
5724 			 tcpm_states[port->delayed_state], port->delay_ms);
5725 		port->prev_state = port->state;
5726 		port->state = port->delayed_state;
5727 		port->delayed_state = INVALID_STATE;
5728 	}
5729 
5730 	/*
5731 	 * Continue running as long as we have (non-delayed) state changes
5732 	 * to make.
5733 	 */
5734 	do {
5735 		prev_state = port->state;
5736 		run_state_machine(port);
5737 		if (port->queued_message)
5738 			tcpm_send_queued_message(port);
5739 	} while (port->state != prev_state && !port->delayed_state);
5740 
5741 done:
5742 	port->state_machine_running = false;
5743 	mutex_unlock(&port->lock);
5744 }
5745 
_tcpm_cc_change(struct tcpm_port * port,enum typec_cc_status cc1,enum typec_cc_status cc2)5746 static void _tcpm_cc_change(struct tcpm_port *port, enum typec_cc_status cc1,
5747 			    enum typec_cc_status cc2)
5748 {
5749 	enum typec_cc_status old_cc1, old_cc2;
5750 	enum tcpm_state new_state;
5751 
5752 	old_cc1 = port->cc1;
5753 	old_cc2 = port->cc2;
5754 	port->cc1 = cc1;
5755 	port->cc2 = cc2;
5756 
5757 	tcpm_log_force(port,
5758 		       "CC1: %u -> %u, CC2: %u -> %u [state %s, polarity %d, %s]",
5759 		       old_cc1, cc1, old_cc2, cc2, tcpm_states[port->state],
5760 		       port->polarity,
5761 		       tcpm_port_is_disconnected(port) ? "disconnected"
5762 						       : "connected");
5763 
5764 	switch (port->state) {
5765 	case TOGGLING:
5766 		if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
5767 		    tcpm_port_is_source(port))
5768 			tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
5769 		else if (tcpm_port_is_sink(port))
5770 			tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
5771 		break;
5772 	case CHECK_CONTAMINANT:
5773 		/* Wait for Toggling to be resumed */
5774 		break;
5775 	case SRC_UNATTACHED:
5776 	case ACC_UNATTACHED:
5777 		if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
5778 		    tcpm_port_is_source(port))
5779 			tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
5780 		break;
5781 	case SRC_ATTACH_WAIT:
5782 		if (tcpm_port_is_disconnected(port) ||
5783 		    tcpm_port_is_audio_detached(port))
5784 			tcpm_set_state(port, SRC_UNATTACHED, 0);
5785 		else if (cc1 != old_cc1 || cc2 != old_cc2)
5786 			tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
5787 		break;
5788 	case SRC_ATTACHED:
5789 	case SRC_STARTUP:
5790 	case SRC_SEND_CAPABILITIES:
5791 	case SRC_READY:
5792 		if (tcpm_port_is_disconnected(port) ||
5793 		    !tcpm_port_is_source(port)) {
5794 			if (port->port_type == TYPEC_PORT_SRC)
5795 				tcpm_set_state(port, SRC_UNATTACHED, tcpm_wait_for_discharge(port));
5796 			else
5797 				tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
5798 		}
5799 		break;
5800 	case SNK_UNATTACHED:
5801 		if (tcpm_port_is_sink(port))
5802 			tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
5803 		break;
5804 	case SNK_ATTACH_WAIT:
5805 		if ((port->cc1 == TYPEC_CC_OPEN &&
5806 		     port->cc2 != TYPEC_CC_OPEN) ||
5807 		    (port->cc1 != TYPEC_CC_OPEN &&
5808 		     port->cc2 == TYPEC_CC_OPEN))
5809 			new_state = SNK_DEBOUNCED;
5810 		else if (tcpm_port_is_disconnected(port))
5811 			new_state = SNK_UNATTACHED;
5812 		else
5813 			break;
5814 		if (new_state != port->delayed_state)
5815 			tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
5816 		break;
5817 	case SNK_DEBOUNCED:
5818 		if (tcpm_port_is_disconnected(port))
5819 			new_state = SNK_UNATTACHED;
5820 		else if (port->vbus_present)
5821 			new_state = tcpm_try_src(port) ? SRC_TRY : SNK_ATTACHED;
5822 		else
5823 			new_state = SNK_UNATTACHED;
5824 		if (new_state != port->delayed_state)
5825 			tcpm_set_state(port, SNK_DEBOUNCED, 0);
5826 		break;
5827 	case SNK_READY:
5828 		/*
5829 		 * EXIT condition is based primarily on vbus disconnect and CC is secondary.
5830 		 * "A port that has entered into USB PD communications with the Source and
5831 		 * has seen the CC voltage exceed vRd-USB may monitor the CC pin to detect
5832 		 * cable disconnect in addition to monitoring VBUS.
5833 		 *
5834 		 * A port that is monitoring the CC voltage for disconnect (but is not in
5835 		 * the process of a USB PD PR_Swap or USB PD FR_Swap) shall transition to
5836 		 * Unattached.SNK within tSinkDisconnect after the CC voltage remains below
5837 		 * vRd-USB for tPDDebounce."
5838 		 *
5839 		 * When set_auto_vbus_discharge_threshold is enabled, CC pins go
5840 		 * away before vbus decays to disconnect threshold. Allow
5841 		 * disconnect to be driven by vbus disconnect when auto vbus
5842 		 * discharge is enabled.
5843 		 */
5844 		if (!port->auto_vbus_discharge_enabled && tcpm_port_is_disconnected(port))
5845 			tcpm_set_state(port, unattached_state(port), 0);
5846 		else if (!port->pd_capable &&
5847 			 (cc1 != old_cc1 || cc2 != old_cc2))
5848 			tcpm_set_current_limit(port,
5849 					       tcpm_get_current_limit(port),
5850 					       5000);
5851 		break;
5852 
5853 	case AUDIO_ACC_ATTACHED:
5854 		if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
5855 			tcpm_set_state(port, AUDIO_ACC_DEBOUNCE, 0);
5856 		break;
5857 	case AUDIO_ACC_DEBOUNCE:
5858 		if (tcpm_port_is_audio(port))
5859 			tcpm_set_state(port, AUDIO_ACC_ATTACHED, 0);
5860 		break;
5861 
5862 	case DEBUG_ACC_ATTACHED:
5863 		if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
5864 			tcpm_set_state(port, ACC_UNATTACHED, 0);
5865 		break;
5866 
5867 	case SNK_TRY:
5868 		/* Do nothing, waiting for timeout */
5869 		break;
5870 
5871 	case SNK_DISCOVERY:
5872 		/* CC line is unstable, wait for debounce */
5873 		if (tcpm_port_is_disconnected(port))
5874 			tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE, 0);
5875 		break;
5876 	case SNK_DISCOVERY_DEBOUNCE:
5877 		break;
5878 
5879 	case SRC_TRYWAIT:
5880 		/* Hand over to state machine if needed */
5881 		if (!port->vbus_present && tcpm_port_is_source(port))
5882 			tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
5883 		break;
5884 	case SRC_TRYWAIT_DEBOUNCE:
5885 		if (port->vbus_present || !tcpm_port_is_source(port))
5886 			tcpm_set_state(port, SRC_TRYWAIT, 0);
5887 		break;
5888 	case SNK_TRY_WAIT_DEBOUNCE:
5889 		if (!tcpm_port_is_sink(port)) {
5890 			port->max_wait = 0;
5891 			tcpm_set_state(port, SRC_TRYWAIT, 0);
5892 		}
5893 		break;
5894 	case SRC_TRY_WAIT:
5895 		if (tcpm_port_is_source(port))
5896 			tcpm_set_state(port, SRC_TRY_DEBOUNCE, 0);
5897 		break;
5898 	case SRC_TRY_DEBOUNCE:
5899 		tcpm_set_state(port, SRC_TRY_WAIT, 0);
5900 		break;
5901 	case SNK_TRYWAIT_DEBOUNCE:
5902 		if (tcpm_port_is_sink(port))
5903 			tcpm_set_state(port, SNK_TRYWAIT_VBUS, 0);
5904 		break;
5905 	case SNK_TRYWAIT_VBUS:
5906 		if (!tcpm_port_is_sink(port))
5907 			tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
5908 		break;
5909 	case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
5910 		if (!tcpm_port_is_sink(port))
5911 			tcpm_set_state(port, SRC_TRYWAIT, PD_T_TRY_CC_DEBOUNCE);
5912 		else
5913 			tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS, 0);
5914 		break;
5915 	case SNK_TRYWAIT:
5916 		/* Do nothing, waiting for tCCDebounce */
5917 		break;
5918 	case PR_SWAP_SNK_SRC_SINK_OFF:
5919 	case PR_SWAP_SRC_SNK_TRANSITION_OFF:
5920 	case PR_SWAP_SRC_SNK_SOURCE_OFF:
5921 	case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
5922 	case PR_SWAP_SNK_SRC_SOURCE_ON:
5923 		/*
5924 		 * CC state change is expected in PR_SWAP
5925 		 * Ignore it.
5926 		 */
5927 		break;
5928 	case FR_SWAP_SEND:
5929 	case FR_SWAP_SEND_TIMEOUT:
5930 	case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5931 	case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5932 	case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5933 		/* Do nothing, CC change expected */
5934 		break;
5935 
5936 	case PORT_RESET:
5937 	case PORT_RESET_WAIT_OFF:
5938 		/*
5939 		 * State set back to default mode once the timer completes.
5940 		 * Ignore CC changes here.
5941 		 */
5942 		break;
5943 	default:
5944 		/*
5945 		 * While acting as sink and auto vbus discharge is enabled, Allow disconnect
5946 		 * to be driven by vbus disconnect.
5947 		 */
5948 		if (tcpm_port_is_disconnected(port) && !(port->pwr_role == TYPEC_SINK &&
5949 							 port->auto_vbus_discharge_enabled))
5950 			tcpm_set_state(port, unattached_state(port), 0);
5951 		break;
5952 	}
5953 }
5954 
_tcpm_pd_vbus_on(struct tcpm_port * port)5955 static void _tcpm_pd_vbus_on(struct tcpm_port *port)
5956 {
5957 	tcpm_log_force(port, "VBUS on");
5958 	port->vbus_present = true;
5959 	/*
5960 	 * When vbus_present is true i.e. Voltage at VBUS is greater than VSAFE5V implicitly
5961 	 * states that vbus is not at VSAFE0V, hence clear the vbus_vsafe0v flag here.
5962 	 */
5963 	port->vbus_vsafe0v = false;
5964 
5965 	switch (port->state) {
5966 	case SNK_TRANSITION_SINK_VBUS:
5967 		port->explicit_contract = true;
5968 		tcpm_set_state(port, SNK_READY, 0);
5969 		break;
5970 	case SNK_DISCOVERY:
5971 		tcpm_set_state(port, SNK_DISCOVERY, 0);
5972 		break;
5973 
5974 	case SNK_DEBOUNCED:
5975 		tcpm_set_state(port, tcpm_try_src(port) ? SRC_TRY
5976 							: SNK_ATTACHED,
5977 				       0);
5978 		break;
5979 	case SNK_HARD_RESET_WAIT_VBUS:
5980 		tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, 0);
5981 		break;
5982 	case SRC_ATTACHED:
5983 		tcpm_set_state(port, SRC_STARTUP, 0);
5984 		break;
5985 	case SRC_HARD_RESET_VBUS_ON:
5986 		tcpm_set_state(port, SRC_STARTUP, 0);
5987 		break;
5988 
5989 	case SNK_TRY:
5990 		/* Do nothing, waiting for timeout */
5991 		break;
5992 	case SRC_TRYWAIT:
5993 		/* Do nothing, Waiting for Rd to be detected */
5994 		break;
5995 	case SRC_TRYWAIT_DEBOUNCE:
5996 		tcpm_set_state(port, SRC_TRYWAIT, 0);
5997 		break;
5998 	case SNK_TRY_WAIT_DEBOUNCE:
5999 		/* Do nothing, waiting for PD_DEBOUNCE to do be done */
6000 		break;
6001 	case SNK_TRYWAIT:
6002 		/* Do nothing, waiting for tCCDebounce */
6003 		break;
6004 	case SNK_TRYWAIT_VBUS:
6005 		if (tcpm_port_is_sink(port))
6006 			tcpm_set_state(port, SNK_ATTACHED, 0);
6007 		break;
6008 	case SNK_TRYWAIT_DEBOUNCE:
6009 		/* Do nothing, waiting for Rp */
6010 		break;
6011 	case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
6012 		if (port->vbus_present && tcpm_port_is_sink(port))
6013 			tcpm_set_state(port, SNK_ATTACHED, 0);
6014 		break;
6015 	case SRC_TRY_WAIT:
6016 	case SRC_TRY_DEBOUNCE:
6017 		/* Do nothing, waiting for sink detection */
6018 		break;
6019 	case FR_SWAP_SEND:
6020 	case FR_SWAP_SEND_TIMEOUT:
6021 	case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
6022 	case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
6023 		if (port->tcpc->frs_sourcing_vbus)
6024 			port->tcpc->frs_sourcing_vbus(port->tcpc);
6025 		break;
6026 	case FR_SWAP_SNK_SRC_NEW_SINK_READY:
6027 		if (port->tcpc->frs_sourcing_vbus)
6028 			port->tcpc->frs_sourcing_vbus(port->tcpc);
6029 		tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
6030 		break;
6031 
6032 	case PORT_RESET:
6033 	case PORT_RESET_WAIT_OFF:
6034 		/*
6035 		 * State set back to default mode once the timer completes.
6036 		 * Ignore vbus changes here.
6037 		 */
6038 		break;
6039 
6040 	default:
6041 		break;
6042 	}
6043 }
6044 
_tcpm_pd_vbus_off(struct tcpm_port * port)6045 static void _tcpm_pd_vbus_off(struct tcpm_port *port)
6046 {
6047 	tcpm_log_force(port, "VBUS off");
6048 	port->vbus_present = false;
6049 	port->vbus_never_low = false;
6050 	switch (port->state) {
6051 	case SNK_HARD_RESET_SINK_OFF:
6052 		tcpm_set_state(port, SNK_HARD_RESET_WAIT_VBUS, 0);
6053 		break;
6054 	case HARD_RESET_SEND:
6055 		break;
6056 	case SNK_TRY:
6057 		/* Do nothing, waiting for timeout */
6058 		break;
6059 	case SRC_TRYWAIT:
6060 		/* Hand over to state machine if needed */
6061 		if (tcpm_port_is_source(port))
6062 			tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
6063 		break;
6064 	case SNK_TRY_WAIT_DEBOUNCE:
6065 		/* Do nothing, waiting for PD_DEBOUNCE to do be done */
6066 		break;
6067 	case SNK_TRYWAIT:
6068 	case SNK_TRYWAIT_VBUS:
6069 	case SNK_TRYWAIT_DEBOUNCE:
6070 		break;
6071 	case SNK_ATTACH_WAIT:
6072 	case SNK_DEBOUNCED:
6073 		/* Do nothing, as TCPM is still waiting for vbus to reaach VSAFE5V to connect */
6074 		break;
6075 
6076 	case SNK_NEGOTIATE_CAPABILITIES:
6077 		break;
6078 
6079 	case PR_SWAP_SRC_SNK_TRANSITION_OFF:
6080 		tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF, 0);
6081 		break;
6082 
6083 	case PR_SWAP_SNK_SRC_SINK_OFF:
6084 		/* Do nothing, expected */
6085 		break;
6086 
6087 	case PR_SWAP_SNK_SRC_SOURCE_ON:
6088 		/*
6089 		 * Do nothing when vbus off notification is received.
6090 		 * TCPM can wait for PD_T_NEWSRC in PR_SWAP_SNK_SRC_SOURCE_ON
6091 		 * for the vbus source to ramp up.
6092 		 */
6093 		break;
6094 
6095 	case PORT_RESET_WAIT_OFF:
6096 		tcpm_set_state(port, tcpm_default_state(port), 0);
6097 		break;
6098 
6099 	case SRC_TRY_WAIT:
6100 	case SRC_TRY_DEBOUNCE:
6101 		/* Do nothing, waiting for sink detection */
6102 		break;
6103 
6104 	case SRC_STARTUP:
6105 	case SRC_SEND_CAPABILITIES:
6106 	case SRC_SEND_CAPABILITIES_TIMEOUT:
6107 	case SRC_NEGOTIATE_CAPABILITIES:
6108 	case SRC_TRANSITION_SUPPLY:
6109 	case SRC_READY:
6110 	case SRC_WAIT_NEW_CAPABILITIES:
6111 		/*
6112 		 * Force to unattached state to re-initiate connection.
6113 		 * DRP port should move to Unattached.SNK instead of Unattached.SRC if
6114 		 * sink removed. Although sink removal here is due to source's vbus collapse,
6115 		 * treat it the same way for consistency.
6116 		 */
6117 		if (port->port_type == TYPEC_PORT_SRC)
6118 			tcpm_set_state(port, SRC_UNATTACHED, tcpm_wait_for_discharge(port));
6119 		else
6120 			tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
6121 		break;
6122 
6123 	case PORT_RESET:
6124 		/*
6125 		 * State set back to default mode once the timer completes.
6126 		 * Ignore vbus changes here.
6127 		 */
6128 		break;
6129 
6130 	case FR_SWAP_SEND:
6131 	case FR_SWAP_SEND_TIMEOUT:
6132 	case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
6133 	case FR_SWAP_SNK_SRC_NEW_SINK_READY:
6134 	case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
6135 		/* Do nothing, vbus drop expected */
6136 		break;
6137 
6138 	case SNK_HARD_RESET_WAIT_VBUS:
6139 		/* Do nothing, its OK to receive vbus off events */
6140 		break;
6141 
6142 	default:
6143 		if (port->pwr_role == TYPEC_SINK && port->attached)
6144 			tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
6145 		break;
6146 	}
6147 }
6148 
_tcpm_pd_vbus_vsafe0v(struct tcpm_port * port)6149 static void _tcpm_pd_vbus_vsafe0v(struct tcpm_port *port)
6150 {
6151 	tcpm_log_force(port, "VBUS VSAFE0V");
6152 	port->vbus_vsafe0v = true;
6153 	switch (port->state) {
6154 	case SRC_HARD_RESET_VBUS_OFF:
6155 		/*
6156 		 * After establishing the vSafe0V voltage condition on VBUS, the Source Shall wait
6157 		 * tSrcRecover before re-applying VCONN and restoring VBUS to vSafe5V.
6158 		 */
6159 		tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SRC_RECOVER);
6160 		break;
6161 	case SRC_ATTACH_WAIT:
6162 		if (tcpm_port_is_source(port))
6163 			tcpm_set_state(port, tcpm_try_snk(port) ? SNK_TRY : SRC_ATTACHED,
6164 				       PD_T_CC_DEBOUNCE);
6165 		break;
6166 	case SRC_STARTUP:
6167 	case SRC_SEND_CAPABILITIES:
6168 	case SRC_SEND_CAPABILITIES_TIMEOUT:
6169 	case SRC_NEGOTIATE_CAPABILITIES:
6170 	case SRC_TRANSITION_SUPPLY:
6171 	case SRC_READY:
6172 	case SRC_WAIT_NEW_CAPABILITIES:
6173 		if (port->auto_vbus_discharge_enabled) {
6174 			if (port->port_type == TYPEC_PORT_SRC)
6175 				tcpm_set_state(port, SRC_UNATTACHED, 0);
6176 			else
6177 				tcpm_set_state(port, SNK_UNATTACHED, 0);
6178 		}
6179 		break;
6180 	case PR_SWAP_SNK_SRC_SINK_OFF:
6181 	case PR_SWAP_SNK_SRC_SOURCE_ON:
6182 		/* Do nothing, vsafe0v is expected during transition */
6183 		break;
6184 	case SNK_ATTACH_WAIT:
6185 	case SNK_DEBOUNCED:
6186 		/*Do nothing, still waiting for VSAFE5V for connect */
6187 		break;
6188 	case SNK_HARD_RESET_WAIT_VBUS:
6189 		/* Do nothing, its OK to receive vbus off events */
6190 		break;
6191 	default:
6192 		if (port->pwr_role == TYPEC_SINK && port->auto_vbus_discharge_enabled)
6193 			tcpm_set_state(port, SNK_UNATTACHED, 0);
6194 		break;
6195 	}
6196 }
6197 
_tcpm_pd_hard_reset(struct tcpm_port * port)6198 static void _tcpm_pd_hard_reset(struct tcpm_port *port)
6199 {
6200 	tcpm_log_force(port, "Received hard reset");
6201 	if (port->bist_request == BDO_MODE_TESTDATA && port->tcpc->set_bist_data)
6202 		port->tcpc->set_bist_data(port->tcpc, false);
6203 
6204 	switch (port->state) {
6205 	case TOGGLING:
6206 	case ERROR_RECOVERY:
6207 	case PORT_RESET:
6208 	case PORT_RESET_WAIT_OFF:
6209 		return;
6210 	default:
6211 		break;
6212 	}
6213 
6214 	if (port->ams != NONE_AMS)
6215 		port->ams = NONE_AMS;
6216 	if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
6217 		port->ams = HARD_RESET;
6218 	/*
6219 	 * If we keep receiving hard reset requests, executing the hard reset
6220 	 * must have failed. Revert to error recovery if that happens.
6221 	 */
6222 	tcpm_set_state(port,
6223 		       port->hard_reset_count < PD_N_HARD_RESET_COUNT ?
6224 				HARD_RESET_START : ERROR_RECOVERY,
6225 		       0);
6226 }
6227 
tcpm_pd_event_handler(struct kthread_work * work)6228 static void tcpm_pd_event_handler(struct kthread_work *work)
6229 {
6230 	struct tcpm_port *port = container_of(work, struct tcpm_port,
6231 					      event_work);
6232 	u32 events;
6233 
6234 	mutex_lock(&port->lock);
6235 
6236 	spin_lock(&port->pd_event_lock);
6237 	while (port->pd_events) {
6238 		events = port->pd_events;
6239 		port->pd_events = 0;
6240 		spin_unlock(&port->pd_event_lock);
6241 		if (events & TCPM_RESET_EVENT)
6242 			_tcpm_pd_hard_reset(port);
6243 		if (events & TCPM_VBUS_EVENT) {
6244 			bool vbus;
6245 
6246 			vbus = port->tcpc->get_vbus(port->tcpc);
6247 			if (vbus) {
6248 				_tcpm_pd_vbus_on(port);
6249 			} else {
6250 				_tcpm_pd_vbus_off(port);
6251 				/*
6252 				 * When TCPC does not support detecting vsafe0v voltage level,
6253 				 * treat vbus absent as vsafe0v. Else invoke is_vbus_vsafe0v
6254 				 * to see if vbus has discharge to VSAFE0V.
6255 				 */
6256 				if (!port->tcpc->is_vbus_vsafe0v ||
6257 				    port->tcpc->is_vbus_vsafe0v(port->tcpc))
6258 					_tcpm_pd_vbus_vsafe0v(port);
6259 			}
6260 		}
6261 		if (events & TCPM_CC_EVENT) {
6262 			enum typec_cc_status cc1, cc2;
6263 
6264 			if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
6265 				_tcpm_cc_change(port, cc1, cc2);
6266 		}
6267 		if (events & TCPM_FRS_EVENT) {
6268 			if (port->state == SNK_READY) {
6269 				int ret;
6270 
6271 				port->upcoming_state = FR_SWAP_SEND;
6272 				ret = tcpm_ams_start(port, FAST_ROLE_SWAP);
6273 				if (ret == -EAGAIN)
6274 					port->upcoming_state = INVALID_STATE;
6275 			} else {
6276 				tcpm_log(port, "Discarding FRS_SIGNAL! Not in sink ready");
6277 			}
6278 		}
6279 		if (events & TCPM_SOURCING_VBUS) {
6280 			tcpm_log(port, "sourcing vbus");
6281 			/*
6282 			 * In fast role swap case TCPC autonomously sources vbus. Set vbus_source
6283 			 * true as TCPM wouldn't have called tcpm_set_vbus.
6284 			 *
6285 			 * When vbus is sourced on the command on TCPM i.e. TCPM called
6286 			 * tcpm_set_vbus to source vbus, vbus_source would already be true.
6287 			 */
6288 			port->vbus_source = true;
6289 			_tcpm_pd_vbus_on(port);
6290 		}
6291 		if (events & TCPM_PORT_CLEAN) {
6292 			tcpm_log(port, "port clean");
6293 			if (port->state == CHECK_CONTAMINANT) {
6294 				if (tcpm_start_toggling(port, tcpm_rp_cc(port)))
6295 					tcpm_set_state(port, TOGGLING, 0);
6296 				else
6297 					tcpm_set_state(port, tcpm_default_state(port), 0);
6298 			}
6299 		}
6300 		if (events & TCPM_PORT_ERROR) {
6301 			tcpm_log(port, "port triggering error recovery");
6302 			tcpm_set_state(port, ERROR_RECOVERY, 0);
6303 		}
6304 
6305 		spin_lock(&port->pd_event_lock);
6306 	}
6307 	spin_unlock(&port->pd_event_lock);
6308 	mutex_unlock(&port->lock);
6309 }
6310 
tcpm_cc_change(struct tcpm_port * port)6311 void tcpm_cc_change(struct tcpm_port *port)
6312 {
6313 	spin_lock(&port->pd_event_lock);
6314 	port->pd_events |= TCPM_CC_EVENT;
6315 	spin_unlock(&port->pd_event_lock);
6316 	kthread_queue_work(port->wq, &port->event_work);
6317 }
6318 EXPORT_SYMBOL_GPL(tcpm_cc_change);
6319 
tcpm_vbus_change(struct tcpm_port * port)6320 void tcpm_vbus_change(struct tcpm_port *port)
6321 {
6322 	spin_lock(&port->pd_event_lock);
6323 	port->pd_events |= TCPM_VBUS_EVENT;
6324 	spin_unlock(&port->pd_event_lock);
6325 	kthread_queue_work(port->wq, &port->event_work);
6326 }
6327 EXPORT_SYMBOL_GPL(tcpm_vbus_change);
6328 
tcpm_pd_hard_reset(struct tcpm_port * port)6329 void tcpm_pd_hard_reset(struct tcpm_port *port)
6330 {
6331 	spin_lock(&port->pd_event_lock);
6332 	port->pd_events = TCPM_RESET_EVENT;
6333 	spin_unlock(&port->pd_event_lock);
6334 	kthread_queue_work(port->wq, &port->event_work);
6335 }
6336 EXPORT_SYMBOL_GPL(tcpm_pd_hard_reset);
6337 
tcpm_sink_frs(struct tcpm_port * port)6338 void tcpm_sink_frs(struct tcpm_port *port)
6339 {
6340 	spin_lock(&port->pd_event_lock);
6341 	port->pd_events |= TCPM_FRS_EVENT;
6342 	spin_unlock(&port->pd_event_lock);
6343 	kthread_queue_work(port->wq, &port->event_work);
6344 }
6345 EXPORT_SYMBOL_GPL(tcpm_sink_frs);
6346 
tcpm_sourcing_vbus(struct tcpm_port * port)6347 void tcpm_sourcing_vbus(struct tcpm_port *port)
6348 {
6349 	spin_lock(&port->pd_event_lock);
6350 	port->pd_events |= TCPM_SOURCING_VBUS;
6351 	spin_unlock(&port->pd_event_lock);
6352 	kthread_queue_work(port->wq, &port->event_work);
6353 }
6354 EXPORT_SYMBOL_GPL(tcpm_sourcing_vbus);
6355 
tcpm_port_clean(struct tcpm_port * port)6356 void tcpm_port_clean(struct tcpm_port *port)
6357 {
6358 	spin_lock(&port->pd_event_lock);
6359 	port->pd_events |= TCPM_PORT_CLEAN;
6360 	spin_unlock(&port->pd_event_lock);
6361 	kthread_queue_work(port->wq, &port->event_work);
6362 }
6363 EXPORT_SYMBOL_GPL(tcpm_port_clean);
6364 
tcpm_port_is_toggling(struct tcpm_port * port)6365 bool tcpm_port_is_toggling(struct tcpm_port *port)
6366 {
6367 	return port->port_type == TYPEC_PORT_DRP && port->state == TOGGLING;
6368 }
6369 EXPORT_SYMBOL_GPL(tcpm_port_is_toggling);
6370 
tcpm_port_error_recovery(struct tcpm_port * port)6371 void tcpm_port_error_recovery(struct tcpm_port *port)
6372 {
6373 	spin_lock(&port->pd_event_lock);
6374 	port->pd_events |= TCPM_PORT_ERROR;
6375 	spin_unlock(&port->pd_event_lock);
6376 	kthread_queue_work(port->wq, &port->event_work);
6377 }
6378 EXPORT_SYMBOL_GPL(tcpm_port_error_recovery);
6379 
tcpm_enable_frs_work(struct kthread_work * work)6380 static void tcpm_enable_frs_work(struct kthread_work *work)
6381 {
6382 	struct tcpm_port *port = container_of(work, struct tcpm_port, enable_frs);
6383 	int ret;
6384 
6385 	mutex_lock(&port->lock);
6386 	/* Not FRS capable */
6387 	if (!port->connected || port->port_type != TYPEC_PORT_DRP ||
6388 	    port->pwr_opmode != TYPEC_PWR_MODE_PD ||
6389 	    !port->tcpc->enable_frs ||
6390 	    /* Sink caps queried */
6391 	    port->sink_cap_done || port->negotiated_rev < PD_REV30)
6392 		goto unlock;
6393 
6394 	/* Send when the state machine is idle */
6395 	if (port->state != SNK_READY || port->vdm_sm_running || port->send_discover ||
6396 	    port->send_discover_prime)
6397 		goto resched;
6398 
6399 	port->upcoming_state = GET_SINK_CAP;
6400 	ret = tcpm_ams_start(port, GET_SINK_CAPABILITIES);
6401 	if (ret == -EAGAIN) {
6402 		port->upcoming_state = INVALID_STATE;
6403 	} else {
6404 		port->sink_cap_done = true;
6405 		goto unlock;
6406 	}
6407 resched:
6408 	mod_enable_frs_delayed_work(port, GET_SINK_CAP_RETRY_MS);
6409 unlock:
6410 	mutex_unlock(&port->lock);
6411 }
6412 
tcpm_send_discover_work(struct kthread_work * work)6413 static void tcpm_send_discover_work(struct kthread_work *work)
6414 {
6415 	struct tcpm_port *port = container_of(work, struct tcpm_port, send_discover_work);
6416 
6417 	mutex_lock(&port->lock);
6418 	/* No need to send DISCOVER_IDENTITY anymore */
6419 	if (!port->send_discover && !port->send_discover_prime)
6420 		goto unlock;
6421 
6422 	if (port->data_role == TYPEC_DEVICE && port->negotiated_rev < PD_REV30) {
6423 		port->send_discover = false;
6424 		port->send_discover_prime = false;
6425 		goto unlock;
6426 	}
6427 
6428 	/* Retry if the port is not idle */
6429 	if ((port->state != SRC_READY && port->state != SNK_READY &&
6430 	     port->state != SRC_VDM_IDENTITY_REQUEST) || port->vdm_sm_running) {
6431 		mod_send_discover_delayed_work(port, SEND_DISCOVER_RETRY_MS);
6432 		goto unlock;
6433 	}
6434 
6435 	tcpm_send_vdm(port, USB_SID_PD, CMD_DISCOVER_IDENT, NULL, 0, port->tx_sop_type);
6436 
6437 unlock:
6438 	mutex_unlock(&port->lock);
6439 }
6440 
tcpm_dr_set(struct typec_port * p,enum typec_data_role data)6441 static int tcpm_dr_set(struct typec_port *p, enum typec_data_role data)
6442 {
6443 	struct tcpm_port *port = typec_get_drvdata(p);
6444 	int ret;
6445 
6446 	mutex_lock(&port->swap_lock);
6447 	mutex_lock(&port->lock);
6448 
6449 	if (port->typec_caps.data != TYPEC_PORT_DRD) {
6450 		ret = -EINVAL;
6451 		goto port_unlock;
6452 	}
6453 	if (port->state != SRC_READY && port->state != SNK_READY) {
6454 		ret = -EAGAIN;
6455 		goto port_unlock;
6456 	}
6457 
6458 	if (port->data_role == data) {
6459 		ret = 0;
6460 		goto port_unlock;
6461 	}
6462 
6463 	/*
6464 	 * XXX
6465 	 * 6.3.9: If an alternate mode is active, a request to swap
6466 	 * alternate modes shall trigger a port reset.
6467 	 * Reject data role swap request in this case.
6468 	 */
6469 
6470 	if (!port->pd_capable) {
6471 		/*
6472 		 * If the partner is not PD capable, reset the port to
6473 		 * trigger a role change. This can only work if a preferred
6474 		 * role is configured, and if it matches the requested role.
6475 		 */
6476 		if (port->try_role == TYPEC_NO_PREFERRED_ROLE ||
6477 		    port->try_role == port->pwr_role) {
6478 			ret = -EINVAL;
6479 			goto port_unlock;
6480 		}
6481 		port->non_pd_role_swap = true;
6482 		tcpm_set_state(port, PORT_RESET, 0);
6483 	} else {
6484 		port->upcoming_state = DR_SWAP_SEND;
6485 		ret = tcpm_ams_start(port, DATA_ROLE_SWAP);
6486 		if (ret == -EAGAIN) {
6487 			port->upcoming_state = INVALID_STATE;
6488 			goto port_unlock;
6489 		}
6490 	}
6491 
6492 	port->swap_status = 0;
6493 	port->swap_pending = true;
6494 	reinit_completion(&port->swap_complete);
6495 	mutex_unlock(&port->lock);
6496 
6497 	if (!wait_for_completion_timeout(&port->swap_complete,
6498 				msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
6499 		ret = -ETIMEDOUT;
6500 	else
6501 		ret = port->swap_status;
6502 
6503 	port->non_pd_role_swap = false;
6504 	goto swap_unlock;
6505 
6506 port_unlock:
6507 	mutex_unlock(&port->lock);
6508 swap_unlock:
6509 	mutex_unlock(&port->swap_lock);
6510 	return ret;
6511 }
6512 
tcpm_pr_set(struct typec_port * p,enum typec_role role)6513 static int tcpm_pr_set(struct typec_port *p, enum typec_role role)
6514 {
6515 	struct tcpm_port *port = typec_get_drvdata(p);
6516 	int ret;
6517 
6518 	mutex_lock(&port->swap_lock);
6519 	mutex_lock(&port->lock);
6520 
6521 	if (port->port_type != TYPEC_PORT_DRP) {
6522 		ret = -EINVAL;
6523 		goto port_unlock;
6524 	}
6525 	if (port->state != SRC_READY && port->state != SNK_READY) {
6526 		ret = -EAGAIN;
6527 		goto port_unlock;
6528 	}
6529 
6530 	if (role == port->pwr_role) {
6531 		ret = 0;
6532 		goto port_unlock;
6533 	}
6534 
6535 	port->upcoming_state = PR_SWAP_SEND;
6536 	ret = tcpm_ams_start(port, POWER_ROLE_SWAP);
6537 	if (ret == -EAGAIN) {
6538 		port->upcoming_state = INVALID_STATE;
6539 		goto port_unlock;
6540 	}
6541 
6542 	port->swap_status = 0;
6543 	port->swap_pending = true;
6544 	reinit_completion(&port->swap_complete);
6545 	mutex_unlock(&port->lock);
6546 
6547 	if (!wait_for_completion_timeout(&port->swap_complete,
6548 				msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
6549 		ret = -ETIMEDOUT;
6550 	else
6551 		ret = port->swap_status;
6552 
6553 	goto swap_unlock;
6554 
6555 port_unlock:
6556 	mutex_unlock(&port->lock);
6557 swap_unlock:
6558 	mutex_unlock(&port->swap_lock);
6559 	return ret;
6560 }
6561 
tcpm_vconn_set(struct typec_port * p,enum typec_role role)6562 static int tcpm_vconn_set(struct typec_port *p, enum typec_role role)
6563 {
6564 	struct tcpm_port *port = typec_get_drvdata(p);
6565 	int ret;
6566 
6567 	mutex_lock(&port->swap_lock);
6568 	mutex_lock(&port->lock);
6569 
6570 	if (port->state != SRC_READY && port->state != SNK_READY) {
6571 		ret = -EAGAIN;
6572 		goto port_unlock;
6573 	}
6574 
6575 	if (role == port->vconn_role) {
6576 		ret = 0;
6577 		goto port_unlock;
6578 	}
6579 
6580 	port->upcoming_state = VCONN_SWAP_SEND;
6581 	ret = tcpm_ams_start(port, VCONN_SWAP);
6582 	if (ret == -EAGAIN) {
6583 		port->upcoming_state = INVALID_STATE;
6584 		goto port_unlock;
6585 	}
6586 
6587 	port->swap_status = 0;
6588 	port->swap_pending = true;
6589 	reinit_completion(&port->swap_complete);
6590 	mutex_unlock(&port->lock);
6591 
6592 	if (!wait_for_completion_timeout(&port->swap_complete,
6593 				msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
6594 		ret = -ETIMEDOUT;
6595 	else
6596 		ret = port->swap_status;
6597 
6598 	goto swap_unlock;
6599 
6600 port_unlock:
6601 	mutex_unlock(&port->lock);
6602 swap_unlock:
6603 	mutex_unlock(&port->swap_lock);
6604 	return ret;
6605 }
6606 
tcpm_try_role(struct typec_port * p,int role)6607 static int tcpm_try_role(struct typec_port *p, int role)
6608 {
6609 	struct tcpm_port *port = typec_get_drvdata(p);
6610 	struct tcpc_dev	*tcpc = port->tcpc;
6611 	int ret = 0;
6612 
6613 	mutex_lock(&port->lock);
6614 	if (tcpc->try_role)
6615 		ret = tcpc->try_role(tcpc, role);
6616 	if (!ret)
6617 		port->try_role = role;
6618 	port->try_src_count = 0;
6619 	port->try_snk_count = 0;
6620 	mutex_unlock(&port->lock);
6621 
6622 	return ret;
6623 }
6624 
tcpm_pps_set_op_curr(struct tcpm_port * port,u16 req_op_curr)6625 static int tcpm_pps_set_op_curr(struct tcpm_port *port, u16 req_op_curr)
6626 {
6627 	unsigned int target_mw;
6628 	int ret;
6629 
6630 	mutex_lock(&port->swap_lock);
6631 	mutex_lock(&port->lock);
6632 
6633 	if (!port->pps_data.active) {
6634 		ret = -EOPNOTSUPP;
6635 		goto port_unlock;
6636 	}
6637 
6638 	if (port->state != SNK_READY) {
6639 		ret = -EAGAIN;
6640 		goto port_unlock;
6641 	}
6642 
6643 	if (req_op_curr > port->pps_data.max_curr) {
6644 		ret = -EINVAL;
6645 		goto port_unlock;
6646 	}
6647 
6648 	target_mw = (req_op_curr * port->supply_voltage) / 1000;
6649 	if (target_mw < port->operating_snk_mw) {
6650 		ret = -EINVAL;
6651 		goto port_unlock;
6652 	}
6653 
6654 	port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6655 	ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6656 	if (ret == -EAGAIN) {
6657 		port->upcoming_state = INVALID_STATE;
6658 		goto port_unlock;
6659 	}
6660 
6661 	/* Round down operating current to align with PPS valid steps */
6662 	req_op_curr = req_op_curr - (req_op_curr % RDO_PROG_CURR_MA_STEP);
6663 
6664 	reinit_completion(&port->pps_complete);
6665 	port->pps_data.req_op_curr = req_op_curr;
6666 	port->pps_status = 0;
6667 	port->pps_pending = true;
6668 	mutex_unlock(&port->lock);
6669 
6670 	if (!wait_for_completion_timeout(&port->pps_complete,
6671 				msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
6672 		ret = -ETIMEDOUT;
6673 	else
6674 		ret = port->pps_status;
6675 
6676 	goto swap_unlock;
6677 
6678 port_unlock:
6679 	mutex_unlock(&port->lock);
6680 swap_unlock:
6681 	mutex_unlock(&port->swap_lock);
6682 
6683 	return ret;
6684 }
6685 
tcpm_pps_set_out_volt(struct tcpm_port * port,u16 req_out_volt)6686 static int tcpm_pps_set_out_volt(struct tcpm_port *port, u16 req_out_volt)
6687 {
6688 	unsigned int target_mw;
6689 	int ret;
6690 
6691 	mutex_lock(&port->swap_lock);
6692 	mutex_lock(&port->lock);
6693 
6694 	if (!port->pps_data.active) {
6695 		ret = -EOPNOTSUPP;
6696 		goto port_unlock;
6697 	}
6698 
6699 	if (port->state != SNK_READY) {
6700 		ret = -EAGAIN;
6701 		goto port_unlock;
6702 	}
6703 
6704 	target_mw = (port->current_limit * req_out_volt) / 1000;
6705 	if (target_mw < port->operating_snk_mw) {
6706 		ret = -EINVAL;
6707 		goto port_unlock;
6708 	}
6709 
6710 	port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6711 	ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6712 	if (ret == -EAGAIN) {
6713 		port->upcoming_state = INVALID_STATE;
6714 		goto port_unlock;
6715 	}
6716 
6717 	/* Round down output voltage to align with PPS valid steps */
6718 	req_out_volt = req_out_volt - (req_out_volt % RDO_PROG_VOLT_MV_STEP);
6719 
6720 	reinit_completion(&port->pps_complete);
6721 	port->pps_data.req_out_volt = req_out_volt;
6722 	port->pps_status = 0;
6723 	port->pps_pending = true;
6724 	mutex_unlock(&port->lock);
6725 
6726 	if (!wait_for_completion_timeout(&port->pps_complete,
6727 				msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
6728 		ret = -ETIMEDOUT;
6729 	else
6730 		ret = port->pps_status;
6731 
6732 	goto swap_unlock;
6733 
6734 port_unlock:
6735 	mutex_unlock(&port->lock);
6736 swap_unlock:
6737 	mutex_unlock(&port->swap_lock);
6738 
6739 	return ret;
6740 }
6741 
tcpm_pps_activate(struct tcpm_port * port,bool activate)6742 static int tcpm_pps_activate(struct tcpm_port *port, bool activate)
6743 {
6744 	int ret = 0;
6745 
6746 	mutex_lock(&port->swap_lock);
6747 	mutex_lock(&port->lock);
6748 
6749 	if (!port->pps_data.supported) {
6750 		ret = -EOPNOTSUPP;
6751 		goto port_unlock;
6752 	}
6753 
6754 	/* Trying to deactivate PPS when already deactivated so just bail */
6755 	if (!port->pps_data.active && !activate)
6756 		goto port_unlock;
6757 
6758 	if (port->state != SNK_READY) {
6759 		ret = -EAGAIN;
6760 		goto port_unlock;
6761 	}
6762 
6763 	if (activate)
6764 		port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6765 	else
6766 		port->upcoming_state = SNK_NEGOTIATE_CAPABILITIES;
6767 	ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6768 	if (ret == -EAGAIN) {
6769 		port->upcoming_state = INVALID_STATE;
6770 		goto port_unlock;
6771 	}
6772 
6773 	reinit_completion(&port->pps_complete);
6774 	port->pps_status = 0;
6775 	port->pps_pending = true;
6776 
6777 	/* Trigger PPS request or move back to standard PDO contract */
6778 	if (activate) {
6779 		port->pps_data.req_out_volt = port->supply_voltage;
6780 		port->pps_data.req_op_curr = port->current_limit;
6781 	}
6782 	mutex_unlock(&port->lock);
6783 
6784 	if (!wait_for_completion_timeout(&port->pps_complete,
6785 				msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
6786 		ret = -ETIMEDOUT;
6787 	else
6788 		ret = port->pps_status;
6789 
6790 	goto swap_unlock;
6791 
6792 port_unlock:
6793 	mutex_unlock(&port->lock);
6794 swap_unlock:
6795 	mutex_unlock(&port->swap_lock);
6796 
6797 	return ret;
6798 }
6799 
tcpm_init(struct tcpm_port * port)6800 static void tcpm_init(struct tcpm_port *port)
6801 {
6802 	enum typec_cc_status cc1, cc2;
6803 
6804 	port->tcpc->init(port->tcpc);
6805 
6806 	tcpm_reset_port(port);
6807 
6808 	/*
6809 	 * XXX
6810 	 * Should possibly wait for VBUS to settle if it was enabled locally
6811 	 * since tcpm_reset_port() will disable VBUS.
6812 	 */
6813 	port->vbus_present = port->tcpc->get_vbus(port->tcpc);
6814 	if (port->vbus_present)
6815 		port->vbus_never_low = true;
6816 
6817 	/*
6818 	 * 1. When vbus_present is true, voltage on VBUS is already at VSAFE5V.
6819 	 * So implicitly vbus_vsafe0v = false.
6820 	 *
6821 	 * 2. When vbus_present is false and TCPC does NOT support querying
6822 	 * vsafe0v status, then, it's best to assume vbus is at VSAFE0V i.e.
6823 	 * vbus_vsafe0v is true.
6824 	 *
6825 	 * 3. When vbus_present is false and TCPC does support querying vsafe0v,
6826 	 * then, query tcpc for vsafe0v status.
6827 	 */
6828 	if (port->vbus_present)
6829 		port->vbus_vsafe0v = false;
6830 	else if (!port->tcpc->is_vbus_vsafe0v)
6831 		port->vbus_vsafe0v = true;
6832 	else
6833 		port->vbus_vsafe0v = port->tcpc->is_vbus_vsafe0v(port->tcpc);
6834 
6835 	tcpm_set_state(port, tcpm_default_state(port), 0);
6836 
6837 	if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
6838 		_tcpm_cc_change(port, cc1, cc2);
6839 
6840 	/*
6841 	 * Some adapters need a clean slate at startup, and won't recover
6842 	 * otherwise. So do not try to be fancy and force a clean disconnect.
6843 	 */
6844 	tcpm_set_state(port, PORT_RESET, 0);
6845 }
6846 
tcpm_port_type_set(struct typec_port * p,enum typec_port_type type)6847 static int tcpm_port_type_set(struct typec_port *p, enum typec_port_type type)
6848 {
6849 	struct tcpm_port *port = typec_get_drvdata(p);
6850 
6851 	mutex_lock(&port->lock);
6852 	if (type == port->port_type)
6853 		goto port_unlock;
6854 
6855 	port->port_type = type;
6856 
6857 	if (!port->connected) {
6858 		tcpm_set_state(port, PORT_RESET, 0);
6859 	} else if (type == TYPEC_PORT_SNK) {
6860 		if (!(port->pwr_role == TYPEC_SINK &&
6861 		      port->data_role == TYPEC_DEVICE))
6862 			tcpm_set_state(port, PORT_RESET, 0);
6863 	} else if (type == TYPEC_PORT_SRC) {
6864 		if (!(port->pwr_role == TYPEC_SOURCE &&
6865 		      port->data_role == TYPEC_HOST))
6866 			tcpm_set_state(port, PORT_RESET, 0);
6867 	}
6868 
6869 port_unlock:
6870 	mutex_unlock(&port->lock);
6871 	return 0;
6872 }
6873 
tcpm_find_pd_data(struct tcpm_port * port,struct usb_power_delivery * pd)6874 static struct pd_data *tcpm_find_pd_data(struct tcpm_port *port, struct usb_power_delivery *pd)
6875 {
6876 	int i;
6877 
6878 	for (i = 0; port->pd_list[i]; i++) {
6879 		if (port->pd_list[i]->pd == pd)
6880 			return port->pd_list[i];
6881 	}
6882 
6883 	return ERR_PTR(-ENODATA);
6884 }
6885 
tcpm_pd_get(struct typec_port * p)6886 static struct usb_power_delivery **tcpm_pd_get(struct typec_port *p)
6887 {
6888 	struct tcpm_port *port = typec_get_drvdata(p);
6889 
6890 	return port->pds;
6891 }
6892 
tcpm_pd_set(struct typec_port * p,struct usb_power_delivery * pd)6893 static int tcpm_pd_set(struct typec_port *p, struct usb_power_delivery *pd)
6894 {
6895 	struct tcpm_port *port = typec_get_drvdata(p);
6896 	struct pd_data *data;
6897 	int i, ret = 0;
6898 
6899 	mutex_lock(&port->lock);
6900 
6901 	if (port->selected_pd == pd)
6902 		goto unlock;
6903 
6904 	data = tcpm_find_pd_data(port, pd);
6905 	if (IS_ERR(data)) {
6906 		ret = PTR_ERR(data);
6907 		goto unlock;
6908 	}
6909 
6910 	if (data->sink_desc.pdo[0]) {
6911 		for (i = 0; i < PDO_MAX_OBJECTS && data->sink_desc.pdo[i]; i++)
6912 			port->snk_pdo[i] = data->sink_desc.pdo[i];
6913 		port->nr_snk_pdo = i;
6914 		port->operating_snk_mw = data->operating_snk_mw;
6915 	}
6916 
6917 	if (data->source_desc.pdo[0]) {
6918 		for (i = 0; i < PDO_MAX_OBJECTS && data->source_desc.pdo[i]; i++)
6919 			port->src_pdo[i] = data->source_desc.pdo[i];
6920 		port->nr_src_pdo = i;
6921 	}
6922 
6923 	switch (port->state) {
6924 	case SRC_UNATTACHED:
6925 	case SRC_ATTACH_WAIT:
6926 	case SRC_TRYWAIT:
6927 		tcpm_set_cc(port, tcpm_rp_cc(port));
6928 		break;
6929 	case SRC_SEND_CAPABILITIES:
6930 	case SRC_SEND_CAPABILITIES_TIMEOUT:
6931 	case SRC_NEGOTIATE_CAPABILITIES:
6932 	case SRC_READY:
6933 	case SRC_WAIT_NEW_CAPABILITIES:
6934 		port->caps_count = 0;
6935 		port->upcoming_state = SRC_SEND_CAPABILITIES;
6936 		ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6937 		if (ret == -EAGAIN) {
6938 			port->upcoming_state = INVALID_STATE;
6939 			goto unlock;
6940 		}
6941 		break;
6942 	case SNK_NEGOTIATE_CAPABILITIES:
6943 	case SNK_NEGOTIATE_PPS_CAPABILITIES:
6944 	case SNK_READY:
6945 	case SNK_TRANSITION_SINK:
6946 	case SNK_TRANSITION_SINK_VBUS:
6947 		if (port->pps_data.active)
6948 			port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
6949 		else if (port->pd_capable)
6950 			port->upcoming_state = SNK_NEGOTIATE_CAPABILITIES;
6951 		else
6952 			break;
6953 
6954 		port->update_sink_caps = true;
6955 
6956 		ret = tcpm_ams_start(port, POWER_NEGOTIATION);
6957 		if (ret == -EAGAIN) {
6958 			port->upcoming_state = INVALID_STATE;
6959 			goto unlock;
6960 		}
6961 		break;
6962 	default:
6963 		break;
6964 	}
6965 
6966 	port->port_source_caps = data->source_cap;
6967 	port->port_sink_caps = data->sink_cap;
6968 	typec_port_set_usb_power_delivery(p, NULL);
6969 	port->selected_pd = pd;
6970 	typec_port_set_usb_power_delivery(p, port->selected_pd);
6971 unlock:
6972 	mutex_unlock(&port->lock);
6973 	return ret;
6974 }
6975 
6976 static const struct typec_operations tcpm_ops = {
6977 	.try_role = tcpm_try_role,
6978 	.dr_set = tcpm_dr_set,
6979 	.pr_set = tcpm_pr_set,
6980 	.vconn_set = tcpm_vconn_set,
6981 	.port_type_set = tcpm_port_type_set,
6982 	.pd_get = tcpm_pd_get,
6983 	.pd_set = tcpm_pd_set
6984 };
6985 
tcpm_tcpc_reset(struct tcpm_port * port)6986 void tcpm_tcpc_reset(struct tcpm_port *port)
6987 {
6988 	mutex_lock(&port->lock);
6989 	/* XXX: Maintain PD connection if possible? */
6990 	tcpm_init(port);
6991 	mutex_unlock(&port->lock);
6992 }
6993 EXPORT_SYMBOL_GPL(tcpm_tcpc_reset);
6994 
tcpm_port_unregister_pd(struct tcpm_port * port)6995 static void tcpm_port_unregister_pd(struct tcpm_port *port)
6996 {
6997 	int i;
6998 
6999 	port->port_sink_caps = NULL;
7000 	port->port_source_caps = NULL;
7001 	for (i = 0; i < port->pd_count; i++) {
7002 		usb_power_delivery_unregister_capabilities(port->pd_list[i]->sink_cap);
7003 		usb_power_delivery_unregister_capabilities(port->pd_list[i]->source_cap);
7004 		devm_kfree(port->dev, port->pd_list[i]);
7005 		port->pd_list[i] = NULL;
7006 		usb_power_delivery_unregister(port->pds[i]);
7007 		port->pds[i] = NULL;
7008 	}
7009 }
7010 
tcpm_port_register_pd(struct tcpm_port * port)7011 static int tcpm_port_register_pd(struct tcpm_port *port)
7012 {
7013 	struct usb_power_delivery_desc desc = { port->typec_caps.pd_revision };
7014 	struct usb_power_delivery_capabilities *cap;
7015 	int ret, i;
7016 
7017 	if (!port->nr_src_pdo && !port->nr_snk_pdo)
7018 		return 0;
7019 
7020 	for (i = 0; i < port->pd_count; i++) {
7021 		port->pds[i] = usb_power_delivery_register(port->dev, &desc);
7022 		if (IS_ERR(port->pds[i])) {
7023 			ret = PTR_ERR(port->pds[i]);
7024 			goto err_unregister;
7025 		}
7026 		port->pd_list[i]->pd = port->pds[i];
7027 
7028 		if (port->pd_list[i]->source_desc.pdo[0]) {
7029 			cap = usb_power_delivery_register_capabilities(port->pds[i],
7030 								&port->pd_list[i]->source_desc);
7031 			if (IS_ERR(cap)) {
7032 				ret = PTR_ERR(cap);
7033 				goto err_unregister;
7034 			}
7035 			port->pd_list[i]->source_cap = cap;
7036 		}
7037 
7038 		if (port->pd_list[i]->sink_desc.pdo[0]) {
7039 			cap = usb_power_delivery_register_capabilities(port->pds[i],
7040 								&port->pd_list[i]->sink_desc);
7041 			if (IS_ERR(cap)) {
7042 				ret = PTR_ERR(cap);
7043 				goto err_unregister;
7044 			}
7045 			port->pd_list[i]->sink_cap = cap;
7046 		}
7047 	}
7048 
7049 	port->port_source_caps = port->pd_list[0]->source_cap;
7050 	port->port_sink_caps = port->pd_list[0]->sink_cap;
7051 	port->selected_pd = port->pds[0];
7052 	return 0;
7053 
7054 err_unregister:
7055 	tcpm_port_unregister_pd(port);
7056 
7057 	return ret;
7058 }
7059 
tcpm_fw_get_caps(struct tcpm_port * port,struct fwnode_handle * fwnode)7060 static int tcpm_fw_get_caps(struct tcpm_port *port, struct fwnode_handle *fwnode)
7061 {
7062 	struct fwnode_handle *capabilities, *child, *caps = NULL;
7063 	unsigned int nr_src_pdo, nr_snk_pdo;
7064 	const char *opmode_str;
7065 	u32 *src_pdo, *snk_pdo;
7066 	u32 uw, frs_current;
7067 	int ret = 0, i;
7068 	int mode;
7069 
7070 	if (!fwnode)
7071 		return -EINVAL;
7072 
7073 	/*
7074 	 * This fwnode has a "compatible" property, but is never populated as a
7075 	 * struct device. Instead we simply parse it to read the properties.
7076 	 * This it breaks fw_devlink=on. To maintain backward compatibility
7077 	 * with existing DT files, we work around this by deleting any
7078 	 * fwnode_links to/from this fwnode.
7079 	 */
7080 	fw_devlink_purge_absent_suppliers(fwnode);
7081 
7082 	ret = typec_get_fw_cap(&port->typec_caps, fwnode);
7083 	if (ret < 0)
7084 		return ret;
7085 
7086 	mode = 0;
7087 
7088 	if (fwnode_property_read_bool(fwnode, "accessory-mode-audio"))
7089 		port->typec_caps.accessory[mode++] = TYPEC_ACCESSORY_AUDIO;
7090 
7091 	if (fwnode_property_read_bool(fwnode, "accessory-mode-debug"))
7092 		port->typec_caps.accessory[mode++] = TYPEC_ACCESSORY_DEBUG;
7093 
7094 	port->port_type = port->typec_caps.type;
7095 	port->pd_supported = !fwnode_property_read_bool(fwnode, "pd-disable");
7096 	port->slow_charger_loop = fwnode_property_read_bool(fwnode, "slow-charger-loop");
7097 	port->self_powered = fwnode_property_read_bool(fwnode, "self-powered");
7098 
7099 	if (!port->pd_supported) {
7100 		ret = fwnode_property_read_string(fwnode, "typec-power-opmode", &opmode_str);
7101 		if (ret)
7102 			return ret;
7103 		ret = typec_find_pwr_opmode(opmode_str);
7104 		if (ret < 0)
7105 			return ret;
7106 		port->src_rp = tcpm_pwr_opmode_to_rp(ret);
7107 		return 0;
7108 	}
7109 
7110 	/* The following code are applicable to pd-capable ports, i.e. pd_supported is true. */
7111 
7112 	/* FRS can only be supported by DRP ports */
7113 	if (port->port_type == TYPEC_PORT_DRP) {
7114 		ret = fwnode_property_read_u32(fwnode, "new-source-frs-typec-current",
7115 					       &frs_current);
7116 		if (!ret && frs_current <= FRS_5V_3A)
7117 			port->new_source_frs_current = frs_current;
7118 
7119 		if (ret)
7120 			ret = 0;
7121 	}
7122 
7123 	/* For the backward compatibility, "capabilities" node is optional. */
7124 	capabilities = fwnode_get_named_child_node(fwnode, "capabilities");
7125 	if (!capabilities) {
7126 		port->pd_count = 1;
7127 	} else {
7128 		fwnode_for_each_child_node(capabilities, child)
7129 			port->pd_count++;
7130 
7131 		if (!port->pd_count) {
7132 			ret = -ENODATA;
7133 			goto put_capabilities;
7134 		}
7135 	}
7136 
7137 	port->pds = devm_kcalloc(port->dev, port->pd_count, sizeof(struct usb_power_delivery *),
7138 				 GFP_KERNEL);
7139 	if (!port->pds) {
7140 		ret = -ENOMEM;
7141 		goto put_capabilities;
7142 	}
7143 
7144 	port->pd_list = devm_kcalloc(port->dev, port->pd_count, sizeof(struct pd_data *),
7145 				     GFP_KERNEL);
7146 	if (!port->pd_list) {
7147 		ret = -ENOMEM;
7148 		goto put_capabilities;
7149 	}
7150 
7151 	for (i = 0; i < port->pd_count; i++) {
7152 		port->pd_list[i] = devm_kzalloc(port->dev, sizeof(struct pd_data), GFP_KERNEL);
7153 		if (!port->pd_list[i]) {
7154 			ret = -ENOMEM;
7155 			goto put_capabilities;
7156 		}
7157 
7158 		src_pdo = port->pd_list[i]->source_desc.pdo;
7159 		port->pd_list[i]->source_desc.role = TYPEC_SOURCE;
7160 		snk_pdo = port->pd_list[i]->sink_desc.pdo;
7161 		port->pd_list[i]->sink_desc.role = TYPEC_SINK;
7162 
7163 		/* If "capabilities" is NULL, fall back to single pd cap population. */
7164 		if (!capabilities)
7165 			caps = fwnode;
7166 		else
7167 			caps = fwnode_get_next_child_node(capabilities, caps);
7168 
7169 		if (port->port_type != TYPEC_PORT_SNK) {
7170 			ret = fwnode_property_count_u32(caps, "source-pdos");
7171 			if (ret == 0) {
7172 				ret = -EINVAL;
7173 				goto put_caps;
7174 			}
7175 			if (ret < 0)
7176 				goto put_caps;
7177 
7178 			nr_src_pdo = min(ret, PDO_MAX_OBJECTS);
7179 			ret = fwnode_property_read_u32_array(caps, "source-pdos", src_pdo,
7180 							     nr_src_pdo);
7181 			if (ret)
7182 				goto put_caps;
7183 
7184 			ret = tcpm_validate_caps(port, src_pdo, nr_src_pdo);
7185 			if (ret)
7186 				goto put_caps;
7187 
7188 			if (i == 0) {
7189 				port->nr_src_pdo = nr_src_pdo;
7190 				memcpy_and_pad(port->src_pdo, sizeof(u32) * PDO_MAX_OBJECTS,
7191 					       port->pd_list[0]->source_desc.pdo,
7192 					       sizeof(u32) * nr_src_pdo,
7193 					       0);
7194 			}
7195 		}
7196 
7197 		if (port->port_type != TYPEC_PORT_SRC) {
7198 			ret = fwnode_property_count_u32(caps, "sink-pdos");
7199 			if (ret == 0) {
7200 				ret = -EINVAL;
7201 				goto put_caps;
7202 			}
7203 
7204 			if (ret < 0)
7205 				goto put_caps;
7206 
7207 			nr_snk_pdo = min(ret, PDO_MAX_OBJECTS);
7208 			ret = fwnode_property_read_u32_array(caps, "sink-pdos", snk_pdo,
7209 							     nr_snk_pdo);
7210 			if (ret)
7211 				goto put_caps;
7212 
7213 			ret = tcpm_validate_caps(port, snk_pdo, nr_snk_pdo);
7214 			if (ret)
7215 				goto put_caps;
7216 
7217 			if (fwnode_property_read_u32(caps, "op-sink-microwatt", &uw) < 0) {
7218 				ret = -EINVAL;
7219 				goto put_caps;
7220 			}
7221 
7222 			port->pd_list[i]->operating_snk_mw = uw / 1000;
7223 
7224 			if (i == 0) {
7225 				port->nr_snk_pdo = nr_snk_pdo;
7226 				memcpy_and_pad(port->snk_pdo, sizeof(u32) * PDO_MAX_OBJECTS,
7227 					       port->pd_list[0]->sink_desc.pdo,
7228 					       sizeof(u32) * nr_snk_pdo,
7229 					       0);
7230 				port->operating_snk_mw = port->pd_list[0]->operating_snk_mw;
7231 			}
7232 		}
7233 	}
7234 
7235 put_caps:
7236 	if (caps != fwnode)
7237 		fwnode_handle_put(caps);
7238 put_capabilities:
7239 	fwnode_handle_put(capabilities);
7240 	return ret;
7241 }
7242 
tcpm_fw_get_snk_vdos(struct tcpm_port * port,struct fwnode_handle * fwnode)7243 static int tcpm_fw_get_snk_vdos(struct tcpm_port *port, struct fwnode_handle *fwnode)
7244 {
7245 	int ret;
7246 
7247 	/* sink-vdos is optional */
7248 	ret = fwnode_property_count_u32(fwnode, "sink-vdos");
7249 	if (ret < 0)
7250 		return 0;
7251 
7252 	port->nr_snk_vdo = min(ret, VDO_MAX_OBJECTS);
7253 	if (port->nr_snk_vdo) {
7254 		ret = fwnode_property_read_u32_array(fwnode, "sink-vdos",
7255 						     port->snk_vdo,
7256 						     port->nr_snk_vdo);
7257 		if (ret < 0)
7258 			return ret;
7259 	}
7260 
7261 	/* If sink-vdos is found, sink-vdos-v1 is expected for backward compatibility. */
7262 	if (port->nr_snk_vdo) {
7263 		ret = fwnode_property_count_u32(fwnode, "sink-vdos-v1");
7264 		if (ret < 0)
7265 			return ret;
7266 		else if (ret == 0)
7267 			return -ENODATA;
7268 
7269 		port->nr_snk_vdo_v1 = min(ret, VDO_MAX_OBJECTS);
7270 		ret = fwnode_property_read_u32_array(fwnode, "sink-vdos-v1",
7271 						     port->snk_vdo_v1,
7272 						     port->nr_snk_vdo_v1);
7273 		if (ret < 0)
7274 			return ret;
7275 	}
7276 
7277 	return 0;
7278 }
7279 
7280 /* Power Supply access to expose source power information */
7281 enum tcpm_psy_online_states {
7282 	TCPM_PSY_OFFLINE = 0,
7283 	TCPM_PSY_FIXED_ONLINE,
7284 	TCPM_PSY_PROG_ONLINE,
7285 };
7286 
7287 static enum power_supply_property tcpm_psy_props[] = {
7288 	POWER_SUPPLY_PROP_USB_TYPE,
7289 	POWER_SUPPLY_PROP_ONLINE,
7290 	POWER_SUPPLY_PROP_VOLTAGE_MIN,
7291 	POWER_SUPPLY_PROP_VOLTAGE_MAX,
7292 	POWER_SUPPLY_PROP_VOLTAGE_NOW,
7293 	POWER_SUPPLY_PROP_CURRENT_MAX,
7294 	POWER_SUPPLY_PROP_CURRENT_NOW,
7295 };
7296 
tcpm_psy_get_online(struct tcpm_port * port,union power_supply_propval * val)7297 static int tcpm_psy_get_online(struct tcpm_port *port,
7298 			       union power_supply_propval *val)
7299 {
7300 	if (port->vbus_charge) {
7301 		if (port->pps_data.active)
7302 			val->intval = TCPM_PSY_PROG_ONLINE;
7303 		else
7304 			val->intval = TCPM_PSY_FIXED_ONLINE;
7305 	} else {
7306 		val->intval = TCPM_PSY_OFFLINE;
7307 	}
7308 
7309 	return 0;
7310 }
7311 
tcpm_psy_get_voltage_min(struct tcpm_port * port,union power_supply_propval * val)7312 static int tcpm_psy_get_voltage_min(struct tcpm_port *port,
7313 				    union power_supply_propval *val)
7314 {
7315 	if (port->pps_data.active)
7316 		val->intval = port->pps_data.min_volt * 1000;
7317 	else
7318 		val->intval = port->supply_voltage * 1000;
7319 
7320 	return 0;
7321 }
7322 
tcpm_psy_get_voltage_max(struct tcpm_port * port,union power_supply_propval * val)7323 static int tcpm_psy_get_voltage_max(struct tcpm_port *port,
7324 				    union power_supply_propval *val)
7325 {
7326 	if (port->pps_data.active)
7327 		val->intval = port->pps_data.max_volt * 1000;
7328 	else
7329 		val->intval = port->supply_voltage * 1000;
7330 
7331 	return 0;
7332 }
7333 
tcpm_psy_get_voltage_now(struct tcpm_port * port,union power_supply_propval * val)7334 static int tcpm_psy_get_voltage_now(struct tcpm_port *port,
7335 				    union power_supply_propval *val)
7336 {
7337 	val->intval = port->supply_voltage * 1000;
7338 
7339 	return 0;
7340 }
7341 
tcpm_psy_get_current_max(struct tcpm_port * port,union power_supply_propval * val)7342 static int tcpm_psy_get_current_max(struct tcpm_port *port,
7343 				    union power_supply_propval *val)
7344 {
7345 	if (port->pps_data.active)
7346 		val->intval = port->pps_data.max_curr * 1000;
7347 	else
7348 		val->intval = port->current_limit * 1000;
7349 
7350 	return 0;
7351 }
7352 
tcpm_psy_get_current_now(struct tcpm_port * port,union power_supply_propval * val)7353 static int tcpm_psy_get_current_now(struct tcpm_port *port,
7354 				    union power_supply_propval *val)
7355 {
7356 	val->intval = port->current_limit * 1000;
7357 
7358 	return 0;
7359 }
7360 
tcpm_psy_get_input_power_limit(struct tcpm_port * port,union power_supply_propval * val)7361 static int tcpm_psy_get_input_power_limit(struct tcpm_port *port,
7362 					  union power_supply_propval *val)
7363 {
7364 	unsigned int src_mv, src_ma, max_src_uw = 0;
7365 	unsigned int i, tmp;
7366 
7367 	for (i = 0; i < port->nr_source_caps; i++) {
7368 		u32 pdo = port->source_caps[i];
7369 
7370 		if (pdo_type(pdo) == PDO_TYPE_FIXED) {
7371 			src_mv = pdo_fixed_voltage(pdo);
7372 			src_ma = pdo_max_current(pdo);
7373 			tmp = src_mv * src_ma;
7374 			max_src_uw = tmp > max_src_uw ? tmp : max_src_uw;
7375 		}
7376 	}
7377 
7378 	val->intval = max_src_uw;
7379 	return 0;
7380 }
7381 
tcpm_psy_get_prop(struct power_supply * psy,enum power_supply_property psp,union power_supply_propval * val)7382 static int tcpm_psy_get_prop(struct power_supply *psy,
7383 			     enum power_supply_property psp,
7384 			     union power_supply_propval *val)
7385 {
7386 	struct tcpm_port *port = power_supply_get_drvdata(psy);
7387 	int ret = 0;
7388 
7389 	switch (psp) {
7390 	case POWER_SUPPLY_PROP_USB_TYPE:
7391 		val->intval = port->usb_type;
7392 		break;
7393 	case POWER_SUPPLY_PROP_ONLINE:
7394 		ret = tcpm_psy_get_online(port, val);
7395 		break;
7396 	case POWER_SUPPLY_PROP_VOLTAGE_MIN:
7397 		ret = tcpm_psy_get_voltage_min(port, val);
7398 		break;
7399 	case POWER_SUPPLY_PROP_VOLTAGE_MAX:
7400 		ret = tcpm_psy_get_voltage_max(port, val);
7401 		break;
7402 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
7403 		ret = tcpm_psy_get_voltage_now(port, val);
7404 		break;
7405 	case POWER_SUPPLY_PROP_CURRENT_MAX:
7406 		ret = tcpm_psy_get_current_max(port, val);
7407 		break;
7408 	case POWER_SUPPLY_PROP_CURRENT_NOW:
7409 		ret = tcpm_psy_get_current_now(port, val);
7410 		break;
7411 	case POWER_SUPPLY_PROP_INPUT_POWER_LIMIT:
7412 		tcpm_psy_get_input_power_limit(port, val);
7413 		break;
7414 	default:
7415 		ret = -EINVAL;
7416 		break;
7417 	}
7418 
7419 	return ret;
7420 }
7421 
tcpm_psy_set_online(struct tcpm_port * port,const union power_supply_propval * val)7422 static int tcpm_psy_set_online(struct tcpm_port *port,
7423 			       const union power_supply_propval *val)
7424 {
7425 	int ret;
7426 
7427 	switch (val->intval) {
7428 	case TCPM_PSY_FIXED_ONLINE:
7429 		ret = tcpm_pps_activate(port, false);
7430 		break;
7431 	case TCPM_PSY_PROG_ONLINE:
7432 		ret = tcpm_pps_activate(port, true);
7433 		break;
7434 	default:
7435 		ret = -EINVAL;
7436 		break;
7437 	}
7438 
7439 	return ret;
7440 }
7441 
tcpm_psy_set_prop(struct power_supply * psy,enum power_supply_property psp,const union power_supply_propval * val)7442 static int tcpm_psy_set_prop(struct power_supply *psy,
7443 			     enum power_supply_property psp,
7444 			     const union power_supply_propval *val)
7445 {
7446 	struct tcpm_port *port = power_supply_get_drvdata(psy);
7447 	int ret;
7448 
7449 	/*
7450 	 * All the properties below are related to USB PD. The check needs to be
7451 	 * property specific when a non-pd related property is added.
7452 	 */
7453 	if (!port->pd_supported)
7454 		return -EOPNOTSUPP;
7455 
7456 	switch (psp) {
7457 	case POWER_SUPPLY_PROP_ONLINE:
7458 		ret = tcpm_psy_set_online(port, val);
7459 		break;
7460 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
7461 		ret = tcpm_pps_set_out_volt(port, val->intval / 1000);
7462 		break;
7463 	case POWER_SUPPLY_PROP_CURRENT_NOW:
7464 		if (val->intval > port->pps_data.max_curr * 1000)
7465 			ret = -EINVAL;
7466 		else
7467 			ret = tcpm_pps_set_op_curr(port, val->intval / 1000);
7468 		break;
7469 	default:
7470 		ret = -EINVAL;
7471 		break;
7472 	}
7473 	power_supply_changed(port->psy);
7474 	return ret;
7475 }
7476 
tcpm_psy_prop_writeable(struct power_supply * psy,enum power_supply_property psp)7477 static int tcpm_psy_prop_writeable(struct power_supply *psy,
7478 				   enum power_supply_property psp)
7479 {
7480 	switch (psp) {
7481 	case POWER_SUPPLY_PROP_ONLINE:
7482 	case POWER_SUPPLY_PROP_VOLTAGE_NOW:
7483 	case POWER_SUPPLY_PROP_CURRENT_NOW:
7484 		return 1;
7485 	default:
7486 		return 0;
7487 	}
7488 }
7489 
7490 static const char *tcpm_psy_name_prefix = "tcpm-source-psy-";
7491 
devm_tcpm_psy_register(struct tcpm_port * port)7492 static int devm_tcpm_psy_register(struct tcpm_port *port)
7493 {
7494 	struct power_supply_config psy_cfg = {};
7495 	const char *port_dev_name = dev_name(port->dev);
7496 	size_t psy_name_len = strlen(tcpm_psy_name_prefix) +
7497 				     strlen(port_dev_name) + 1;
7498 	char *psy_name;
7499 
7500 	psy_cfg.drv_data = port;
7501 	psy_cfg.fwnode = dev_fwnode(port->dev);
7502 	psy_name = devm_kzalloc(port->dev, psy_name_len, GFP_KERNEL);
7503 	if (!psy_name)
7504 		return -ENOMEM;
7505 
7506 	snprintf(psy_name, psy_name_len, "%s%s", tcpm_psy_name_prefix,
7507 		 port_dev_name);
7508 	port->psy_desc.name = psy_name;
7509 	port->psy_desc.type = POWER_SUPPLY_TYPE_USB;
7510 	port->psy_desc.usb_types = BIT(POWER_SUPPLY_USB_TYPE_C)  |
7511 				   BIT(POWER_SUPPLY_USB_TYPE_PD) |
7512 				   BIT(POWER_SUPPLY_USB_TYPE_PD_PPS);
7513 	port->psy_desc.properties = tcpm_psy_props;
7514 	port->psy_desc.num_properties = ARRAY_SIZE(tcpm_psy_props);
7515 	port->psy_desc.get_property = tcpm_psy_get_prop;
7516 	port->psy_desc.set_property = tcpm_psy_set_prop;
7517 	port->psy_desc.property_is_writeable = tcpm_psy_prop_writeable;
7518 
7519 	port->usb_type = POWER_SUPPLY_USB_TYPE_C;
7520 
7521 	port->psy = devm_power_supply_register(port->dev, &port->psy_desc,
7522 					       &psy_cfg);
7523 
7524 	return PTR_ERR_OR_ZERO(port->psy);
7525 }
7526 
state_machine_timer_handler(struct hrtimer * timer)7527 static enum hrtimer_restart state_machine_timer_handler(struct hrtimer *timer)
7528 {
7529 	struct tcpm_port *port = container_of(timer, struct tcpm_port, state_machine_timer);
7530 
7531 	if (port->registered)
7532 		kthread_queue_work(port->wq, &port->state_machine);
7533 	return HRTIMER_NORESTART;
7534 }
7535 
vdm_state_machine_timer_handler(struct hrtimer * timer)7536 static enum hrtimer_restart vdm_state_machine_timer_handler(struct hrtimer *timer)
7537 {
7538 	struct tcpm_port *port = container_of(timer, struct tcpm_port, vdm_state_machine_timer);
7539 
7540 	if (port->registered)
7541 		kthread_queue_work(port->wq, &port->vdm_state_machine);
7542 	return HRTIMER_NORESTART;
7543 }
7544 
enable_frs_timer_handler(struct hrtimer * timer)7545 static enum hrtimer_restart enable_frs_timer_handler(struct hrtimer *timer)
7546 {
7547 	struct tcpm_port *port = container_of(timer, struct tcpm_port, enable_frs_timer);
7548 
7549 	if (port->registered)
7550 		kthread_queue_work(port->wq, &port->enable_frs);
7551 	return HRTIMER_NORESTART;
7552 }
7553 
send_discover_timer_handler(struct hrtimer * timer)7554 static enum hrtimer_restart send_discover_timer_handler(struct hrtimer *timer)
7555 {
7556 	struct tcpm_port *port = container_of(timer, struct tcpm_port, send_discover_timer);
7557 
7558 	if (port->registered)
7559 		kthread_queue_work(port->wq, &port->send_discover_work);
7560 	return HRTIMER_NORESTART;
7561 }
7562 
tcpm_register_port(struct device * dev,struct tcpc_dev * tcpc)7563 struct tcpm_port *tcpm_register_port(struct device *dev, struct tcpc_dev *tcpc)
7564 {
7565 	struct tcpm_port *port;
7566 	int err;
7567 
7568 	if (!dev || !tcpc ||
7569 	    !tcpc->get_vbus || !tcpc->set_cc || !tcpc->get_cc ||
7570 	    !tcpc->set_polarity || !tcpc->set_vconn || !tcpc->set_vbus ||
7571 	    !tcpc->set_pd_rx || !tcpc->set_roles || !tcpc->pd_transmit)
7572 		return ERR_PTR(-EINVAL);
7573 
7574 	port = devm_kzalloc(dev, sizeof(*port), GFP_KERNEL);
7575 	if (!port)
7576 		return ERR_PTR(-ENOMEM);
7577 
7578 	port->dev = dev;
7579 	port->tcpc = tcpc;
7580 
7581 	mutex_init(&port->lock);
7582 	mutex_init(&port->swap_lock);
7583 
7584 	port->wq = kthread_create_worker(0, dev_name(dev));
7585 	if (IS_ERR(port->wq))
7586 		return ERR_CAST(port->wq);
7587 	sched_set_fifo(port->wq->task);
7588 
7589 	kthread_init_work(&port->state_machine, tcpm_state_machine_work);
7590 	kthread_init_work(&port->vdm_state_machine, vdm_state_machine_work);
7591 	kthread_init_work(&port->event_work, tcpm_pd_event_handler);
7592 	kthread_init_work(&port->enable_frs, tcpm_enable_frs_work);
7593 	kthread_init_work(&port->send_discover_work, tcpm_send_discover_work);
7594 	hrtimer_init(&port->state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7595 	port->state_machine_timer.function = state_machine_timer_handler;
7596 	hrtimer_init(&port->vdm_state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7597 	port->vdm_state_machine_timer.function = vdm_state_machine_timer_handler;
7598 	hrtimer_init(&port->enable_frs_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7599 	port->enable_frs_timer.function = enable_frs_timer_handler;
7600 	hrtimer_init(&port->send_discover_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7601 	port->send_discover_timer.function = send_discover_timer_handler;
7602 
7603 	spin_lock_init(&port->pd_event_lock);
7604 
7605 	init_completion(&port->tx_complete);
7606 	init_completion(&port->swap_complete);
7607 	init_completion(&port->pps_complete);
7608 	tcpm_debugfs_init(port);
7609 
7610 	err = tcpm_fw_get_caps(port, tcpc->fwnode);
7611 	if (err < 0)
7612 		goto out_destroy_wq;
7613 	err = tcpm_fw_get_snk_vdos(port, tcpc->fwnode);
7614 	if (err < 0)
7615 		goto out_destroy_wq;
7616 
7617 	port->try_role = port->typec_caps.prefer_role;
7618 
7619 	port->typec_caps.revision = 0x0120;	/* Type-C spec release 1.2 */
7620 	port->typec_caps.pd_revision = 0x0300;	/* USB-PD spec release 3.0 */
7621 	port->typec_caps.svdm_version = SVDM_VER_2_0;
7622 	port->typec_caps.driver_data = port;
7623 	port->typec_caps.ops = &tcpm_ops;
7624 	port->typec_caps.orientation_aware = 1;
7625 
7626 	port->partner_desc.identity = &port->partner_ident;
7627 
7628 	port->role_sw = usb_role_switch_get(port->dev);
7629 	if (!port->role_sw)
7630 		port->role_sw = fwnode_usb_role_switch_get(tcpc->fwnode);
7631 	if (IS_ERR(port->role_sw)) {
7632 		err = PTR_ERR(port->role_sw);
7633 		goto out_destroy_wq;
7634 	}
7635 
7636 	err = devm_tcpm_psy_register(port);
7637 	if (err)
7638 		goto out_role_sw_put;
7639 	power_supply_changed(port->psy);
7640 
7641 	err = tcpm_port_register_pd(port);
7642 	if (err)
7643 		goto out_role_sw_put;
7644 
7645 	if (port->pds)
7646 		port->typec_caps.pd = port->pds[0];
7647 
7648 	port->typec_port = typec_register_port(port->dev, &port->typec_caps);
7649 	if (IS_ERR(port->typec_port)) {
7650 		err = PTR_ERR(port->typec_port);
7651 		goto out_unregister_pd;
7652 	}
7653 
7654 	typec_port_register_altmodes(port->typec_port,
7655 				     &tcpm_altmode_ops, port,
7656 				     port->port_altmode, ALTMODE_DISCOVERY_MAX);
7657 	typec_port_register_cable_ops(port->port_altmode, ARRAY_SIZE(port->port_altmode),
7658 				      &tcpm_cable_ops);
7659 	port->registered = true;
7660 
7661 	mutex_lock(&port->lock);
7662 	tcpm_init(port);
7663 	mutex_unlock(&port->lock);
7664 
7665 	tcpm_log(port, "%s: registered", dev_name(dev));
7666 	return port;
7667 
7668 out_unregister_pd:
7669 	tcpm_port_unregister_pd(port);
7670 out_role_sw_put:
7671 	usb_role_switch_put(port->role_sw);
7672 out_destroy_wq:
7673 	tcpm_debugfs_exit(port);
7674 	kthread_destroy_worker(port->wq);
7675 	return ERR_PTR(err);
7676 }
7677 EXPORT_SYMBOL_GPL(tcpm_register_port);
7678 
tcpm_unregister_port(struct tcpm_port * port)7679 void tcpm_unregister_port(struct tcpm_port *port)
7680 {
7681 	int i;
7682 
7683 	port->registered = false;
7684 	kthread_destroy_worker(port->wq);
7685 
7686 	hrtimer_cancel(&port->send_discover_timer);
7687 	hrtimer_cancel(&port->enable_frs_timer);
7688 	hrtimer_cancel(&port->vdm_state_machine_timer);
7689 	hrtimer_cancel(&port->state_machine_timer);
7690 
7691 	tcpm_reset_port(port);
7692 
7693 	tcpm_port_unregister_pd(port);
7694 
7695 	for (i = 0; i < ARRAY_SIZE(port->port_altmode); i++)
7696 		typec_unregister_altmode(port->port_altmode[i]);
7697 	typec_unregister_port(port->typec_port);
7698 	usb_role_switch_put(port->role_sw);
7699 	tcpm_debugfs_exit(port);
7700 }
7701 EXPORT_SYMBOL_GPL(tcpm_unregister_port);
7702 
7703 MODULE_AUTHOR("Guenter Roeck <groeck@chromium.org>");
7704 MODULE_DESCRIPTION("USB Type-C Port Manager");
7705 MODULE_LICENSE("GPL");
7706