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