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