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