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