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