1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright 2015-2017 Google, Inc
5 * USB Power Delivery protocol stack.
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>
34 #include <uapi/linux/sched/types.h>
36 #define FOREACH_STATE(S) \
39 S(CHECK_CONTAMINANT), \
44 S(SRC_SEND_CAPABILITIES), \
45 S(SRC_SEND_CAPABILITIES_TIMEOUT), \
46 S(SRC_NEGOTIATE_CAPABILITIES), \
47 S(SRC_TRANSITION_SUPPLY), \
49 S(SRC_WAIT_NEW_CAPABILITIES), \
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), \
67 S(DEBUG_ACC_ATTACHED), \
68 S(AUDIO_ACC_ATTACHED), \
69 S(AUDIO_ACC_DEBOUNCE), \
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), \
80 S(SRC_SOFT_RESET_WAIT_SNK_TX), \
86 S(DR_SWAP_SEND_TIMEOUT), \
88 S(DR_SWAP_CHANGE_DR), \
92 S(PR_SWAP_SEND_TIMEOUT), \
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), \
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), \
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), \
121 S(SNK_TRY_WAIT_DEBOUNCE), \
122 S(SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS), \
124 S(SRC_TRYWAIT_DEBOUNCE), \
125 S(SRC_TRYWAIT_UNATTACHED), \
129 S(SRC_TRY_DEBOUNCE), \
131 S(SNK_TRYWAIT_DEBOUNCE), \
132 S(SNK_TRYWAIT_VBUS), \
135 S(GET_STATUS_SEND), \
136 S(GET_STATUS_SEND_TIMEOUT), \
137 S(GET_PPS_STATUS_SEND), \
138 S(GET_PPS_STATUS_SEND_TIMEOUT), \
141 S(GET_SINK_CAP_TIMEOUT), \
145 S(PORT_RESET_WAIT_OFF), \
150 #define FOREACH_AMS(S) \
152 S(POWER_NEGOTIATION), \
157 S(GET_SOURCE_CAPABILITIES), \
158 S(GET_SINK_CAPABILITIES), \
159 S(POWER_ROLE_SWAP), \
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), \
170 S(FIRMWARE_UPDATE), \
171 S(DISCOVER_IDENTITY), \
172 S(SOURCE_STARTUP_CABLE_PLUG_DISCOVER_IDENTITY), \
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), \
181 S(UNSTRUCTURED_VDMS), \
182 S(STRUCTURED_VDMS), \
186 #define GENERATE_ENUM(e) e
187 #define GENERATE_STRING(s) #s
190 FOREACH_STATE(GENERATE_ENUM)
193 static const char * const tcpm_states[] = {
194 FOREACH_STATE(GENERATE_STRING)
198 FOREACH_AMS(GENERATE_ENUM)
201 static const char * const tcpm_ams_str[] = {
202 FOREACH_AMS(GENERATE_STRING)
206 VDM_STATE_ERR_BUSY = -3,
207 VDM_STATE_ERR_SEND = -2,
208 VDM_STATE_ERR_TMOUT = -1,
210 /* Anything >0 represents an active state */
213 VDM_STATE_WAIT_RSP_BUSY = 3,
214 VDM_STATE_SEND_MESSAGE = 4,
217 enum pd_msg_request {
221 PD_MSG_CTRL_NOT_SUPP,
222 PD_MSG_DATA_SINK_CAP,
223 PD_MSG_DATA_SOURCE_CAP,
228 ADEV_NOTIFY_USB_AND_QUEUE_VDM,
230 ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL,
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,
239 enum frs_typec_current {
246 /* Events from low level driver */
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)
255 #define LOG_BUFFER_ENTRIES 1024
256 #define LOG_BUFFER_ENTRY_SIZE 128
258 /* Alternate mode support */
260 #define SVID_DISCOVERY_MAX 16
261 #define ALTMODE_DISCOVERY_MAX (SVID_DISCOVERY_MAX * MODE_DISCOVERY_MAX)
263 #define GET_SINK_CAP_RETRY_MS 100
264 #define SEND_DISCOVER_RETRY_MS 100
266 struct pd_mode_data {
267 int svid_index; /* current SVID index */
269 u16 svids[SVID_DISCOVERY_MAX];
270 int altmodes; /* number of alternate modes */
271 struct typec_altmode_desc altmode_desc[ALTMODE_DISCOVERY_MAX];
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
302 struct mutex lock; /* tcpm state machine lock */
303 struct kthread_worker *wq;
305 struct typec_capability typec_caps;
306 struct typec_port *typec_port;
308 struct tcpc_dev *tcpc;
309 struct usb_role_switch *role_sw;
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;
316 struct usb_pd_identity partner_ident;
317 struct typec_partner_desc partner_desc;
318 struct typec_partner *partner;
320 enum typec_cc_status cc_req;
321 enum typec_cc_status src_rp; /* work only if pd_supported == false */
323 enum typec_cc_status cc1;
324 enum typec_cc_status cc2;
325 enum typec_cc_polarity polarity;
331 enum typec_port_type port_type;
334 * Set to true when vbus is greater than VSAFE5V min.
335 * Set to false when vbus falls below vSinkDisconnect max threshold.
340 * Set to true when vbus is less than VSAFE0V max.
341 * Set to false when vbus is greater than VSAFE0V max.
349 /* Set to true when Discover_Identity Command is expected to be sent in Ready states. */
357 enum pd_msg_request queued_message;
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;
366 spinlock_t pd_event_lock;
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. */
382 struct completion tx_complete;
383 enum tcpm_transmit_status tx_status;
385 struct mutex swap_lock; /* swap command lock */
387 bool non_pd_role_swap;
388 struct completion swap_complete;
391 unsigned int negotiated_rev;
392 unsigned int message_id;
393 unsigned int caps_count;
394 unsigned int hard_reset_count;
396 bool explicit_contract;
397 unsigned int rx_msgid;
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;
407 /* Partner capabilities/requests */
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;
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;
424 unsigned int operating_snk_mw;
425 bool update_sink_caps;
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 */
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;
441 /* PD state for Vendor Defined Messages */
442 enum vdm_states vdm_state;
444 /* next Vendor Defined Message to send */
445 u32 vdo_data[VDO_MAX_SIZE];
447 /* VDO to retry if UFP responder replied busy */
451 struct pd_pps_data pps_data;
452 struct completion pps_complete;
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];
461 /* Deadline in jiffies to exit src_try_wait state */
462 unsigned long max_wait;
464 /* port belongs to a self powered device */
468 enum frs_typec_current new_source_frs_current;
470 /* Sink caps have been queried */
473 /* Collision Avoidance and Atomic Message Sequence */
474 enum tcpm_state upcoming_state;
476 enum tcpm_ams next_ams;
479 /* Auto vbus discharge status */
480 bool auto_vbus_discharge_enabled;
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.
487 bool slow_charger_loop;
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
494 bool potential_contaminant;
495 #ifdef CONFIG_DEBUG_FS
496 struct dentry *dentry;
497 struct mutex logbuffer_lock; /* log buffer access lock */
500 u8 *logbuffer[LOG_BUFFER_ENTRIES];
505 struct kthread_work work;
506 struct tcpm_port *port;
507 struct pd_message msg;
510 static const char * const pd_rev[] = {
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)
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)))
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)
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)))
534 #define tcpm_port_is_debug(port) \
535 (tcpm_cc_is_source((port)->cc1) && tcpm_cc_is_source((port)->cc2))
537 #define tcpm_port_is_audio(port) \
538 (tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_audio((port)->cc2))
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)))
544 #define tcpm_try_snk(port) \
545 ((port)->try_snk_count == 0 && (port)->try_role == TYPEC_SINK && \
546 (port)->port_type == TYPEC_PORT_DRP)
548 #define tcpm_try_src(port) \
549 ((port)->try_src_count == 0 && (port)->try_role == TYPEC_SOURCE && \
550 (port)->port_type == TYPEC_PORT_DRP)
552 #define tcpm_data_role_for_source(port) \
553 ((port)->typec_caps.data == TYPEC_PORT_UFP ? \
554 TYPEC_DEVICE : TYPEC_HOST)
556 #define tcpm_data_role_for_sink(port) \
557 ((port)->typec_caps.data == TYPEC_PORT_DFP ? \
558 TYPEC_HOST : TYPEC_DEVICE)
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))
564 #define tcpm_wait_for_discharge(port) \
565 (((port)->auto_vbus_discharge_enabled && !(port)->vbus_vsafe0v) ? PD_T_SAFE_0V : 0)
567 static enum tcpm_state tcpm_default_state(struct tcpm_port *port)
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;
578 return SRC_UNATTACHED;
581 static bool tcpm_port_is_disconnected(struct tcpm_port *port)
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)));
595 #ifdef CONFIG_DEBUG_FS
597 static bool tcpm_log_full(struct tcpm_port *port)
599 return port->logbuffer_tail ==
600 (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
604 static void _tcpm_log(struct tcpm_port *port, const char *fmt, va_list args)
606 char tmpbuffer[LOG_BUFFER_ENTRY_SIZE];
607 u64 ts_nsec = local_clock();
608 unsigned long rem_nsec;
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);
620 vsnprintf(tmpbuffer, sizeof(tmpbuffer), fmt, args);
622 if (tcpm_log_full(port)) {
623 port->logbuffer_head = max(port->logbuffer_head - 1, 0);
624 strcpy(tmpbuffer, "overflow");
627 if (port->logbuffer_head < 0 ||
628 port->logbuffer_head >= LOG_BUFFER_ENTRIES) {
630 "Bad log buffer index %d\n", port->logbuffer_head);
634 if (!port->logbuffer[port->logbuffer_head]) {
636 "Log buffer index %d is NULL\n", port->logbuffer_head);
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,
645 port->logbuffer_head = (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
648 mutex_unlock(&port->logbuffer_lock);
652 static void tcpm_log(struct tcpm_port *port, const char *fmt, ...)
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))
663 _tcpm_log(port, fmt, args);
668 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...)
673 _tcpm_log(port, fmt, args);
677 static void tcpm_log_source_caps(struct tcpm_port *port)
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);
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) ?
694 (pdo & PDO_FIXED_SUSPEND) ?
696 (pdo & PDO_FIXED_HIGHER_CAP) ?
698 (pdo & PDO_FIXED_USB_COMM) ?
700 (pdo & PDO_FIXED_DATA_SWAP) ?
702 (pdo & PDO_FIXED_EXTPOWER) ?
706 scnprintf(msg, sizeof(msg),
708 pdo_min_voltage(pdo),
709 pdo_max_voltage(pdo),
710 pdo_max_current(pdo));
713 scnprintf(msg, sizeof(msg),
715 pdo_min_voltage(pdo),
716 pdo_max_voltage(pdo),
720 if (pdo_apdo_type(pdo) == APDO_TYPE_PPS)
721 scnprintf(msg, sizeof(msg),
723 pdo_pps_apdo_min_voltage(pdo),
724 pdo_pps_apdo_max_voltage(pdo),
725 pdo_pps_apdo_max_current(pdo));
727 strcpy(msg, "undefined APDO");
730 strcpy(msg, "undefined");
733 tcpm_log(port, " PDO %d: type %d, %s",
738 static int tcpm_debug_show(struct seq_file *s, void *v)
740 struct tcpm_port *port = (struct tcpm_port *)s->private;
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;
749 if (!seq_has_overflowed(s))
750 port->logbuffer_tail = tail;
751 mutex_unlock(&port->logbuffer_lock);
755 DEFINE_SHOW_ATTRIBUTE(tcpm_debug);
757 static void tcpm_debugfs_init(struct tcpm_port *port)
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,
768 static void tcpm_debugfs_exit(struct tcpm_port *port)
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;
777 mutex_unlock(&port->logbuffer_lock);
779 debugfs_remove(port->dentry);
785 static void tcpm_log(const struct tcpm_port *port, const char *fmt, ...) { }
787 static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...) { }
788 static void tcpm_log_source_caps(struct tcpm_port *port) { }
789 static void tcpm_debugfs_init(const struct tcpm_port *port) { }
790 static void tcpm_debugfs_exit(const struct tcpm_port *port) { }
794 static void tcpm_set_cc(struct tcpm_port *port, enum typec_cc_status cc)
796 tcpm_log(port, "cc:=%d", cc);
798 port->tcpc->set_cc(port->tcpc, cc);
801 static int tcpm_enable_auto_vbus_discharge(struct tcpm_port *port, bool enable)
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",
810 port->auto_vbus_discharge_enabled = enable;
816 static void tcpm_apply_rc(struct tcpm_port *port)
819 * TCPCI: Move to APPLY_RC state to prevent disconnect during PR_SWAP
820 * when Vbus auto discharge on disconnect is enabled.
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);
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.
834 static enum typec_cc_status tcpm_rp_cc(struct tcpm_port *port)
836 const u32 *src_pdo = port->src_pdo;
837 int nr_pdo = port->nr_src_pdo;
840 if (!port->pd_supported)
844 * Search for first entry with matching voltage.
845 * It should report the maximum supported current.
847 for (i = 0; i < nr_pdo; i++) {
848 const u32 pdo = src_pdo[i];
850 if (pdo_type(pdo) == PDO_TYPE_FIXED &&
851 pdo_fixed_voltage(pdo) == 5000) {
852 unsigned int curr = pdo_max_current(pdo);
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;
862 return TYPEC_CC_RP_DEF;
865 static void tcpm_ams_finish(struct tcpm_port *port)
867 tcpm_log(port, "AMS %s finished", tcpm_ams_str[port->ams]);
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);
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));
878 port->in_ams = false;
879 port->ams = NONE_AMS;
882 static int tcpm_pd_transmit(struct tcpm_port *port,
883 enum tcpm_transmit_type type,
884 const struct pd_message *msg)
886 unsigned long timeout;
890 tcpm_log(port, "PD TX, header: %#x", le16_to_cpu(msg->header));
892 tcpm_log(port, "PD TX, type: %#x", type);
894 reinit_completion(&port->tx_complete);
895 ret = port->tcpc->pd_transmit(port->tcpc, type, msg, port->negotiated_rev);
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);
906 switch (port->tx_status) {
907 case TCPC_TX_SUCCESS:
908 port->message_id = (port->message_id + 1) & PD_HEADER_ID_MASK;
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)."
916 if (port->ams != NONE_AMS)
919 case TCPC_TX_DISCARDED:
928 /* Some AMS don't expect responses. Finish them here. */
929 if (port->ams == ATTENTION || port->ams == SOURCE_ALERT)
930 tcpm_ams_finish(port);
935 void tcpm_pd_transmit_complete(struct tcpm_port *port,
936 enum tcpm_transmit_status status)
938 tcpm_log(port, "PD TX complete, status: %u", status);
939 port->tx_status = status;
940 complete(&port->tx_complete);
942 EXPORT_SYMBOL_GPL(tcpm_pd_transmit_complete);
944 static int tcpm_mux_set(struct tcpm_port *port, int state,
945 enum usb_role usb_role,
946 enum typec_orientation orientation)
950 tcpm_log(port, "Requesting mux state %d, usb-role %d, orientation %d",
951 state, usb_role, orientation);
953 ret = typec_set_orientation(port->typec_port, orientation);
958 ret = usb_role_switch_set_role(port->role_sw, usb_role);
963 return typec_set_mode(port->typec_port, state);
966 static int tcpm_set_polarity(struct tcpm_port *port,
967 enum typec_cc_polarity polarity)
971 tcpm_log(port, "polarity %d", polarity);
973 ret = port->tcpc->set_polarity(port->tcpc, polarity);
977 port->polarity = polarity;
982 static int tcpm_set_vconn(struct tcpm_port *port, bool enable)
986 tcpm_log(port, "vconn:=%d", enable);
988 ret = port->tcpc->set_vconn(port->tcpc, enable);
990 port->vconn_role = enable ? TYPEC_SOURCE : TYPEC_SINK;
991 typec_set_vconn_role(port->typec_port, port->vconn_role);
997 static u32 tcpm_get_current_limit(struct tcpm_port *port)
999 enum typec_cc_status cc;
1002 cc = port->polarity ? port->cc2 : port->cc1;
1004 case TYPEC_CC_RP_1_5:
1007 case TYPEC_CC_RP_3_0:
1010 case TYPEC_CC_RP_DEF:
1012 if (port->tcpc->get_current_limit)
1013 limit = port->tcpc->get_current_limit(port->tcpc);
1022 static int tcpm_set_current_limit(struct tcpm_port *port, u32 max_ma, u32 mv)
1024 int ret = -EOPNOTSUPP;
1026 tcpm_log(port, "Setting voltage/current limit %u mV %u mA", mv, max_ma);
1028 port->supply_voltage = mv;
1029 port->current_limit = max_ma;
1030 power_supply_changed(port->psy);
1032 if (port->tcpc->set_current_limit)
1033 ret = port->tcpc->set_current_limit(port->tcpc, max_ma, mv);
1038 static int tcpm_set_attached_state(struct tcpm_port *port, bool attached)
1040 return port->tcpc->set_roles(port->tcpc, attached, port->pwr_role,
1044 static int tcpm_set_roles(struct tcpm_port *port, bool attached,
1045 enum typec_role role, enum typec_data_role data)
1047 enum typec_orientation orientation;
1048 enum usb_role usb_role;
1051 if (port->polarity == TYPEC_POLARITY_CC1)
1052 orientation = TYPEC_ORIENTATION_NORMAL;
1054 orientation = TYPEC_ORIENTATION_REVERSE;
1056 if (port->typec_caps.data == TYPEC_PORT_DRD) {
1057 if (data == TYPEC_HOST)
1058 usb_role = USB_ROLE_HOST;
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;
1066 usb_role = USB_ROLE_NONE;
1071 if (data == TYPEC_DEVICE) {
1072 if (role == TYPEC_SINK)
1073 usb_role = USB_ROLE_DEVICE;
1075 usb_role = USB_ROLE_NONE;
1081 ret = tcpm_mux_set(port, TYPEC_STATE_USB, usb_role, orientation);
1085 ret = port->tcpc->set_roles(port->tcpc, attached, role, data);
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);
1097 static int tcpm_set_pwr_role(struct tcpm_port *port, enum typec_role role)
1101 ret = port->tcpc->set_roles(port->tcpc, true, role,
1106 port->pwr_role = role;
1107 typec_set_pwr_role(port->typec_port, role);
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.
1117 static u32 tcpm_forge_legacy_pdo(struct tcpm_port *port, u32 pdo, enum typec_role role)
1119 switch (pdo_type(pdo)) {
1120 case PDO_TYPE_FIXED:
1121 if (role == TYPEC_SINK)
1122 return pdo & ~PDO_FIXED_FRS_CURR_MASK;
1124 return pdo & ~PDO_FIXED_UNCHUNK_EXT;
1134 static int tcpm_pd_send_source_caps(struct tcpm_port *port)
1136 struct pd_message msg;
1138 unsigned int i, nr_pdo = 0;
1140 memset(&msg, 0, sizeof(msg));
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]);
1146 pdo = tcpm_forge_legacy_pdo(port, port->src_pdo[i], TYPEC_SOURCE);
1148 msg.payload[nr_pdo++] = cpu_to_le32(pdo);
1153 /* No source capabilities defined, sink only */
1154 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
1157 port->negotiated_rev,
1158 port->message_id, 0);
1160 msg.header = PD_HEADER_LE(PD_DATA_SOURCE_CAP,
1163 port->negotiated_rev,
1168 return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1171 static int tcpm_pd_send_sink_caps(struct tcpm_port *port)
1173 struct pd_message msg;
1175 unsigned int i, nr_pdo = 0;
1177 memset(&msg, 0, sizeof(msg));
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]);
1183 pdo = tcpm_forge_legacy_pdo(port, port->snk_pdo[i], TYPEC_SINK);
1185 msg.payload[nr_pdo++] = cpu_to_le32(pdo);
1190 /* No sink capabilities defined, source only */
1191 msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
1194 port->negotiated_rev,
1195 port->message_id, 0);
1197 msg.header = PD_HEADER_LE(PD_DATA_SINK_CAP,
1200 port->negotiated_rev,
1205 return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1208 static void mod_tcpm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1211 hrtimer_start(&port->state_machine_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1213 hrtimer_cancel(&port->state_machine_timer);
1214 kthread_queue_work(port->wq, &port->state_machine);
1218 static void mod_vdm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1221 hrtimer_start(&port->vdm_state_machine_timer, ms_to_ktime(delay_ms),
1224 hrtimer_cancel(&port->vdm_state_machine_timer);
1225 kthread_queue_work(port->wq, &port->vdm_state_machine);
1229 static void mod_enable_frs_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1232 hrtimer_start(&port->enable_frs_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1234 hrtimer_cancel(&port->enable_frs_timer);
1235 kthread_queue_work(port->wq, &port->enable_frs);
1239 static void mod_send_discover_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1242 hrtimer_start(&port->send_discover_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1244 hrtimer_cancel(&port->send_discover_timer);
1245 kthread_queue_work(port->wq, &port->send_discover_work);
1249 static void tcpm_set_state(struct tcpm_port *port, enum tcpm_state state,
1250 unsigned int 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;
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;
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
1273 if (!port->state_machine_running)
1274 mod_tcpm_delayed_work(port, 0);
1278 static void tcpm_set_state_cond(struct tcpm_port *port, enum tcpm_state state,
1279 unsigned int delay_ms)
1281 if (port->enter_state == port->state)
1282 tcpm_set_state(port, state, delay_ms);
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]);
1292 static void tcpm_queue_message(struct tcpm_port *port,
1293 enum pd_msg_request message)
1295 port->queued_message = message;
1296 mod_tcpm_delayed_work(port, 0);
1299 static bool tcpm_vdm_ams(struct tcpm_port *port)
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:
1311 case UNSTRUCTURED_VDMS:
1312 case STRUCTURED_VDMS:
1321 static bool tcpm_ams_interruptible(struct tcpm_port *port)
1323 switch (port->ams) {
1324 /* Interruptible AMS */
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:
1341 /* Non-Interruptible AMS */
1351 static int tcpm_ams_start(struct tcpm_port *port, enum tcpm_ams ams)
1355 tcpm_log(port, "AMS %s start", tcpm_ams_str[ams]);
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]);
1365 if (port->pwr_role == TYPEC_SOURCE) {
1366 enum typec_cc_status cc_req = port->cc_req;
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);
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);
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);
1387 if (port->negotiated_rev >= PD_REV30)
1388 tcpm_set_cc(port, SINK_TX_NG);
1390 switch (port->state) {
1393 case SRC_SOFT_RESET_WAIT_SNK_TX:
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 ?
1401 tcpm_set_state(port, AMS_START, 0);
1404 if (port->negotiated_rev >= PD_REV30)
1405 tcpm_set_state(port, SRC_READY,
1406 cc_req == SINK_TX_OK ?
1409 tcpm_set_state(port, SRC_READY, 0);
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");
1424 if (ams == HARD_RESET) {
1425 tcpm_pd_transmit(port, TCPC_TX_HARD_RESET, NULL);
1426 tcpm_set_state(port, HARD_RESET_START, 0);
1428 } else if (tcpm_vdm_ams(port)) {
1432 if (port->state == SNK_READY ||
1433 port->state == SNK_SOFT_RESET)
1434 tcpm_set_state(port, AMS_START, 0);
1436 tcpm_set_state(port, SNK_READY, 0);
1443 * VDM/VDO handling functions
1445 static void tcpm_queue_vdm(struct tcpm_port *port, const u32 header,
1446 const u32 *data, int cnt)
1448 WARN_ON(!mutex_is_locked(&port->lock));
1450 /* Make sure we are not still processing a previous VDM packet */
1451 WARN_ON(port->vdm_state > VDM_STATE_DONE);
1453 port->vdo_count = cnt + 1;
1454 port->vdo_data[0] = header;
1455 memcpy(&port->vdo_data[1], data, sizeof(u32) * cnt);
1456 /* Set ready, vdm state machine will actually send */
1457 port->vdm_retries = 0;
1458 port->vdm_state = VDM_STATE_READY;
1459 port->vdm_sm_running = true;
1461 mod_vdm_delayed_work(port, 0);
1464 static void tcpm_queue_vdm_unlocked(struct tcpm_port *port, const u32 header,
1465 const u32 *data, int cnt)
1467 mutex_lock(&port->lock);
1468 tcpm_queue_vdm(port, header, data, cnt);
1469 mutex_unlock(&port->lock);
1472 static void svdm_consume_identity(struct tcpm_port *port, const u32 *p, int cnt)
1474 u32 vdo = p[VDO_INDEX_IDH];
1475 u32 product = p[VDO_INDEX_PRODUCT];
1477 memset(&port->mode_data, 0, sizeof(port->mode_data));
1479 port->partner_ident.id_header = vdo;
1480 port->partner_ident.cert_stat = p[VDO_INDEX_CSTAT];
1481 port->partner_ident.product = product;
1483 typec_partner_set_identity(port->partner);
1485 tcpm_log(port, "Identity: %04x:%04x.%04x",
1487 PD_PRODUCT_PID(product), product & 0xffff);
1490 static bool svdm_consume_svids(struct tcpm_port *port, const u32 *p, int cnt)
1492 struct pd_mode_data *pmdata = &port->mode_data;
1495 for (i = 1; i < cnt; i++) {
1498 svid = (p[i] >> 16) & 0xffff;
1502 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1505 pmdata->svids[pmdata->nsvids++] = svid;
1506 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1508 svid = p[i] & 0xffff;
1512 if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1515 pmdata->svids[pmdata->nsvids++] = svid;
1516 tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1520 tcpm_log(port, "SVID_DISCOVERY_MAX(%d) too low!", SVID_DISCOVERY_MAX);
1524 static void svdm_consume_modes(struct tcpm_port *port, const u32 *p, int cnt)
1526 struct pd_mode_data *pmdata = &port->mode_data;
1527 struct typec_altmode_desc *paltmode;
1530 if (pmdata->altmodes >= ARRAY_SIZE(port->partner_altmode)) {
1531 /* Already logged in svdm_consume_svids() */
1535 for (i = 1; i < cnt; i++) {
1536 paltmode = &pmdata->altmode_desc[pmdata->altmodes];
1537 memset(paltmode, 0, sizeof(*paltmode));
1539 paltmode->svid = pmdata->svids[pmdata->svid_index];
1541 paltmode->vdo = p[i];
1543 tcpm_log(port, " Alternate mode %d: SVID 0x%04x, VDO %d: 0x%08x",
1544 pmdata->altmodes, paltmode->svid,
1545 paltmode->mode, paltmode->vdo);
1551 static void tcpm_register_partner_altmodes(struct tcpm_port *port)
1553 struct pd_mode_data *modep = &port->mode_data;
1554 struct typec_altmode *altmode;
1557 for (i = 0; i < modep->altmodes; i++) {
1558 altmode = typec_partner_register_altmode(port->partner,
1559 &modep->altmode_desc[i]);
1560 if (IS_ERR(altmode)) {
1561 tcpm_log(port, "Failed to register partner SVID 0x%04x",
1562 modep->altmode_desc[i].svid);
1565 port->partner_altmode[i] = altmode;
1569 #define supports_modal(port) PD_IDH_MODAL_SUPP((port)->partner_ident.id_header)
1571 static int tcpm_pd_svdm(struct tcpm_port *port, struct typec_altmode *adev,
1572 const u32 *p, int cnt, u32 *response,
1573 enum adev_actions *adev_action)
1575 struct typec_port *typec = port->typec_port;
1576 struct typec_altmode *pdev;
1577 struct pd_mode_data *modep;
1584 cmd_type = PD_VDO_CMDT(p[0]);
1585 cmd = PD_VDO_CMD(p[0]);
1587 tcpm_log(port, "Rx VDM cmd 0x%x type %d cmd %d len %d",
1588 p[0], cmd_type, cmd, cnt);
1590 modep = &port->mode_data;
1592 pdev = typec_match_altmode(port->partner_altmode, ALTMODE_DISCOVERY_MAX,
1593 PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1595 svdm_version = typec_get_negotiated_svdm_version(typec);
1596 if (svdm_version < 0)
1602 case CMD_DISCOVER_IDENT:
1603 if (PD_VDO_VID(p[0]) != USB_SID_PD)
1606 if (PD_VDO_SVDM_VER(p[0]) < svdm_version) {
1607 typec_partner_set_svdm_version(port->partner,
1608 PD_VDO_SVDM_VER(p[0]));
1609 svdm_version = PD_VDO_SVDM_VER(p[0]);
1612 port->ams = DISCOVER_IDENTITY;
1614 * PD2.0 Spec 6.10.3: respond with NAK as DFP (data host)
1615 * PD3.1 Spec 6.4.4.2.5.1: respond with NAK if "invalid field" or
1616 * "wrong configuation" or "Unrecognized"
1618 if ((port->data_role == TYPEC_DEVICE || svdm_version >= SVDM_VER_2_0) &&
1620 if (svdm_version < SVDM_VER_2_0) {
1621 for (i = 0; i < port->nr_snk_vdo_v1; i++)
1622 response[i + 1] = port->snk_vdo_v1[i];
1623 rlen = port->nr_snk_vdo_v1 + 1;
1626 for (i = 0; i < port->nr_snk_vdo; i++)
1627 response[i + 1] = port->snk_vdo[i];
1628 rlen = port->nr_snk_vdo + 1;
1632 case CMD_DISCOVER_SVID:
1633 port->ams = DISCOVER_SVIDS;
1635 case CMD_DISCOVER_MODES:
1636 port->ams = DISCOVER_MODES;
1638 case CMD_ENTER_MODE:
1639 port->ams = DFP_TO_UFP_ENTER_MODE;
1642 port->ams = DFP_TO_UFP_EXIT_MODE;
1645 /* Attention command does not have response */
1646 *adev_action = ADEV_ATTENTION;
1652 response[0] = p[0] | VDO_CMDT(CMDT_RSP_ACK);
1653 } else if (rlen == 0) {
1654 response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1657 response[0] = p[0] | VDO_CMDT(CMDT_RSP_BUSY);
1660 response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
1661 (VDO_SVDM_VERS(typec_get_negotiated_svdm_version(typec)));
1664 /* silently drop message if we are not connected */
1665 if (IS_ERR_OR_NULL(port->partner))
1668 tcpm_ams_finish(port);
1671 case CMD_DISCOVER_IDENT:
1672 if (PD_VDO_SVDM_VER(p[0]) < svdm_version)
1673 typec_partner_set_svdm_version(port->partner,
1674 PD_VDO_SVDM_VER(p[0]));
1676 svdm_consume_identity(port, p, cnt);
1677 response[0] = VDO(USB_SID_PD, 1, typec_get_negotiated_svdm_version(typec),
1681 case CMD_DISCOVER_SVID:
1683 if (svdm_consume_svids(port, p, cnt)) {
1684 response[0] = VDO(USB_SID_PD, 1, svdm_version, CMD_DISCOVER_SVID);
1686 } else if (modep->nsvids && supports_modal(port)) {
1687 response[0] = VDO(modep->svids[0], 1, svdm_version,
1688 CMD_DISCOVER_MODES);
1692 case CMD_DISCOVER_MODES:
1694 svdm_consume_modes(port, p, cnt);
1695 modep->svid_index++;
1696 if (modep->svid_index < modep->nsvids) {
1697 u16 svid = modep->svids[modep->svid_index];
1698 response[0] = VDO(svid, 1, svdm_version, CMD_DISCOVER_MODES);
1701 tcpm_register_partner_altmodes(port);
1704 case CMD_ENTER_MODE:
1706 typec_altmode_update_active(pdev, true);
1707 *adev_action = ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL;
1712 typec_altmode_update_active(pdev, false);
1713 /* Back to USB Operation */
1714 *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
1718 case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
1721 /* Unrecognized SVDM */
1722 response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1724 response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
1725 (VDO_SVDM_VERS(svdm_version));
1730 tcpm_ams_finish(port);
1732 case CMD_DISCOVER_IDENT:
1733 case CMD_DISCOVER_SVID:
1734 case CMD_DISCOVER_MODES:
1735 case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
1737 case CMD_ENTER_MODE:
1738 /* Back to USB Operation */
1739 *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
1742 /* Unrecognized SVDM */
1743 response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1745 response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
1746 (VDO_SVDM_VERS(svdm_version));
1751 response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1753 response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
1754 (VDO_SVDM_VERS(svdm_version));
1758 /* Informing the alternate mode drivers about everything */
1759 *adev_action = ADEV_QUEUE_VDM;
1763 static void tcpm_pd_handle_msg(struct tcpm_port *port,
1764 enum pd_msg_request message,
1767 static void tcpm_handle_vdm_request(struct tcpm_port *port,
1768 const __le32 *payload, int cnt)
1770 enum adev_actions adev_action = ADEV_NONE;
1771 struct typec_altmode *adev;
1772 u32 p[PD_MAX_PAYLOAD];
1773 u32 response[8] = { };
1776 for (i = 0; i < cnt; i++)
1777 p[i] = le32_to_cpu(payload[i]);
1779 adev = typec_match_altmode(port->port_altmode, ALTMODE_DISCOVERY_MAX,
1780 PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1782 if (port->vdm_state == VDM_STATE_BUSY) {
1783 /* If UFP responded busy retry after timeout */
1784 if (PD_VDO_CMDT(p[0]) == CMDT_RSP_BUSY) {
1785 port->vdm_state = VDM_STATE_WAIT_RSP_BUSY;
1786 port->vdo_retry = (p[0] & ~VDO_CMDT_MASK) |
1788 mod_vdm_delayed_work(port, PD_T_VDM_BUSY);
1791 port->vdm_state = VDM_STATE_DONE;
1794 if (PD_VDO_SVDM(p[0]) && (adev || tcpm_vdm_ams(port) || port->nr_snk_vdo)) {
1796 * Here a SVDM is received (INIT or RSP or unknown). Set the vdm_sm_running in
1797 * advance because we are dropping the lock but may send VDMs soon.
1798 * For the cases of INIT received:
1799 * - If no response to send, it will be cleared later in this function.
1800 * - If there are responses to send, it will be cleared in the state machine.
1801 * For the cases of RSP received:
1802 * - If no further INIT to send, it will be cleared later in this function.
1803 * - Otherwise, it will be cleared in the state machine if timeout or it will go
1804 * back here until no further INIT to send.
1805 * For the cases of unknown type received:
1806 * - We will send NAK and the flag will be cleared in the state machine.
1808 port->vdm_sm_running = true;
1809 rlen = tcpm_pd_svdm(port, adev, p, cnt, response, &adev_action);
1811 if (port->negotiated_rev >= PD_REV30)
1812 tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
1816 * We are done with any state stored in the port struct now, except
1817 * for any port struct changes done by the tcpm_queue_vdm() call
1818 * below, which is a separate operation.
1820 * So we can safely release the lock here; and we MUST release the
1821 * lock here to avoid an AB BA lock inversion:
1823 * If we keep the lock here then the lock ordering in this path is:
1824 * 1. tcpm_pd_rx_handler take the tcpm port lock
1825 * 2. One of the typec_altmode_* calls below takes the alt-mode's lock
1827 * And we also have this ordering:
1828 * 1. alt-mode driver takes the alt-mode's lock
1829 * 2. alt-mode driver calls tcpm_altmode_enter which takes the
1832 * Dropping our lock here avoids this.
1834 mutex_unlock(&port->lock);
1837 switch (adev_action) {
1840 case ADEV_NOTIFY_USB_AND_QUEUE_VDM:
1841 WARN_ON(typec_altmode_notify(adev, TYPEC_STATE_USB, NULL));
1842 typec_altmode_vdm(adev, p[0], &p[1], cnt);
1844 case ADEV_QUEUE_VDM:
1845 typec_altmode_vdm(adev, p[0], &p[1], cnt);
1847 case ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL:
1848 if (typec_altmode_vdm(adev, p[0], &p[1], cnt)) {
1849 int svdm_version = typec_get_negotiated_svdm_version(
1851 if (svdm_version < 0)
1854 response[0] = VDO(adev->svid, 1, svdm_version,
1856 response[0] |= VDO_OPOS(adev->mode);
1860 case ADEV_ATTENTION:
1861 typec_altmode_attention(adev, p[1]);
1867 * We must re-take the lock here to balance the unlock in
1868 * tcpm_pd_rx_handler, note that no changes, other then the
1869 * tcpm_queue_vdm call, are made while the lock is held again.
1870 * All that is done after the call is unwinding the call stack until
1871 * we return to tcpm_pd_rx_handler and do the unlock there.
1873 mutex_lock(&port->lock);
1876 tcpm_queue_vdm(port, response[0], &response[1], rlen - 1);
1878 port->vdm_sm_running = false;
1881 static void tcpm_send_vdm(struct tcpm_port *port, u32 vid, int cmd,
1882 const u32 *data, int count)
1884 int svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
1887 if (svdm_version < 0)
1890 if (WARN_ON(count > VDO_MAX_SIZE - 1))
1891 count = VDO_MAX_SIZE - 1;
1893 /* set VDM header with VID & CMD */
1894 header = VDO(vid, ((vid & USB_SID_PD) == USB_SID_PD) ?
1895 1 : (PD_VDO_CMD(cmd) <= CMD_ATTENTION),
1897 tcpm_queue_vdm(port, header, data, count);
1900 static unsigned int vdm_ready_timeout(u32 vdm_hdr)
1902 unsigned int timeout;
1903 int cmd = PD_VDO_CMD(vdm_hdr);
1905 /* its not a structured VDM command */
1906 if (!PD_VDO_SVDM(vdm_hdr))
1907 return PD_T_VDM_UNSTRUCTURED;
1909 switch (PD_VDO_CMDT(vdm_hdr)) {
1911 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1912 timeout = PD_T_VDM_WAIT_MODE_E;
1914 timeout = PD_T_VDM_SNDR_RSP;
1917 if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1918 timeout = PD_T_VDM_E_MODE;
1920 timeout = PD_T_VDM_RCVR_RSP;
1926 static void vdm_run_state_machine(struct tcpm_port *port)
1928 struct pd_message msg;
1930 u32 vdo_hdr = port->vdo_data[0];
1932 switch (port->vdm_state) {
1933 case VDM_STATE_READY:
1934 /* Only transmit VDM if attached */
1935 if (!port->attached) {
1936 port->vdm_state = VDM_STATE_ERR_BUSY;
1941 * if there's traffic or we're not in PDO ready state don't send
1944 if (port->state != SRC_READY && port->state != SNK_READY) {
1945 port->vdm_sm_running = false;
1949 /* TODO: AMS operation for Unstructured VDM */
1950 if (PD_VDO_SVDM(vdo_hdr) && PD_VDO_CMDT(vdo_hdr) == CMDT_INIT) {
1951 switch (PD_VDO_CMD(vdo_hdr)) {
1952 case CMD_DISCOVER_IDENT:
1953 res = tcpm_ams_start(port, DISCOVER_IDENTITY);
1955 port->send_discover = false;
1956 else if (res == -EAGAIN)
1957 mod_send_discover_delayed_work(port,
1958 SEND_DISCOVER_RETRY_MS);
1960 case CMD_DISCOVER_SVID:
1961 res = tcpm_ams_start(port, DISCOVER_SVIDS);
1963 case CMD_DISCOVER_MODES:
1964 res = tcpm_ams_start(port, DISCOVER_MODES);
1966 case CMD_ENTER_MODE:
1967 res = tcpm_ams_start(port, DFP_TO_UFP_ENTER_MODE);
1970 res = tcpm_ams_start(port, DFP_TO_UFP_EXIT_MODE);
1973 res = tcpm_ams_start(port, ATTENTION);
1975 case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
1976 res = tcpm_ams_start(port, STRUCTURED_VDMS);
1984 port->vdm_state = VDM_STATE_ERR_BUSY;
1989 port->vdm_state = VDM_STATE_SEND_MESSAGE;
1990 mod_vdm_delayed_work(port, (port->negotiated_rev >= PD_REV30 &&
1991 port->pwr_role == TYPEC_SOURCE &&
1992 PD_VDO_SVDM(vdo_hdr) &&
1993 PD_VDO_CMDT(vdo_hdr) == CMDT_INIT) ?
1996 case VDM_STATE_WAIT_RSP_BUSY:
1997 port->vdo_data[0] = port->vdo_retry;
1998 port->vdo_count = 1;
1999 port->vdm_state = VDM_STATE_READY;
2000 tcpm_ams_finish(port);
2002 case VDM_STATE_BUSY:
2003 port->vdm_state = VDM_STATE_ERR_TMOUT;
2004 if (port->ams != NONE_AMS)
2005 tcpm_ams_finish(port);
2007 case VDM_STATE_ERR_SEND:
2009 * A partner which does not support USB PD will not reply,
2010 * so this is not a fatal error. At the same time, some
2011 * devices may not return GoodCRC under some circumstances,
2012 * so we need to retry.
2014 if (port->vdm_retries < 3) {
2015 tcpm_log(port, "VDM Tx error, retry");
2016 port->vdm_retries++;
2017 port->vdm_state = VDM_STATE_READY;
2018 if (PD_VDO_SVDM(vdo_hdr) && PD_VDO_CMDT(vdo_hdr) == CMDT_INIT)
2019 tcpm_ams_finish(port);
2021 tcpm_ams_finish(port);
2024 case VDM_STATE_SEND_MESSAGE:
2025 /* Prepare and send VDM */
2026 memset(&msg, 0, sizeof(msg));
2027 msg.header = PD_HEADER_LE(PD_DATA_VENDOR_DEF,
2030 port->negotiated_rev,
2031 port->message_id, port->vdo_count);
2032 for (i = 0; i < port->vdo_count; i++)
2033 msg.payload[i] = cpu_to_le32(port->vdo_data[i]);
2034 res = tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2036 port->vdm_state = VDM_STATE_ERR_SEND;
2038 unsigned long timeout;
2040 port->vdm_retries = 0;
2041 port->vdm_state = VDM_STATE_BUSY;
2042 timeout = vdm_ready_timeout(vdo_hdr);
2043 mod_vdm_delayed_work(port, timeout);
2051 static void vdm_state_machine_work(struct kthread_work *work)
2053 struct tcpm_port *port = container_of(work, struct tcpm_port, vdm_state_machine);
2054 enum vdm_states prev_state;
2056 mutex_lock(&port->lock);
2059 * Continue running as long as the port is not busy and there was
2063 prev_state = port->vdm_state;
2064 vdm_run_state_machine(port);
2065 } while (port->vdm_state != prev_state &&
2066 port->vdm_state != VDM_STATE_BUSY &&
2067 port->vdm_state != VDM_STATE_SEND_MESSAGE);
2069 if (port->vdm_state < VDM_STATE_READY)
2070 port->vdm_sm_running = false;
2072 mutex_unlock(&port->lock);
2078 PDO_ERR_VSAFE5V_NOT_FIRST,
2079 PDO_ERR_PDO_TYPE_NOT_IN_ORDER,
2080 PDO_ERR_FIXED_NOT_SORTED,
2081 PDO_ERR_VARIABLE_BATT_NOT_SORTED,
2083 PDO_ERR_PPS_APDO_NOT_SORTED,
2084 PDO_ERR_DUPE_PPS_APDO,
2087 static const char * const pdo_err_msg[] = {
2088 [PDO_ERR_NO_VSAFE5V] =
2089 " err: source/sink caps should at least have vSafe5V",
2090 [PDO_ERR_VSAFE5V_NOT_FIRST] =
2091 " err: vSafe5V Fixed Supply Object Shall always be the first object",
2092 [PDO_ERR_PDO_TYPE_NOT_IN_ORDER] =
2093 " err: PDOs should be in the following order: Fixed; Battery; Variable",
2094 [PDO_ERR_FIXED_NOT_SORTED] =
2095 " err: Fixed supply pdos should be in increasing order of their fixed voltage",
2096 [PDO_ERR_VARIABLE_BATT_NOT_SORTED] =
2097 " err: Variable/Battery supply pdos should be in increasing order of their minimum voltage",
2098 [PDO_ERR_DUPE_PDO] =
2099 " err: Variable/Batt supply pdos cannot have same min/max voltage",
2100 [PDO_ERR_PPS_APDO_NOT_SORTED] =
2101 " err: Programmable power supply apdos should be in increasing order of their maximum voltage",
2102 [PDO_ERR_DUPE_PPS_APDO] =
2103 " err: Programmable power supply apdos cannot have same min/max voltage and max current",
2106 static enum pdo_err tcpm_caps_err(struct tcpm_port *port, const u32 *pdo,
2107 unsigned int nr_pdo)
2111 /* Should at least contain vSafe5v */
2113 return PDO_ERR_NO_VSAFE5V;
2115 /* The vSafe5V Fixed Supply Object Shall always be the first object */
2116 if (pdo_type(pdo[0]) != PDO_TYPE_FIXED ||
2117 pdo_fixed_voltage(pdo[0]) != VSAFE5V)
2118 return PDO_ERR_VSAFE5V_NOT_FIRST;
2120 for (i = 1; i < nr_pdo; i++) {
2121 if (pdo_type(pdo[i]) < pdo_type(pdo[i - 1])) {
2122 return PDO_ERR_PDO_TYPE_NOT_IN_ORDER;
2123 } else if (pdo_type(pdo[i]) == pdo_type(pdo[i - 1])) {
2124 enum pd_pdo_type type = pdo_type(pdo[i]);
2128 * The remaining Fixed Supply Objects, if
2129 * present, shall be sent in voltage order;
2130 * lowest to highest.
2132 case PDO_TYPE_FIXED:
2133 if (pdo_fixed_voltage(pdo[i]) <=
2134 pdo_fixed_voltage(pdo[i - 1]))
2135 return PDO_ERR_FIXED_NOT_SORTED;
2138 * The Battery Supply Objects and Variable
2139 * supply, if present shall be sent in Minimum
2140 * Voltage order; lowest to highest.
2144 if (pdo_min_voltage(pdo[i]) <
2145 pdo_min_voltage(pdo[i - 1]))
2146 return PDO_ERR_VARIABLE_BATT_NOT_SORTED;
2147 else if ((pdo_min_voltage(pdo[i]) ==
2148 pdo_min_voltage(pdo[i - 1])) &&
2149 (pdo_max_voltage(pdo[i]) ==
2150 pdo_max_voltage(pdo[i - 1])))
2151 return PDO_ERR_DUPE_PDO;
2154 * The Programmable Power Supply APDOs, if present,
2155 * shall be sent in Maximum Voltage order;
2156 * lowest to highest.
2159 if (pdo_apdo_type(pdo[i]) != APDO_TYPE_PPS)
2162 if (pdo_pps_apdo_max_voltage(pdo[i]) <
2163 pdo_pps_apdo_max_voltage(pdo[i - 1]))
2164 return PDO_ERR_PPS_APDO_NOT_SORTED;
2165 else if (pdo_pps_apdo_min_voltage(pdo[i]) ==
2166 pdo_pps_apdo_min_voltage(pdo[i - 1]) &&
2167 pdo_pps_apdo_max_voltage(pdo[i]) ==
2168 pdo_pps_apdo_max_voltage(pdo[i - 1]) &&
2169 pdo_pps_apdo_max_current(pdo[i]) ==
2170 pdo_pps_apdo_max_current(pdo[i - 1]))
2171 return PDO_ERR_DUPE_PPS_APDO;
2174 tcpm_log_force(port, " Unknown pdo type");
2182 static int tcpm_validate_caps(struct tcpm_port *port, const u32 *pdo,
2183 unsigned int nr_pdo)
2185 enum pdo_err err_index = tcpm_caps_err(port, pdo, nr_pdo);
2187 if (err_index != PDO_NO_ERR) {
2188 tcpm_log_force(port, " %s", pdo_err_msg[err_index]);
2195 static int tcpm_altmode_enter(struct typec_altmode *altmode, u32 *vdo)
2197 struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2201 svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2202 if (svdm_version < 0)
2203 return svdm_version;
2205 header = VDO(altmode->svid, vdo ? 2 : 1, svdm_version, CMD_ENTER_MODE);
2206 header |= VDO_OPOS(altmode->mode);
2208 tcpm_queue_vdm_unlocked(port, header, vdo, vdo ? 1 : 0);
2212 static int tcpm_altmode_exit(struct typec_altmode *altmode)
2214 struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2218 svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2219 if (svdm_version < 0)
2220 return svdm_version;
2222 header = VDO(altmode->svid, 1, svdm_version, CMD_EXIT_MODE);
2223 header |= VDO_OPOS(altmode->mode);
2225 tcpm_queue_vdm_unlocked(port, header, NULL, 0);
2229 static int tcpm_altmode_vdm(struct typec_altmode *altmode,
2230 u32 header, const u32 *data, int count)
2232 struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2234 tcpm_queue_vdm_unlocked(port, header, data, count - 1);
2239 static const struct typec_altmode_ops tcpm_altmode_ops = {
2240 .enter = tcpm_altmode_enter,
2241 .exit = tcpm_altmode_exit,
2242 .vdm = tcpm_altmode_vdm,
2246 * PD (data, control) command handling functions
2248 static inline enum tcpm_state ready_state(struct tcpm_port *port)
2250 if (port->pwr_role == TYPEC_SOURCE)
2256 static int tcpm_pd_send_control(struct tcpm_port *port,
2257 enum pd_ctrl_msg_type type);
2259 static void tcpm_handle_alert(struct tcpm_port *port, const __le32 *payload,
2262 u32 p0 = le32_to_cpu(payload[0]);
2263 unsigned int type = usb_pd_ado_type(p0);
2266 tcpm_log(port, "Alert message received with no type");
2267 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2271 /* Just handling non-battery alerts for now */
2272 if (!(type & USB_PD_ADO_TYPE_BATT_STATUS_CHANGE)) {
2273 if (port->pwr_role == TYPEC_SOURCE) {
2274 port->upcoming_state = GET_STATUS_SEND;
2275 tcpm_ams_start(port, GETTING_SOURCE_SINK_STATUS);
2278 * Do not check SinkTxOk here in case the Source doesn't set its Rp to
2281 port->ams = GETTING_SOURCE_SINK_STATUS;
2282 tcpm_set_state(port, GET_STATUS_SEND, 0);
2285 tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2289 static int tcpm_set_auto_vbus_discharge_threshold(struct tcpm_port *port,
2290 enum typec_pwr_opmode mode, bool pps_active,
2291 u32 requested_vbus_voltage)
2295 if (!port->tcpc->set_auto_vbus_discharge_threshold)
2298 ret = port->tcpc->set_auto_vbus_discharge_threshold(port->tcpc, mode, pps_active,
2299 requested_vbus_voltage);
2300 tcpm_log_force(port,
2301 "set_auto_vbus_discharge_threshold mode:%d pps_active:%c vbus:%u ret:%d",
2302 mode, pps_active ? 'y' : 'n', requested_vbus_voltage, ret);
2307 static void tcpm_pd_handle_state(struct tcpm_port *port,
2308 enum tcpm_state state,
2310 unsigned int delay_ms)
2312 switch (port->state) {
2316 tcpm_set_state(port, state, delay_ms);
2318 /* 8.3.3.4.1.1 and 6.8.1 power transitioning */
2319 case SNK_TRANSITION_SINK:
2320 case SNK_TRANSITION_SINK_VBUS:
2321 case SRC_TRANSITION_SUPPLY:
2322 tcpm_set_state(port, HARD_RESET_SEND, 0);
2325 if (!tcpm_ams_interruptible(port)) {
2326 tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
2327 SRC_SOFT_RESET_WAIT_SNK_TX :
2331 /* process the Message 6.8.1 */
2332 port->upcoming_state = state;
2333 port->next_ams = ams;
2334 tcpm_set_state(port, ready_state(port), delay_ms);
2340 static void tcpm_pd_handle_msg(struct tcpm_port *port,
2341 enum pd_msg_request message,
2344 switch (port->state) {
2348 tcpm_queue_message(port, message);
2350 /* PD 3.0 Spec 8.3.3.4.1.1 and 6.8.1 */
2351 case SNK_TRANSITION_SINK:
2352 case SNK_TRANSITION_SINK_VBUS:
2353 case SRC_TRANSITION_SUPPLY:
2354 tcpm_set_state(port, HARD_RESET_SEND, 0);
2357 if (!tcpm_ams_interruptible(port)) {
2358 tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
2359 SRC_SOFT_RESET_WAIT_SNK_TX :
2363 port->next_ams = ams;
2364 tcpm_set_state(port, ready_state(port), 0);
2365 /* 6.8.1 process the Message */
2366 tcpm_queue_message(port, message);
2372 static int tcpm_register_source_caps(struct tcpm_port *port)
2374 struct usb_power_delivery_desc desc = { port->negotiated_rev };
2375 struct usb_power_delivery_capabilities_desc caps = { };
2376 struct usb_power_delivery_capabilities *cap;
2378 if (!port->partner_pd)
2379 port->partner_pd = usb_power_delivery_register(NULL, &desc);
2380 if (IS_ERR(port->partner_pd))
2381 return PTR_ERR(port->partner_pd);
2383 memcpy(caps.pdo, port->source_caps, sizeof(u32) * port->nr_source_caps);
2384 caps.role = TYPEC_SOURCE;
2386 cap = usb_power_delivery_register_capabilities(port->partner_pd, &caps);
2388 return PTR_ERR(cap);
2390 port->partner_source_caps = cap;
2395 static int tcpm_register_sink_caps(struct tcpm_port *port)
2397 struct usb_power_delivery_desc desc = { port->negotiated_rev };
2398 struct usb_power_delivery_capabilities_desc caps = { };
2399 struct usb_power_delivery_capabilities *cap;
2401 if (!port->partner_pd)
2402 port->partner_pd = usb_power_delivery_register(NULL, &desc);
2403 if (IS_ERR(port->partner_pd))
2404 return PTR_ERR(port->partner_pd);
2406 memcpy(caps.pdo, port->sink_caps, sizeof(u32) * port->nr_sink_caps);
2407 caps.role = TYPEC_SINK;
2409 cap = usb_power_delivery_register_capabilities(port->partner_pd, &caps);
2411 return PTR_ERR(cap);
2413 port->partner_sink_caps = cap;
2418 static void tcpm_pd_data_request(struct tcpm_port *port,
2419 const struct pd_message *msg)
2421 enum pd_data_msg_type type = pd_header_type_le(msg->header);
2422 unsigned int cnt = pd_header_cnt_le(msg->header);
2423 unsigned int rev = pd_header_rev_le(msg->header);
2425 enum frs_typec_current partner_frs_current;
2429 if (tcpm_vdm_ams(port) && type != PD_DATA_VENDOR_DEF) {
2430 port->vdm_state = VDM_STATE_ERR_BUSY;
2431 tcpm_ams_finish(port);
2432 mod_vdm_delayed_work(port, 0);
2436 case PD_DATA_SOURCE_CAP:
2437 for (i = 0; i < cnt; i++)
2438 port->source_caps[i] = le32_to_cpu(msg->payload[i]);
2440 port->nr_source_caps = cnt;
2442 tcpm_log_source_caps(port);
2444 tcpm_validate_caps(port, port->source_caps,
2445 port->nr_source_caps);
2447 tcpm_register_source_caps(port);
2450 * Adjust revision in subsequent message headers, as required,
2451 * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
2452 * support Rev 1.0 so just do nothing in that scenario.
2454 if (rev == PD_REV10) {
2455 if (port->ams == GET_SOURCE_CAPABILITIES)
2456 tcpm_ams_finish(port);
2460 if (rev < PD_MAX_REV)
2461 port->negotiated_rev = rev;
2463 if (port->pwr_role == TYPEC_SOURCE) {
2464 if (port->ams == GET_SOURCE_CAPABILITIES)
2465 tcpm_pd_handle_state(port, SRC_READY, NONE_AMS, 0);
2466 /* Unexpected Source Capabilities */
2468 tcpm_pd_handle_msg(port,
2469 port->negotiated_rev < PD_REV30 ?
2470 PD_MSG_CTRL_REJECT :
2471 PD_MSG_CTRL_NOT_SUPP,
2473 } else if (port->state == SNK_WAIT_CAPABILITIES) {
2475 * This message may be received even if VBUS is not
2476 * present. This is quite unexpected; see USB PD
2477 * specification, sections 8.3.3.6.3.1 and 8.3.3.6.3.2.
2478 * However, at the same time, we must be ready to
2479 * receive this message and respond to it 15ms after
2480 * receiving PS_RDY during power swap operations, no matter
2481 * if VBUS is available or not (USB PD specification,
2483 * So we need to accept the message either way,
2484 * but be prepared to keep waiting for VBUS after it was
2487 port->ams = POWER_NEGOTIATION;
2488 port->in_ams = true;
2489 tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
2491 if (port->ams == GET_SOURCE_CAPABILITIES)
2492 tcpm_ams_finish(port);
2493 tcpm_pd_handle_state(port, SNK_NEGOTIATE_CAPABILITIES,
2494 POWER_NEGOTIATION, 0);
2497 case PD_DATA_REQUEST:
2499 * Adjust revision in subsequent message headers, as required,
2500 * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
2501 * support Rev 1.0 so just reject in that scenario.
2503 if (rev == PD_REV10) {
2504 tcpm_pd_handle_msg(port,
2505 port->negotiated_rev < PD_REV30 ?
2506 PD_MSG_CTRL_REJECT :
2507 PD_MSG_CTRL_NOT_SUPP,
2512 if (rev < PD_MAX_REV)
2513 port->negotiated_rev = rev;
2515 if (port->pwr_role != TYPEC_SOURCE || cnt != 1) {
2516 tcpm_pd_handle_msg(port,
2517 port->negotiated_rev < PD_REV30 ?
2518 PD_MSG_CTRL_REJECT :
2519 PD_MSG_CTRL_NOT_SUPP,
2524 port->sink_request = le32_to_cpu(msg->payload[0]);
2526 if (port->vdm_sm_running && port->explicit_contract) {
2527 tcpm_pd_handle_msg(port, PD_MSG_CTRL_WAIT, port->ams);
2531 if (port->state == SRC_SEND_CAPABILITIES)
2532 tcpm_set_state(port, SRC_NEGOTIATE_CAPABILITIES, 0);
2534 tcpm_pd_handle_state(port, SRC_NEGOTIATE_CAPABILITIES,
2535 POWER_NEGOTIATION, 0);
2537 case PD_DATA_SINK_CAP:
2538 /* We don't do anything with this at the moment... */
2539 for (i = 0; i < cnt; i++)
2540 port->sink_caps[i] = le32_to_cpu(msg->payload[i]);
2542 partner_frs_current = (port->sink_caps[0] & PDO_FIXED_FRS_CURR_MASK) >>
2543 PDO_FIXED_FRS_CURR_SHIFT;
2544 frs_enable = partner_frs_current && (partner_frs_current <=
2545 port->new_source_frs_current);
2547 "Port partner FRS capable partner_frs_current:%u port_frs_current:%u enable:%c",
2548 partner_frs_current, port->new_source_frs_current, frs_enable ? 'y' : 'n');
2550 ret = port->tcpc->enable_frs(port->tcpc, true);
2551 tcpm_log(port, "Enable FRS %s, ret:%d\n", ret ? "fail" : "success", ret);
2554 port->nr_sink_caps = cnt;
2555 port->sink_cap_done = true;
2556 tcpm_register_sink_caps(port);
2558 if (port->ams == GET_SINK_CAPABILITIES)
2559 tcpm_set_state(port, ready_state(port), 0);
2560 /* Unexpected Sink Capabilities */
2562 tcpm_pd_handle_msg(port,
2563 port->negotiated_rev < PD_REV30 ?
2564 PD_MSG_CTRL_REJECT :
2565 PD_MSG_CTRL_NOT_SUPP,
2568 case PD_DATA_VENDOR_DEF:
2569 tcpm_handle_vdm_request(port, msg->payload, cnt);
2572 port->bist_request = le32_to_cpu(msg->payload[0]);
2573 tcpm_pd_handle_state(port, BIST_RX, BIST, 0);
2576 if (port->state != SRC_READY && port->state != SNK_READY)
2577 tcpm_pd_handle_state(port, port->pwr_role == TYPEC_SOURCE ?
2578 SRC_SOFT_RESET_WAIT_SNK_TX : SNK_SOFT_RESET,
2581 tcpm_handle_alert(port, msg->payload, cnt);
2583 case PD_DATA_BATT_STATUS:
2584 case PD_DATA_GET_COUNTRY_INFO:
2585 /* Currently unsupported */
2586 tcpm_pd_handle_msg(port, port->negotiated_rev < PD_REV30 ?
2587 PD_MSG_CTRL_REJECT :
2588 PD_MSG_CTRL_NOT_SUPP,
2592 tcpm_pd_handle_msg(port, port->negotiated_rev < PD_REV30 ?
2593 PD_MSG_CTRL_REJECT :
2594 PD_MSG_CTRL_NOT_SUPP,
2596 tcpm_log(port, "Unrecognized data message type %#x", type);
2601 static void tcpm_pps_complete(struct tcpm_port *port, int result)
2603 if (port->pps_pending) {
2604 port->pps_status = result;
2605 port->pps_pending = false;
2606 complete(&port->pps_complete);
2610 static void tcpm_pd_ctrl_request(struct tcpm_port *port,
2611 const struct pd_message *msg)
2613 enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
2614 enum tcpm_state next_state;
2617 * Stop VDM state machine if interrupted by other Messages while NOT_SUPP is allowed in
2618 * VDM AMS if waiting for VDM responses and will be handled later.
2620 if (tcpm_vdm_ams(port) && type != PD_CTRL_NOT_SUPP && type != PD_CTRL_GOOD_CRC) {
2621 port->vdm_state = VDM_STATE_ERR_BUSY;
2622 tcpm_ams_finish(port);
2623 mod_vdm_delayed_work(port, 0);
2627 case PD_CTRL_GOOD_CRC:
2630 case PD_CTRL_GET_SOURCE_CAP:
2631 tcpm_pd_handle_msg(port, PD_MSG_DATA_SOURCE_CAP, GET_SOURCE_CAPABILITIES);
2633 case PD_CTRL_GET_SINK_CAP:
2634 tcpm_pd_handle_msg(port, PD_MSG_DATA_SINK_CAP, GET_SINK_CAPABILITIES);
2636 case PD_CTRL_GOTO_MIN:
2638 case PD_CTRL_PS_RDY:
2639 switch (port->state) {
2640 case SNK_TRANSITION_SINK:
2641 if (port->vbus_present) {
2642 tcpm_set_current_limit(port,
2643 port->req_current_limit,
2644 port->req_supply_voltage);
2645 port->explicit_contract = true;
2646 tcpm_set_auto_vbus_discharge_threshold(port,
2648 port->pps_data.active,
2649 port->supply_voltage);
2650 tcpm_set_state(port, SNK_READY, 0);
2653 * Seen after power swap. Keep waiting for VBUS
2654 * in a transitional state.
2656 tcpm_set_state(port,
2657 SNK_TRANSITION_SINK_VBUS, 0);
2660 case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
2661 tcpm_set_state(port, PR_SWAP_SRC_SNK_SINK_ON, 0);
2663 case PR_SWAP_SNK_SRC_SINK_OFF:
2664 tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON, 0);
2666 case VCONN_SWAP_WAIT_FOR_VCONN:
2667 tcpm_set_state(port, VCONN_SWAP_TURN_OFF_VCONN, 0);
2669 case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
2670 tcpm_set_state(port, FR_SWAP_SNK_SRC_NEW_SINK_READY, 0);
2673 tcpm_pd_handle_state(port,
2674 port->pwr_role == TYPEC_SOURCE ?
2675 SRC_SOFT_RESET_WAIT_SNK_TX :
2681 case PD_CTRL_REJECT:
2683 case PD_CTRL_NOT_SUPP:
2684 switch (port->state) {
2685 case SNK_NEGOTIATE_CAPABILITIES:
2686 /* USB PD specification, Figure 8-43 */
2687 if (port->explicit_contract)
2688 next_state = SNK_READY;
2690 next_state = SNK_WAIT_CAPABILITIES;
2692 /* Threshold was relaxed before sending Request. Restore it back. */
2693 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
2694 port->pps_data.active,
2695 port->supply_voltage);
2696 tcpm_set_state(port, next_state, 0);
2698 case SNK_NEGOTIATE_PPS_CAPABILITIES:
2699 /* Revert data back from any requested PPS updates */
2700 port->pps_data.req_out_volt = port->supply_voltage;
2701 port->pps_data.req_op_curr = port->current_limit;
2702 port->pps_status = (type == PD_CTRL_WAIT ?
2703 -EAGAIN : -EOPNOTSUPP);
2705 /* Threshold was relaxed before sending Request. Restore it back. */
2706 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
2707 port->pps_data.active,
2708 port->supply_voltage);
2710 tcpm_set_state(port, SNK_READY, 0);
2713 port->swap_status = (type == PD_CTRL_WAIT ?
2714 -EAGAIN : -EOPNOTSUPP);
2715 tcpm_set_state(port, DR_SWAP_CANCEL, 0);
2718 port->swap_status = (type == PD_CTRL_WAIT ?
2719 -EAGAIN : -EOPNOTSUPP);
2720 tcpm_set_state(port, PR_SWAP_CANCEL, 0);
2722 case VCONN_SWAP_SEND:
2723 port->swap_status = (type == PD_CTRL_WAIT ?
2724 -EAGAIN : -EOPNOTSUPP);
2725 tcpm_set_state(port, VCONN_SWAP_CANCEL, 0);
2728 tcpm_set_state(port, FR_SWAP_CANCEL, 0);
2731 port->sink_cap_done = true;
2732 tcpm_set_state(port, ready_state(port), 0);
2736 if (port->vdm_state > VDM_STATE_READY) {
2737 port->vdm_state = VDM_STATE_DONE;
2738 if (tcpm_vdm_ams(port))
2739 tcpm_ams_finish(port);
2740 mod_vdm_delayed_work(port, 0);
2745 tcpm_pd_handle_state(port,
2746 port->pwr_role == TYPEC_SOURCE ?
2747 SRC_SOFT_RESET_WAIT_SNK_TX :
2753 case PD_CTRL_ACCEPT:
2754 switch (port->state) {
2755 case SNK_NEGOTIATE_CAPABILITIES:
2756 port->pps_data.active = false;
2757 tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
2759 case SNK_NEGOTIATE_PPS_CAPABILITIES:
2760 port->pps_data.active = true;
2761 port->pps_data.min_volt = port->pps_data.req_min_volt;
2762 port->pps_data.max_volt = port->pps_data.req_max_volt;
2763 port->pps_data.max_curr = port->pps_data.req_max_curr;
2764 port->req_supply_voltage = port->pps_data.req_out_volt;
2765 port->req_current_limit = port->pps_data.req_op_curr;
2766 power_supply_changed(port->psy);
2767 tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
2769 case SOFT_RESET_SEND:
2770 if (port->ams == SOFT_RESET_AMS)
2771 tcpm_ams_finish(port);
2772 if (port->pwr_role == TYPEC_SOURCE) {
2773 port->upcoming_state = SRC_SEND_CAPABILITIES;
2774 tcpm_ams_start(port, POWER_NEGOTIATION);
2776 tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
2780 tcpm_set_state(port, DR_SWAP_CHANGE_DR, 0);
2783 tcpm_set_state(port, PR_SWAP_START, 0);
2785 case VCONN_SWAP_SEND:
2786 tcpm_set_state(port, VCONN_SWAP_START, 0);
2789 tcpm_set_state(port, FR_SWAP_SNK_SRC_TRANSITION_TO_OFF, 0);
2792 tcpm_pd_handle_state(port,
2793 port->pwr_role == TYPEC_SOURCE ?
2794 SRC_SOFT_RESET_WAIT_SNK_TX :
2800 case PD_CTRL_SOFT_RESET:
2801 port->ams = SOFT_RESET_AMS;
2802 tcpm_set_state(port, SOFT_RESET, 0);
2804 case PD_CTRL_DR_SWAP:
2807 * 6.3.9: If an alternate mode is active, a request to swap
2808 * alternate modes shall trigger a port reset.
2810 if (port->typec_caps.data != TYPEC_PORT_DRD) {
2811 tcpm_pd_handle_msg(port,
2812 port->negotiated_rev < PD_REV30 ?
2813 PD_MSG_CTRL_REJECT :
2814 PD_MSG_CTRL_NOT_SUPP,
2817 if (port->send_discover) {
2818 tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2822 tcpm_pd_handle_state(port, DR_SWAP_ACCEPT, DATA_ROLE_SWAP, 0);
2825 case PD_CTRL_PR_SWAP:
2826 if (port->port_type != TYPEC_PORT_DRP) {
2827 tcpm_pd_handle_msg(port,
2828 port->negotiated_rev < PD_REV30 ?
2829 PD_MSG_CTRL_REJECT :
2830 PD_MSG_CTRL_NOT_SUPP,
2833 if (port->send_discover) {
2834 tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2838 tcpm_pd_handle_state(port, PR_SWAP_ACCEPT, POWER_ROLE_SWAP, 0);
2841 case PD_CTRL_VCONN_SWAP:
2842 if (port->send_discover) {
2843 tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2847 tcpm_pd_handle_state(port, VCONN_SWAP_ACCEPT, VCONN_SWAP, 0);
2849 case PD_CTRL_GET_SOURCE_CAP_EXT:
2850 case PD_CTRL_GET_STATUS:
2851 case PD_CTRL_FR_SWAP:
2852 case PD_CTRL_GET_PPS_STATUS:
2853 case PD_CTRL_GET_COUNTRY_CODES:
2854 /* Currently not supported */
2855 tcpm_pd_handle_msg(port,
2856 port->negotiated_rev < PD_REV30 ?
2857 PD_MSG_CTRL_REJECT :
2858 PD_MSG_CTRL_NOT_SUPP,
2862 tcpm_pd_handle_msg(port,
2863 port->negotiated_rev < PD_REV30 ?
2864 PD_MSG_CTRL_REJECT :
2865 PD_MSG_CTRL_NOT_SUPP,
2867 tcpm_log(port, "Unrecognized ctrl message type %#x", type);
2872 static void tcpm_pd_ext_msg_request(struct tcpm_port *port,
2873 const struct pd_message *msg)
2875 enum pd_ext_msg_type type = pd_header_type_le(msg->header);
2876 unsigned int data_size = pd_ext_header_data_size_le(msg->ext_msg.header);
2878 /* stopping VDM state machine if interrupted by other Messages */
2879 if (tcpm_vdm_ams(port)) {
2880 port->vdm_state = VDM_STATE_ERR_BUSY;
2881 tcpm_ams_finish(port);
2882 mod_vdm_delayed_work(port, 0);
2885 if (!(le16_to_cpu(msg->ext_msg.header) & PD_EXT_HDR_CHUNKED)) {
2886 tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
2887 tcpm_log(port, "Unchunked extended messages unsupported");
2891 if (data_size > PD_EXT_MAX_CHUNK_DATA) {
2892 tcpm_pd_handle_state(port, CHUNK_NOT_SUPP, NONE_AMS, PD_T_CHUNK_NOT_SUPP);
2893 tcpm_log(port, "Chunk handling not yet supported");
2899 case PD_EXT_PPS_STATUS:
2900 if (port->ams == GETTING_SOURCE_SINK_STATUS) {
2901 tcpm_ams_finish(port);
2902 tcpm_set_state(port, ready_state(port), 0);
2904 /* unexpected Status or PPS_Status Message */
2905 tcpm_pd_handle_state(port, port->pwr_role == TYPEC_SOURCE ?
2906 SRC_SOFT_RESET_WAIT_SNK_TX : SNK_SOFT_RESET,
2910 case PD_EXT_SOURCE_CAP_EXT:
2911 case PD_EXT_GET_BATT_CAP:
2912 case PD_EXT_GET_BATT_STATUS:
2913 case PD_EXT_BATT_CAP:
2914 case PD_EXT_GET_MANUFACTURER_INFO:
2915 case PD_EXT_MANUFACTURER_INFO:
2916 case PD_EXT_SECURITY_REQUEST:
2917 case PD_EXT_SECURITY_RESPONSE:
2918 case PD_EXT_FW_UPDATE_REQUEST:
2919 case PD_EXT_FW_UPDATE_RESPONSE:
2920 case PD_EXT_COUNTRY_INFO:
2921 case PD_EXT_COUNTRY_CODES:
2922 tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
2925 tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
2926 tcpm_log(port, "Unrecognized extended message type %#x", type);
2931 static void tcpm_pd_rx_handler(struct kthread_work *work)
2933 struct pd_rx_event *event = container_of(work,
2934 struct pd_rx_event, work);
2935 const struct pd_message *msg = &event->msg;
2936 unsigned int cnt = pd_header_cnt_le(msg->header);
2937 struct tcpm_port *port = event->port;
2939 mutex_lock(&port->lock);
2941 tcpm_log(port, "PD RX, header: %#x [%d]", le16_to_cpu(msg->header),
2944 if (port->attached) {
2945 enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
2946 unsigned int msgid = pd_header_msgid_le(msg->header);
2949 * USB PD standard, 6.6.1.2:
2950 * "... if MessageID value in a received Message is the
2951 * same as the stored value, the receiver shall return a
2952 * GoodCRC Message with that MessageID value and drop
2953 * the Message (this is a retry of an already received
2954 * Message). Note: this shall not apply to the Soft_Reset
2955 * Message which always has a MessageID value of zero."
2957 if (msgid == port->rx_msgid && type != PD_CTRL_SOFT_RESET)
2959 port->rx_msgid = msgid;
2962 * If both ends believe to be DFP/host, we have a data role
2965 if (!!(le16_to_cpu(msg->header) & PD_HEADER_DATA_ROLE) ==
2966 (port->data_role == TYPEC_HOST)) {
2968 "Data role mismatch, initiating error recovery");
2969 tcpm_set_state(port, ERROR_RECOVERY, 0);
2971 if (le16_to_cpu(msg->header) & PD_HEADER_EXT_HDR)
2972 tcpm_pd_ext_msg_request(port, msg);
2974 tcpm_pd_data_request(port, msg);
2976 tcpm_pd_ctrl_request(port, msg);
2981 mutex_unlock(&port->lock);
2985 void tcpm_pd_receive(struct tcpm_port *port, const struct pd_message *msg)
2987 struct pd_rx_event *event;
2989 event = kzalloc(sizeof(*event), GFP_ATOMIC);
2993 kthread_init_work(&event->work, tcpm_pd_rx_handler);
2995 memcpy(&event->msg, msg, sizeof(*msg));
2996 kthread_queue_work(port->wq, &event->work);
2998 EXPORT_SYMBOL_GPL(tcpm_pd_receive);
3000 static int tcpm_pd_send_control(struct tcpm_port *port,
3001 enum pd_ctrl_msg_type type)
3003 struct pd_message msg;
3005 memset(&msg, 0, sizeof(msg));
3006 msg.header = PD_HEADER_LE(type, port->pwr_role,
3008 port->negotiated_rev,
3009 port->message_id, 0);
3011 return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
3015 * Send queued message without affecting state.
3016 * Return true if state machine should go back to sleep,
3019 static bool tcpm_send_queued_message(struct tcpm_port *port)
3021 enum pd_msg_request queued_message;
3025 queued_message = port->queued_message;
3026 port->queued_message = PD_MSG_NONE;
3028 switch (queued_message) {
3029 case PD_MSG_CTRL_WAIT:
3030 tcpm_pd_send_control(port, PD_CTRL_WAIT);
3032 case PD_MSG_CTRL_REJECT:
3033 tcpm_pd_send_control(port, PD_CTRL_REJECT);
3035 case PD_MSG_CTRL_NOT_SUPP:
3036 tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP);
3038 case PD_MSG_DATA_SINK_CAP:
3039 ret = tcpm_pd_send_sink_caps(port);
3041 tcpm_log(port, "Unable to send snk caps, ret=%d", ret);
3042 tcpm_set_state(port, SNK_SOFT_RESET, 0);
3044 tcpm_ams_finish(port);
3046 case PD_MSG_DATA_SOURCE_CAP:
3047 ret = tcpm_pd_send_source_caps(port);
3050 "Unable to send src caps, ret=%d",
3052 tcpm_set_state(port, SOFT_RESET_SEND, 0);
3053 } else if (port->pwr_role == TYPEC_SOURCE) {
3054 tcpm_ams_finish(port);
3055 tcpm_set_state(port, HARD_RESET_SEND,
3056 PD_T_SENDER_RESPONSE);
3058 tcpm_ams_finish(port);
3064 } while (port->queued_message != PD_MSG_NONE);
3066 if (port->delayed_state != INVALID_STATE) {
3067 if (ktime_after(port->delayed_runtime, ktime_get())) {
3068 mod_tcpm_delayed_work(port, ktime_to_ms(ktime_sub(port->delayed_runtime,
3072 port->delayed_state = INVALID_STATE;
3077 static int tcpm_pd_check_request(struct tcpm_port *port)
3079 u32 pdo, rdo = port->sink_request;
3080 unsigned int max, op, pdo_max, index;
3081 enum pd_pdo_type type;
3083 index = rdo_index(rdo);
3084 if (!index || index > port->nr_src_pdo)
3087 pdo = port->src_pdo[index - 1];
3088 type = pdo_type(pdo);
3090 case PDO_TYPE_FIXED:
3092 max = rdo_max_current(rdo);
3093 op = rdo_op_current(rdo);
3094 pdo_max = pdo_max_current(pdo);
3098 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
3101 if (type == PDO_TYPE_FIXED)
3103 "Requested %u mV, %u mA for %u / %u mA",
3104 pdo_fixed_voltage(pdo), pdo_max, op, max);
3107 "Requested %u -> %u mV, %u mA for %u / %u mA",
3108 pdo_min_voltage(pdo), pdo_max_voltage(pdo),
3112 max = rdo_max_power(rdo);
3113 op = rdo_op_power(rdo);
3114 pdo_max = pdo_max_power(pdo);
3118 if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
3121 "Requested %u -> %u mV, %u mW for %u / %u mW",
3122 pdo_min_voltage(pdo), pdo_max_voltage(pdo),
3129 port->op_vsafe5v = index == 1;
3134 #define min_power(x, y) min(pdo_max_power(x), pdo_max_power(y))
3135 #define min_current(x, y) min(pdo_max_current(x), pdo_max_current(y))
3137 static int tcpm_pd_select_pdo(struct tcpm_port *port, int *sink_pdo,
3140 unsigned int i, j, max_src_mv = 0, min_src_mv = 0, max_mw = 0,
3141 max_mv = 0, src_mw = 0, src_ma = 0, max_snk_mv = 0,
3145 port->pps_data.supported = false;
3146 port->usb_type = POWER_SUPPLY_USB_TYPE_PD;
3147 power_supply_changed(port->psy);
3150 * Select the source PDO providing the most power which has a
3153 for (i = 0; i < port->nr_source_caps; i++) {
3154 u32 pdo = port->source_caps[i];
3155 enum pd_pdo_type type = pdo_type(pdo);
3158 case PDO_TYPE_FIXED:
3159 max_src_mv = pdo_fixed_voltage(pdo);
3160 min_src_mv = max_src_mv;
3164 max_src_mv = pdo_max_voltage(pdo);
3165 min_src_mv = pdo_min_voltage(pdo);
3168 if (pdo_apdo_type(pdo) == APDO_TYPE_PPS) {
3169 port->pps_data.supported = true;
3171 POWER_SUPPLY_USB_TYPE_PD_PPS;
3172 power_supply_changed(port->psy);
3176 tcpm_log(port, "Invalid source PDO type, ignoring");
3181 case PDO_TYPE_FIXED:
3183 src_ma = pdo_max_current(pdo);
3184 src_mw = src_ma * min_src_mv / 1000;
3187 src_mw = pdo_max_power(pdo);
3192 tcpm_log(port, "Invalid source PDO type, ignoring");
3196 for (j = 0; j < port->nr_snk_pdo; j++) {
3197 pdo = port->snk_pdo[j];
3199 switch (pdo_type(pdo)) {
3200 case PDO_TYPE_FIXED:
3201 max_snk_mv = pdo_fixed_voltage(pdo);
3202 min_snk_mv = max_snk_mv;
3206 max_snk_mv = pdo_max_voltage(pdo);
3207 min_snk_mv = pdo_min_voltage(pdo);
3212 tcpm_log(port, "Invalid sink PDO type, ignoring");
3216 if (max_src_mv <= max_snk_mv &&
3217 min_src_mv >= min_snk_mv) {
3218 /* Prefer higher voltages if available */
3219 if ((src_mw == max_mw && min_src_mv > max_mv) ||
3224 max_mv = min_src_mv;
3234 #define min_pps_apdo_current(x, y) \
3235 min(pdo_pps_apdo_max_current(x), pdo_pps_apdo_max_current(y))
3237 static unsigned int tcpm_pd_select_pps_apdo(struct tcpm_port *port)
3239 unsigned int i, j, max_mw = 0, max_mv = 0;
3240 unsigned int min_src_mv, max_src_mv, src_ma, src_mw;
3241 unsigned int min_snk_mv, max_snk_mv;
3242 unsigned int max_op_mv;
3244 unsigned int src_pdo = 0, snk_pdo = 0;
3247 * Select the source PPS APDO providing the most power while staying
3248 * within the board's limits. We skip the first PDO as this is always
3251 for (i = 1; i < port->nr_source_caps; ++i) {
3252 pdo = port->source_caps[i];
3254 switch (pdo_type(pdo)) {
3256 if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
3257 tcpm_log(port, "Not PPS APDO (source), ignoring");
3261 min_src_mv = pdo_pps_apdo_min_voltage(pdo);
3262 max_src_mv = pdo_pps_apdo_max_voltage(pdo);
3263 src_ma = pdo_pps_apdo_max_current(pdo);
3264 src_mw = (src_ma * max_src_mv) / 1000;
3267 * Now search through the sink PDOs to find a matching
3268 * PPS APDO. Again skip the first sink PDO as this will
3271 for (j = 1; j < port->nr_snk_pdo; j++) {
3272 pdo = port->snk_pdo[j];
3274 switch (pdo_type(pdo)) {
3276 if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
3278 "Not PPS APDO (sink), ignoring");
3283 pdo_pps_apdo_min_voltage(pdo);
3285 pdo_pps_apdo_max_voltage(pdo);
3289 "Not APDO type (sink), ignoring");
3293 if (min_src_mv <= max_snk_mv &&
3294 max_src_mv >= min_snk_mv) {
3295 max_op_mv = min(max_src_mv, max_snk_mv);
3296 src_mw = (max_op_mv * src_ma) / 1000;
3297 /* Prefer higher voltages if available */
3298 if ((src_mw == max_mw &&
3299 max_op_mv > max_mv) ||
3311 tcpm_log(port, "Not APDO type (source), ignoring");
3317 src = port->source_caps[src_pdo];
3318 snk = port->snk_pdo[snk_pdo];
3320 port->pps_data.req_min_volt = max(pdo_pps_apdo_min_voltage(src),
3321 pdo_pps_apdo_min_voltage(snk));
3322 port->pps_data.req_max_volt = min(pdo_pps_apdo_max_voltage(src),
3323 pdo_pps_apdo_max_voltage(snk));
3324 port->pps_data.req_max_curr = min_pps_apdo_current(src, snk);
3325 port->pps_data.req_out_volt = min(port->pps_data.req_max_volt,
3326 max(port->pps_data.req_min_volt,
3327 port->pps_data.req_out_volt));
3328 port->pps_data.req_op_curr = min(port->pps_data.req_max_curr,
3329 port->pps_data.req_op_curr);
3335 static int tcpm_pd_build_request(struct tcpm_port *port, u32 *rdo)
3337 unsigned int mv, ma, mw, flags;
3338 unsigned int max_ma, max_mw;
3339 enum pd_pdo_type type;
3340 u32 pdo, matching_snk_pdo;
3341 int src_pdo_index = 0;
3342 int snk_pdo_index = 0;
3345 ret = tcpm_pd_select_pdo(port, &snk_pdo_index, &src_pdo_index);
3349 pdo = port->source_caps[src_pdo_index];
3350 matching_snk_pdo = port->snk_pdo[snk_pdo_index];
3351 type = pdo_type(pdo);
3354 case PDO_TYPE_FIXED:
3355 mv = pdo_fixed_voltage(pdo);
3359 mv = pdo_min_voltage(pdo);
3362 tcpm_log(port, "Invalid PDO selected!");
3366 /* Select maximum available current within the sink pdo's limit */
3367 if (type == PDO_TYPE_BATT) {
3368 mw = min_power(pdo, matching_snk_pdo);
3369 ma = 1000 * mw / mv;
3371 ma = min_current(pdo, matching_snk_pdo);
3372 mw = ma * mv / 1000;
3375 flags = RDO_USB_COMM | RDO_NO_SUSPEND;
3377 /* Set mismatch bit if offered power is less than operating power */
3380 if (mw < port->operating_snk_mw) {
3381 flags |= RDO_CAP_MISMATCH;
3382 if (type == PDO_TYPE_BATT &&
3383 (pdo_max_power(matching_snk_pdo) > pdo_max_power(pdo)))
3384 max_mw = pdo_max_power(matching_snk_pdo);
3385 else if (pdo_max_current(matching_snk_pdo) >
3386 pdo_max_current(pdo))
3387 max_ma = pdo_max_current(matching_snk_pdo);
3390 tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
3391 port->cc_req, port->cc1, port->cc2, port->vbus_source,
3392 port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
3395 if (type == PDO_TYPE_BATT) {
3396 *rdo = RDO_BATT(src_pdo_index + 1, mw, max_mw, flags);
3398 tcpm_log(port, "Requesting PDO %d: %u mV, %u mW%s",
3399 src_pdo_index, mv, mw,
3400 flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
3402 *rdo = RDO_FIXED(src_pdo_index + 1, ma, max_ma, flags);
3404 tcpm_log(port, "Requesting PDO %d: %u mV, %u mA%s",
3405 src_pdo_index, mv, ma,
3406 flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
3409 port->req_current_limit = ma;
3410 port->req_supply_voltage = mv;
3415 static int tcpm_pd_send_request(struct tcpm_port *port)
3417 struct pd_message msg;
3421 ret = tcpm_pd_build_request(port, &rdo);
3426 * Relax the threshold as voltage will be adjusted after Accept Message plus tSrcTransition.
3427 * It is safer to modify the threshold here.
3429 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
3431 memset(&msg, 0, sizeof(msg));
3432 msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
3435 port->negotiated_rev,
3436 port->message_id, 1);
3437 msg.payload[0] = cpu_to_le32(rdo);
3439 return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
3442 static int tcpm_pd_build_pps_request(struct tcpm_port *port, u32 *rdo)
3444 unsigned int out_mv, op_ma, op_mw, max_mv, max_ma, flags;
3445 enum pd_pdo_type type;
3446 unsigned int src_pdo_index;
3449 src_pdo_index = tcpm_pd_select_pps_apdo(port);
3453 pdo = port->source_caps[src_pdo_index];
3454 type = pdo_type(pdo);
3458 if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
3459 tcpm_log(port, "Invalid APDO selected!");
3462 max_mv = port->pps_data.req_max_volt;
3463 max_ma = port->pps_data.req_max_curr;
3464 out_mv = port->pps_data.req_out_volt;
3465 op_ma = port->pps_data.req_op_curr;
3468 tcpm_log(port, "Invalid PDO selected!");
3472 flags = RDO_USB_COMM | RDO_NO_SUSPEND;
3474 op_mw = (op_ma * out_mv) / 1000;
3475 if (op_mw < port->operating_snk_mw) {
3477 * Try raising current to meet power needs. If that's not enough
3478 * then try upping the voltage. If that's still not enough
3479 * then we've obviously chosen a PPS APDO which really isn't
3480 * suitable so abandon ship.
3482 op_ma = (port->operating_snk_mw * 1000) / out_mv;
3483 if ((port->operating_snk_mw * 1000) % out_mv)
3485 op_ma += RDO_PROG_CURR_MA_STEP - (op_ma % RDO_PROG_CURR_MA_STEP);
3487 if (op_ma > max_ma) {
3489 out_mv = (port->operating_snk_mw * 1000) / op_ma;
3490 if ((port->operating_snk_mw * 1000) % op_ma)
3492 out_mv += RDO_PROG_VOLT_MV_STEP -
3493 (out_mv % RDO_PROG_VOLT_MV_STEP);
3495 if (out_mv > max_mv) {
3496 tcpm_log(port, "Invalid PPS APDO selected!");
3502 tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
3503 port->cc_req, port->cc1, port->cc2, port->vbus_source,
3504 port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
3507 *rdo = RDO_PROG(src_pdo_index + 1, out_mv, op_ma, flags);
3509 tcpm_log(port, "Requesting APDO %d: %u mV, %u mA",
3510 src_pdo_index, out_mv, op_ma);
3512 port->pps_data.req_op_curr = op_ma;
3513 port->pps_data.req_out_volt = out_mv;
3518 static int tcpm_pd_send_pps_request(struct tcpm_port *port)
3520 struct pd_message msg;
3524 ret = tcpm_pd_build_pps_request(port, &rdo);
3528 /* Relax the threshold as voltage will be adjusted right after Accept Message. */
3529 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
3531 memset(&msg, 0, sizeof(msg));
3532 msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
3535 port->negotiated_rev,
3536 port->message_id, 1);
3537 msg.payload[0] = cpu_to_le32(rdo);
3539 return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
3542 static int tcpm_set_vbus(struct tcpm_port *port, bool enable)
3546 if (enable && port->vbus_charge)
3549 tcpm_log(port, "vbus:=%d charge=%d", enable, port->vbus_charge);
3551 ret = port->tcpc->set_vbus(port->tcpc, enable, port->vbus_charge);
3555 port->vbus_source = enable;
3559 static int tcpm_set_charge(struct tcpm_port *port, bool charge)
3563 if (charge && port->vbus_source)
3566 if (charge != port->vbus_charge) {
3567 tcpm_log(port, "vbus=%d charge:=%d", port->vbus_source, charge);
3568 ret = port->tcpc->set_vbus(port->tcpc, port->vbus_source,
3573 port->vbus_charge = charge;
3574 power_supply_changed(port->psy);
3578 static bool tcpm_start_toggling(struct tcpm_port *port, enum typec_cc_status cc)
3582 if (!port->tcpc->start_toggling)
3585 tcpm_log_force(port, "Start toggling");
3586 ret = port->tcpc->start_toggling(port->tcpc, port->port_type, cc);
3590 static int tcpm_init_vbus(struct tcpm_port *port)
3594 ret = port->tcpc->set_vbus(port->tcpc, false, false);
3595 port->vbus_source = false;
3596 port->vbus_charge = false;
3600 static int tcpm_init_vconn(struct tcpm_port *port)
3604 ret = port->tcpc->set_vconn(port->tcpc, false);
3605 port->vconn_role = TYPEC_SINK;
3609 static void tcpm_typec_connect(struct tcpm_port *port)
3611 if (!port->connected) {
3612 /* Make sure we don't report stale identity information */
3613 memset(&port->partner_ident, 0, sizeof(port->partner_ident));
3614 port->partner_desc.usb_pd = port->pd_capable;
3615 if (tcpm_port_is_debug(port))
3616 port->partner_desc.accessory = TYPEC_ACCESSORY_DEBUG;
3617 else if (tcpm_port_is_audio(port))
3618 port->partner_desc.accessory = TYPEC_ACCESSORY_AUDIO;
3620 port->partner_desc.accessory = TYPEC_ACCESSORY_NONE;
3621 port->partner = typec_register_partner(port->typec_port,
3622 &port->partner_desc);
3623 port->connected = true;
3624 typec_partner_set_usb_power_delivery(port->partner, port->partner_pd);
3628 static int tcpm_src_attach(struct tcpm_port *port)
3630 enum typec_cc_polarity polarity =
3631 port->cc2 == TYPEC_CC_RD ? TYPEC_POLARITY_CC2
3632 : TYPEC_POLARITY_CC1;
3638 ret = tcpm_set_polarity(port, polarity);
3642 tcpm_enable_auto_vbus_discharge(port, true);
3644 ret = tcpm_set_roles(port, true, TYPEC_SOURCE, tcpm_data_role_for_source(port));
3648 if (port->pd_supported) {
3649 ret = port->tcpc->set_pd_rx(port->tcpc, true);
3651 goto out_disable_mux;
3655 * USB Type-C specification, version 1.2,
3656 * chapter 4.5.2.2.8.1 (Attached.SRC Requirements)
3657 * Enable VCONN only if the non-RD port is set to RA.
3659 if ((polarity == TYPEC_POLARITY_CC1 && port->cc2 == TYPEC_CC_RA) ||
3660 (polarity == TYPEC_POLARITY_CC2 && port->cc1 == TYPEC_CC_RA)) {
3661 ret = tcpm_set_vconn(port, true);
3663 goto out_disable_pd;
3666 ret = tcpm_set_vbus(port, true);
3668 goto out_disable_vconn;
3670 port->pd_capable = false;
3672 port->partner = NULL;
3674 port->attached = true;
3675 port->send_discover = true;
3680 tcpm_set_vconn(port, false);
3682 if (port->pd_supported)
3683 port->tcpc->set_pd_rx(port->tcpc, false);
3685 tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
3686 TYPEC_ORIENTATION_NONE);
3690 static void tcpm_typec_disconnect(struct tcpm_port *port)
3692 if (port->connected) {
3693 typec_partner_set_usb_power_delivery(port->partner, NULL);
3694 typec_unregister_partner(port->partner);
3695 port->partner = NULL;
3696 port->connected = false;
3700 static void tcpm_unregister_altmodes(struct tcpm_port *port)
3702 struct pd_mode_data *modep = &port->mode_data;
3705 for (i = 0; i < modep->altmodes; i++) {
3706 typec_unregister_altmode(port->partner_altmode[i]);
3707 port->partner_altmode[i] = NULL;
3710 memset(modep, 0, sizeof(*modep));
3713 static void tcpm_set_partner_usb_comm_capable(struct tcpm_port *port, bool capable)
3715 tcpm_log(port, "Setting usb_comm capable %s", capable ? "true" : "false");
3717 if (port->tcpc->set_partner_usb_comm_capable)
3718 port->tcpc->set_partner_usb_comm_capable(port->tcpc, capable);
3721 static void tcpm_reset_port(struct tcpm_port *port)
3723 tcpm_enable_auto_vbus_discharge(port, false);
3724 port->in_ams = false;
3725 port->ams = NONE_AMS;
3726 port->vdm_sm_running = false;
3727 tcpm_unregister_altmodes(port);
3728 tcpm_typec_disconnect(port);
3729 port->attached = false;
3730 port->pd_capable = false;
3731 port->pps_data.supported = false;
3732 tcpm_set_partner_usb_comm_capable(port, false);
3735 * First Rx ID should be 0; set this to a sentinel of -1 so that
3736 * we can check tcpm_pd_rx_handler() if we had seen it before.
3738 port->rx_msgid = -1;
3740 port->tcpc->set_pd_rx(port->tcpc, false);
3741 tcpm_init_vbus(port); /* also disables charging */
3742 tcpm_init_vconn(port);
3743 tcpm_set_current_limit(port, 0, 0);
3744 tcpm_set_polarity(port, TYPEC_POLARITY_CC1);
3745 tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
3746 TYPEC_ORIENTATION_NONE);
3747 tcpm_set_attached_state(port, false);
3748 port->try_src_count = 0;
3749 port->try_snk_count = 0;
3750 port->usb_type = POWER_SUPPLY_USB_TYPE_C;
3751 power_supply_changed(port->psy);
3752 port->nr_sink_caps = 0;
3753 port->sink_cap_done = false;
3754 if (port->tcpc->enable_frs)
3755 port->tcpc->enable_frs(port->tcpc, false);
3757 usb_power_delivery_unregister_capabilities(port->partner_sink_caps);
3758 port->partner_sink_caps = NULL;
3759 usb_power_delivery_unregister_capabilities(port->partner_source_caps);
3760 port->partner_source_caps = NULL;
3761 usb_power_delivery_unregister(port->partner_pd);
3762 port->partner_pd = NULL;
3765 static void tcpm_detach(struct tcpm_port *port)
3767 if (tcpm_port_is_disconnected(port))
3768 port->hard_reset_count = 0;
3770 if (!port->attached)
3773 if (port->tcpc->set_bist_data) {
3774 tcpm_log(port, "disable BIST MODE TESTDATA");
3775 port->tcpc->set_bist_data(port->tcpc, false);
3778 tcpm_reset_port(port);
3781 static void tcpm_src_detach(struct tcpm_port *port)
3786 static int tcpm_snk_attach(struct tcpm_port *port)
3793 ret = tcpm_set_polarity(port, port->cc2 != TYPEC_CC_OPEN ?
3794 TYPEC_POLARITY_CC2 : TYPEC_POLARITY_CC1);
3798 tcpm_enable_auto_vbus_discharge(port, true);
3800 ret = tcpm_set_roles(port, true, TYPEC_SINK, tcpm_data_role_for_sink(port));
3804 port->pd_capable = false;
3806 port->partner = NULL;
3808 port->attached = true;
3809 port->send_discover = true;
3814 static void tcpm_snk_detach(struct tcpm_port *port)
3819 static int tcpm_acc_attach(struct tcpm_port *port)
3826 ret = tcpm_set_roles(port, true, TYPEC_SOURCE,
3827 tcpm_data_role_for_source(port));
3831 port->partner = NULL;
3833 tcpm_typec_connect(port);
3835 port->attached = true;
3840 static void tcpm_acc_detach(struct tcpm_port *port)
3845 static inline enum tcpm_state hard_reset_state(struct tcpm_port *port)
3847 if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
3848 return HARD_RESET_SEND;
3849 if (port->pd_capable)
3850 return ERROR_RECOVERY;
3851 if (port->pwr_role == TYPEC_SOURCE)
3852 return SRC_UNATTACHED;
3853 if (port->state == SNK_WAIT_CAPABILITIES)
3855 return SNK_UNATTACHED;
3858 static inline enum tcpm_state unattached_state(struct tcpm_port *port)
3860 if (port->port_type == TYPEC_PORT_DRP) {
3861 if (port->pwr_role == TYPEC_SOURCE)
3862 return SRC_UNATTACHED;
3864 return SNK_UNATTACHED;
3865 } else if (port->port_type == TYPEC_PORT_SRC) {
3866 return SRC_UNATTACHED;
3869 return SNK_UNATTACHED;
3872 static void tcpm_swap_complete(struct tcpm_port *port, int result)
3874 if (port->swap_pending) {
3875 port->swap_status = result;
3876 port->swap_pending = false;
3877 port->non_pd_role_swap = false;
3878 complete(&port->swap_complete);
3882 static enum typec_pwr_opmode tcpm_get_pwr_opmode(enum typec_cc_status cc)
3885 case TYPEC_CC_RP_1_5:
3886 return TYPEC_PWR_MODE_1_5A;
3887 case TYPEC_CC_RP_3_0:
3888 return TYPEC_PWR_MODE_3_0A;
3889 case TYPEC_CC_RP_DEF:
3891 return TYPEC_PWR_MODE_USB;
3895 static enum typec_cc_status tcpm_pwr_opmode_to_rp(enum typec_pwr_opmode opmode)
3898 case TYPEC_PWR_MODE_USB:
3899 return TYPEC_CC_RP_DEF;
3900 case TYPEC_PWR_MODE_1_5A:
3901 return TYPEC_CC_RP_1_5;
3902 case TYPEC_PWR_MODE_3_0A:
3903 case TYPEC_PWR_MODE_PD:
3905 return TYPEC_CC_RP_3_0;
3909 static void run_state_machine(struct tcpm_port *port)
3912 enum typec_pwr_opmode opmode;
3914 enum tcpm_state upcoming_state;
3916 if (port->tcpc->check_contaminant && port->state != CHECK_CONTAMINANT)
3917 port->potential_contaminant = ((port->enter_state == SRC_ATTACH_WAIT &&
3918 port->state == SRC_UNATTACHED) ||
3919 (port->enter_state == SNK_ATTACH_WAIT &&
3920 port->state == SNK_UNATTACHED));
3922 port->enter_state = port->state;
3923 switch (port->state) {
3926 case CHECK_CONTAMINANT:
3927 port->tcpc->check_contaminant(port->tcpc);
3930 case SRC_UNATTACHED:
3931 if (!port->non_pd_role_swap)
3932 tcpm_swap_complete(port, -ENOTCONN);
3933 tcpm_src_detach(port);
3934 if (port->potential_contaminant) {
3935 tcpm_set_state(port, CHECK_CONTAMINANT, 0);
3938 if (tcpm_start_toggling(port, tcpm_rp_cc(port))) {
3939 tcpm_set_state(port, TOGGLING, 0);
3942 tcpm_set_cc(port, tcpm_rp_cc(port));
3943 if (port->port_type == TYPEC_PORT_DRP)
3944 tcpm_set_state(port, SNK_UNATTACHED, PD_T_DRP_SNK);
3946 case SRC_ATTACH_WAIT:
3947 if (tcpm_port_is_debug(port))
3948 tcpm_set_state(port, DEBUG_ACC_ATTACHED,
3950 else if (tcpm_port_is_audio(port))
3951 tcpm_set_state(port, AUDIO_ACC_ATTACHED,
3953 else if (tcpm_port_is_source(port) && port->vbus_vsafe0v)
3954 tcpm_set_state(port,
3955 tcpm_try_snk(port) ? SNK_TRY
3961 port->try_snk_count++;
3964 * - Do not drive vconn or vbus
3965 * - Terminate CC pins (both) to Rd
3967 * - Wait for tDRPTry (PD_T_DRP_TRY).
3968 * Until then, ignore any state changes.
3970 tcpm_set_cc(port, TYPEC_CC_RD);
3971 tcpm_set_state(port, SNK_TRY_WAIT, PD_T_DRP_TRY);
3974 if (tcpm_port_is_sink(port)) {
3975 tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE, 0);
3977 tcpm_set_state(port, SRC_TRYWAIT, 0);
3981 case SNK_TRY_WAIT_DEBOUNCE:
3982 tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS,
3983 PD_T_TRY_CC_DEBOUNCE);
3985 case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
3986 if (port->vbus_present && tcpm_port_is_sink(port))
3987 tcpm_set_state(port, SNK_ATTACHED, 0);
3992 tcpm_set_cc(port, tcpm_rp_cc(port));
3993 if (port->max_wait == 0) {
3994 port->max_wait = jiffies +
3995 msecs_to_jiffies(PD_T_DRP_TRY);
3996 tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
3999 if (time_is_after_jiffies(port->max_wait))
4000 tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
4001 jiffies_to_msecs(port->max_wait -
4004 tcpm_set_state(port, SNK_UNATTACHED, 0);
4007 case SRC_TRYWAIT_DEBOUNCE:
4008 tcpm_set_state(port, SRC_ATTACHED, PD_T_CC_DEBOUNCE);
4010 case SRC_TRYWAIT_UNATTACHED:
4011 tcpm_set_state(port, SNK_UNATTACHED, 0);
4015 ret = tcpm_src_attach(port);
4016 tcpm_set_state(port, SRC_UNATTACHED,
4017 ret < 0 ? 0 : PD_T_PS_SOURCE_ON);
4020 opmode = tcpm_get_pwr_opmode(tcpm_rp_cc(port));
4021 typec_set_pwr_opmode(port->typec_port, opmode);
4022 port->pwr_opmode = TYPEC_PWR_MODE_USB;
4023 port->caps_count = 0;
4024 port->negotiated_rev = PD_MAX_REV;
4025 port->message_id = 0;
4026 port->rx_msgid = -1;
4027 port->explicit_contract = false;
4028 /* SNK -> SRC POWER/FAST_ROLE_SWAP finished */
4029 if (port->ams == POWER_ROLE_SWAP ||
4030 port->ams == FAST_ROLE_SWAP)
4031 tcpm_ams_finish(port);
4032 if (!port->pd_supported) {
4033 tcpm_set_state(port, SRC_READY, 0);
4036 port->upcoming_state = SRC_SEND_CAPABILITIES;
4037 tcpm_ams_start(port, POWER_NEGOTIATION);
4039 case SRC_SEND_CAPABILITIES:
4041 if (port->caps_count > PD_N_CAPS_COUNT) {
4042 tcpm_set_state(port, SRC_READY, 0);
4045 ret = tcpm_pd_send_source_caps(port);
4047 tcpm_set_state(port, SRC_SEND_CAPABILITIES,
4048 PD_T_SEND_SOURCE_CAP);
4051 * Per standard, we should clear the reset counter here.
4052 * However, that can result in state machine hang-ups.
4053 * Reset it only in READY state to improve stability.
4055 /* port->hard_reset_count = 0; */
4056 port->caps_count = 0;
4057 port->pd_capable = true;
4058 tcpm_set_state_cond(port, SRC_SEND_CAPABILITIES_TIMEOUT,
4059 PD_T_SEND_SOURCE_CAP);
4062 case SRC_SEND_CAPABILITIES_TIMEOUT:
4064 * Error recovery for a PD_DATA_SOURCE_CAP reply timeout.
4066 * PD 2.0 sinks are supposed to accept src-capabilities with a
4067 * 3.0 header and simply ignore any src PDOs which the sink does
4068 * not understand such as PPS but some 2.0 sinks instead ignore
4069 * the entire PD_DATA_SOURCE_CAP message, causing contract
4070 * negotiation to fail.
4072 * After PD_N_HARD_RESET_COUNT hard-reset attempts, we try
4073 * sending src-capabilities with a lower PD revision to
4074 * make these broken sinks work.
4076 if (port->hard_reset_count < PD_N_HARD_RESET_COUNT) {
4077 tcpm_set_state(port, HARD_RESET_SEND, 0);
4078 } else if (port->negotiated_rev > PD_REV20) {
4079 port->negotiated_rev--;
4080 port->hard_reset_count = 0;
4081 tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
4083 tcpm_set_state(port, hard_reset_state(port), 0);
4086 case SRC_NEGOTIATE_CAPABILITIES:
4087 ret = tcpm_pd_check_request(port);
4089 tcpm_pd_send_control(port, PD_CTRL_REJECT);
4090 if (!port->explicit_contract) {
4091 tcpm_set_state(port,
4092 SRC_WAIT_NEW_CAPABILITIES, 0);
4094 tcpm_set_state(port, SRC_READY, 0);
4097 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
4098 tcpm_set_partner_usb_comm_capable(port,
4099 !!(port->sink_request & RDO_USB_COMM));
4100 tcpm_set_state(port, SRC_TRANSITION_SUPPLY,
4101 PD_T_SRC_TRANSITION);
4104 case SRC_TRANSITION_SUPPLY:
4105 /* XXX: regulator_set_voltage(vbus, ...) */
4106 tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
4107 port->explicit_contract = true;
4108 typec_set_pwr_opmode(port->typec_port, TYPEC_PWR_MODE_PD);
4109 port->pwr_opmode = TYPEC_PWR_MODE_PD;
4110 tcpm_set_state_cond(port, SRC_READY, 0);
4114 port->hard_reset_count = 0;
4116 port->try_src_count = 0;
4118 tcpm_swap_complete(port, 0);
4119 tcpm_typec_connect(port);
4121 if (port->ams != NONE_AMS)
4122 tcpm_ams_finish(port);
4123 if (port->next_ams != NONE_AMS) {
4124 port->ams = port->next_ams;
4125 port->next_ams = NONE_AMS;
4129 * If previous AMS is interrupted, switch to the upcoming
4132 if (port->upcoming_state != INVALID_STATE) {
4133 upcoming_state = port->upcoming_state;
4134 port->upcoming_state = INVALID_STATE;
4135 tcpm_set_state(port, upcoming_state, 0);
4140 * 6.4.4.3.1 Discover Identity
4141 * "The Discover Identity Command Shall only be sent to SOP when there is an
4142 * Explicit Contract."
4143 * For now, this driver only supports SOP for DISCOVER_IDENTITY, thus using
4144 * port->explicit_contract to decide whether to send the command.
4146 if (port->explicit_contract)
4147 mod_send_discover_delayed_work(port, 0);
4149 port->send_discover = false;
4153 * Sending ping messages is not necessary if
4154 * - the source operates at vSafe5V
4156 * - The system is not operating in PD mode
4158 * - Both partners are connected using a Type-C connector
4160 * There is no actual need to send PD messages since the local
4161 * port type-c and the spec does not clearly say whether PD is
4162 * possible when type-c is connected to Type-A/B
4165 case SRC_WAIT_NEW_CAPABILITIES:
4166 /* Nothing to do... */
4170 case SNK_UNATTACHED:
4171 if (!port->non_pd_role_swap)
4172 tcpm_swap_complete(port, -ENOTCONN);
4173 tcpm_pps_complete(port, -ENOTCONN);
4174 tcpm_snk_detach(port);
4175 if (port->potential_contaminant) {
4176 tcpm_set_state(port, CHECK_CONTAMINANT, 0);
4179 if (tcpm_start_toggling(port, TYPEC_CC_RD)) {
4180 tcpm_set_state(port, TOGGLING, 0);
4183 tcpm_set_cc(port, TYPEC_CC_RD);
4184 if (port->port_type == TYPEC_PORT_DRP)
4185 tcpm_set_state(port, SRC_UNATTACHED, PD_T_DRP_SRC);
4187 case SNK_ATTACH_WAIT:
4188 if ((port->cc1 == TYPEC_CC_OPEN &&
4189 port->cc2 != TYPEC_CC_OPEN) ||
4190 (port->cc1 != TYPEC_CC_OPEN &&
4191 port->cc2 == TYPEC_CC_OPEN))
4192 tcpm_set_state(port, SNK_DEBOUNCED,
4194 else if (tcpm_port_is_disconnected(port))
4195 tcpm_set_state(port, SNK_UNATTACHED,
4199 if (tcpm_port_is_disconnected(port))
4200 tcpm_set_state(port, SNK_UNATTACHED,
4202 else if (port->vbus_present)
4203 tcpm_set_state(port,
4204 tcpm_try_src(port) ? SRC_TRY
4209 port->try_src_count++;
4210 tcpm_set_cc(port, tcpm_rp_cc(port));
4212 tcpm_set_state(port, SRC_TRY_WAIT, 0);
4215 if (port->max_wait == 0) {
4216 port->max_wait = jiffies +
4217 msecs_to_jiffies(PD_T_DRP_TRY);
4218 msecs = PD_T_DRP_TRY;
4220 if (time_is_after_jiffies(port->max_wait))
4221 msecs = jiffies_to_msecs(port->max_wait -
4226 tcpm_set_state(port, SNK_TRYWAIT, msecs);
4228 case SRC_TRY_DEBOUNCE:
4229 tcpm_set_state(port, SRC_ATTACHED, PD_T_PD_DEBOUNCE);
4232 tcpm_set_cc(port, TYPEC_CC_RD);
4233 tcpm_set_state(port, SNK_TRYWAIT_VBUS, PD_T_CC_DEBOUNCE);
4235 case SNK_TRYWAIT_VBUS:
4237 * TCPM stays in this state indefinitely until VBUS
4238 * is detected as long as Rp is not detected for
4239 * more than a time period of tPDDebounce.
4241 if (port->vbus_present && tcpm_port_is_sink(port)) {
4242 tcpm_set_state(port, SNK_ATTACHED, 0);
4245 if (!tcpm_port_is_sink(port))
4246 tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
4248 case SNK_TRYWAIT_DEBOUNCE:
4249 tcpm_set_state(port, SNK_UNATTACHED, PD_T_PD_DEBOUNCE);
4252 ret = tcpm_snk_attach(port);
4254 tcpm_set_state(port, SNK_UNATTACHED, 0);
4256 tcpm_set_state(port, SNK_STARTUP, 0);
4259 opmode = tcpm_get_pwr_opmode(port->polarity ?
4260 port->cc2 : port->cc1);
4261 typec_set_pwr_opmode(port->typec_port, opmode);
4262 port->pwr_opmode = TYPEC_PWR_MODE_USB;
4263 port->negotiated_rev = PD_MAX_REV;
4264 port->message_id = 0;
4265 port->rx_msgid = -1;
4266 port->explicit_contract = false;
4268 if (port->ams == POWER_ROLE_SWAP ||
4269 port->ams == FAST_ROLE_SWAP)
4270 /* SRC -> SNK POWER/FAST_ROLE_SWAP finished */
4271 tcpm_ams_finish(port);
4273 tcpm_set_state(port, SNK_DISCOVERY, 0);
4276 if (port->vbus_present) {
4277 u32 current_lim = tcpm_get_current_limit(port);
4279 if (port->slow_charger_loop && (current_lim > PD_P_SNK_STDBY_MW / 5))
4280 current_lim = PD_P_SNK_STDBY_MW / 5;
4281 tcpm_set_current_limit(port, current_lim, 5000);
4282 tcpm_set_charge(port, true);
4283 if (!port->pd_supported)
4284 tcpm_set_state(port, SNK_READY, 0);
4286 tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
4290 * For DRP, timeouts differ. Also, handling is supposed to be
4291 * different and much more complex (dead battery detection;
4292 * see USB power delivery specification, section 8.3.3.6.1.5.1).
4294 tcpm_set_state(port, hard_reset_state(port),
4295 port->port_type == TYPEC_PORT_DRP ?
4296 PD_T_DB_DETECT : PD_T_NO_RESPONSE);
4298 case SNK_DISCOVERY_DEBOUNCE:
4299 tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE_DONE,
4302 case SNK_DISCOVERY_DEBOUNCE_DONE:
4303 if (!tcpm_port_is_disconnected(port) &&
4304 tcpm_port_is_sink(port) &&
4305 ktime_after(port->delayed_runtime, ktime_get())) {
4306 tcpm_set_state(port, SNK_DISCOVERY,
4307 ktime_to_ms(ktime_sub(port->delayed_runtime, ktime_get())));
4310 tcpm_set_state(port, unattached_state(port), 0);
4312 case SNK_WAIT_CAPABILITIES:
4313 ret = port->tcpc->set_pd_rx(port->tcpc, true);
4315 tcpm_set_state(port, SNK_READY, 0);
4319 * If VBUS has never been low, and we time out waiting
4320 * for source cap, try a soft reset first, in case we
4321 * were already in a stable contract before this boot.
4322 * Do this only once.
4324 if (port->vbus_never_low) {
4325 port->vbus_never_low = false;
4326 tcpm_set_state(port, SNK_SOFT_RESET,
4327 PD_T_SINK_WAIT_CAP);
4329 tcpm_set_state(port, hard_reset_state(port),
4330 PD_T_SINK_WAIT_CAP);
4333 case SNK_NEGOTIATE_CAPABILITIES:
4334 port->pd_capable = true;
4335 tcpm_set_partner_usb_comm_capable(port,
4336 !!(port->source_caps[0] & PDO_FIXED_USB_COMM));
4337 port->hard_reset_count = 0;
4338 ret = tcpm_pd_send_request(port);
4340 /* Restore back to the original state */
4341 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
4342 port->pps_data.active,
4343 port->supply_voltage);
4344 /* Let the Source send capabilities again. */
4345 tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
4347 tcpm_set_state_cond(port, hard_reset_state(port),
4348 PD_T_SENDER_RESPONSE);
4351 case SNK_NEGOTIATE_PPS_CAPABILITIES:
4352 ret = tcpm_pd_send_pps_request(port);
4354 /* Restore back to the original state */
4355 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
4356 port->pps_data.active,
4357 port->supply_voltage);
4358 port->pps_status = ret;
4360 * If this was called due to updates to sink
4361 * capabilities, and pps is no longer valid, we should
4362 * safely fall back to a standard PDO.
4364 if (port->update_sink_caps)
4365 tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
4367 tcpm_set_state(port, SNK_READY, 0);
4369 tcpm_set_state_cond(port, hard_reset_state(port),
4370 PD_T_SENDER_RESPONSE);
4373 case SNK_TRANSITION_SINK:
4374 /* From the USB PD spec:
4375 * "The Sink Shall transition to Sink Standby before a positive or
4376 * negative voltage transition of VBUS. During Sink Standby
4377 * the Sink Shall reduce its power draw to pSnkStdby."
4379 * This is not applicable to PPS though as the port can continue
4380 * to draw negotiated power without switching to standby.
4382 if (port->supply_voltage != port->req_supply_voltage && !port->pps_data.active &&
4383 port->current_limit * port->supply_voltage / 1000 > PD_P_SNK_STDBY_MW) {
4384 u32 stdby_ma = PD_P_SNK_STDBY_MW * 1000 / port->supply_voltage;
4386 tcpm_log(port, "Setting standby current %u mV @ %u mA",
4387 port->supply_voltage, stdby_ma);
4388 tcpm_set_current_limit(port, stdby_ma, port->supply_voltage);
4391 case SNK_TRANSITION_SINK_VBUS:
4392 tcpm_set_state(port, hard_reset_state(port),
4393 PD_T_PS_TRANSITION);
4396 port->try_snk_count = 0;
4397 port->update_sink_caps = false;
4398 if (port->explicit_contract) {
4399 typec_set_pwr_opmode(port->typec_port,
4401 port->pwr_opmode = TYPEC_PWR_MODE_PD;
4404 if (!port->pd_capable && port->slow_charger_loop)
4405 tcpm_set_current_limit(port, tcpm_get_current_limit(port), 5000);
4406 tcpm_swap_complete(port, 0);
4407 tcpm_typec_connect(port);
4408 mod_enable_frs_delayed_work(port, 0);
4409 tcpm_pps_complete(port, port->pps_status);
4411 if (port->ams != NONE_AMS)
4412 tcpm_ams_finish(port);
4413 if (port->next_ams != NONE_AMS) {
4414 port->ams = port->next_ams;
4415 port->next_ams = NONE_AMS;
4419 * If previous AMS is interrupted, switch to the upcoming
4422 if (port->upcoming_state != INVALID_STATE) {
4423 upcoming_state = port->upcoming_state;
4424 port->upcoming_state = INVALID_STATE;
4425 tcpm_set_state(port, upcoming_state, 0);
4430 * 6.4.4.3.1 Discover Identity
4431 * "The Discover Identity Command Shall only be sent to SOP when there is an
4432 * Explicit Contract."
4433 * For now, this driver only supports SOP for DISCOVER_IDENTITY, thus using
4434 * port->explicit_contract.
4436 if (port->explicit_contract)
4437 mod_send_discover_delayed_work(port, 0);
4439 port->send_discover = false;
4441 power_supply_changed(port->psy);
4444 /* Accessory states */
4445 case ACC_UNATTACHED:
4446 tcpm_acc_detach(port);
4447 tcpm_set_state(port, SRC_UNATTACHED, 0);
4449 case DEBUG_ACC_ATTACHED:
4450 case AUDIO_ACC_ATTACHED:
4451 ret = tcpm_acc_attach(port);
4453 tcpm_set_state(port, ACC_UNATTACHED, 0);
4455 case AUDIO_ACC_DEBOUNCE:
4456 tcpm_set_state(port, ACC_UNATTACHED, PD_T_CC_DEBOUNCE);
4459 /* Hard_Reset states */
4460 case HARD_RESET_SEND:
4461 if (port->ams != NONE_AMS)
4462 tcpm_ams_finish(port);
4464 * State machine will be directed to HARD_RESET_START,
4465 * thus set upcoming_state to INVALID_STATE.
4467 port->upcoming_state = INVALID_STATE;
4468 tcpm_ams_start(port, HARD_RESET);
4470 case HARD_RESET_START:
4471 port->sink_cap_done = false;
4472 if (port->tcpc->enable_frs)
4473 port->tcpc->enable_frs(port->tcpc, false);
4474 port->hard_reset_count++;
4475 port->tcpc->set_pd_rx(port->tcpc, false);
4476 tcpm_unregister_altmodes(port);
4477 port->nr_sink_caps = 0;
4478 port->send_discover = true;
4479 if (port->pwr_role == TYPEC_SOURCE)
4480 tcpm_set_state(port, SRC_HARD_RESET_VBUS_OFF,
4481 PD_T_PS_HARD_RESET);
4483 tcpm_set_state(port, SNK_HARD_RESET_SINK_OFF, 0);
4485 case SRC_HARD_RESET_VBUS_OFF:
4487 * 7.1.5 Response to Hard Resets
4488 * Hard Reset Signaling indicates a communication failure has occurred and the
4489 * Source Shall stop driving VCONN, Shall remove Rp from the VCONN pin and Shall
4490 * drive VBUS to vSafe0V as shown in Figure 7-9.
4492 tcpm_set_vconn(port, false);
4493 tcpm_set_vbus(port, false);
4494 tcpm_set_roles(port, port->self_powered, TYPEC_SOURCE,
4495 tcpm_data_role_for_source(port));
4497 * If tcpc fails to notify vbus off, TCPM will wait for PD_T_SAFE_0V +
4498 * PD_T_SRC_RECOVER before turning vbus back on.
4499 * From Table 7-12 Sequence Description for a Source Initiated Hard Reset:
4500 * 4. Policy Engine waits tPSHardReset after sending Hard Reset Signaling and then
4501 * tells the Device Policy Manager to instruct the power supply to perform a
4502 * Hard Reset. The transition to vSafe0V Shall occur within tSafe0V (t2).
4503 * 5. After tSrcRecover the Source applies power to VBUS in an attempt to
4504 * re-establish communication with the Sink and resume USB Default Operation.
4505 * The transition to vSafe5V Shall occur within tSrcTurnOn(t4).
4507 tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SAFE_0V + PD_T_SRC_RECOVER);
4509 case SRC_HARD_RESET_VBUS_ON:
4510 tcpm_set_vconn(port, true);
4511 tcpm_set_vbus(port, true);
4512 if (port->ams == HARD_RESET)
4513 tcpm_ams_finish(port);
4514 if (port->pd_supported)
4515 port->tcpc->set_pd_rx(port->tcpc, true);
4516 tcpm_set_attached_state(port, true);
4517 tcpm_set_state(port, SRC_UNATTACHED, PD_T_PS_SOURCE_ON);
4519 case SNK_HARD_RESET_SINK_OFF:
4520 /* Do not discharge/disconnect during hard reseet */
4521 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
4522 memset(&port->pps_data, 0, sizeof(port->pps_data));
4523 tcpm_set_vconn(port, false);
4524 if (port->pd_capable)
4525 tcpm_set_charge(port, false);
4526 tcpm_set_roles(port, port->self_powered, TYPEC_SINK,
4527 tcpm_data_role_for_sink(port));
4529 * VBUS may or may not toggle, depending on the adapter.
4530 * If it doesn't toggle, transition to SNK_HARD_RESET_SINK_ON
4531 * directly after timeout.
4533 tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, PD_T_SAFE_0V);
4535 case SNK_HARD_RESET_WAIT_VBUS:
4536 if (port->ams == HARD_RESET)
4537 tcpm_ams_finish(port);
4538 /* Assume we're disconnected if VBUS doesn't come back. */
4539 tcpm_set_state(port, SNK_UNATTACHED,
4540 PD_T_SRC_RECOVER_MAX + PD_T_SRC_TURN_ON);
4542 case SNK_HARD_RESET_SINK_ON:
4543 /* Note: There is no guarantee that VBUS is on in this state */
4546 * The specification suggests that dual mode ports in sink
4547 * mode should transition to state PE_SRC_Transition_to_default.
4548 * See USB power delivery specification chapter 8.3.3.6.1.3.
4549 * This would mean to
4550 * - turn off VCONN, reset power supply
4551 * - request hardware reset
4553 * - Transition to state PE_Src_Startup
4554 * SNK only ports shall transition to state Snk_Startup
4555 * (see chapter 8.3.3.3.8).
4556 * Similar, dual-mode ports in source mode should transition
4557 * to PE_SNK_Transition_to_default.
4559 if (port->pd_capable) {
4560 tcpm_set_current_limit(port,
4561 tcpm_get_current_limit(port),
4563 tcpm_set_charge(port, true);
4565 if (port->ams == HARD_RESET)
4566 tcpm_ams_finish(port);
4567 tcpm_set_attached_state(port, true);
4568 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, VSAFE5V);
4569 tcpm_set_state(port, SNK_STARTUP, 0);
4572 /* Soft_Reset states */
4574 port->message_id = 0;
4575 port->rx_msgid = -1;
4576 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
4577 tcpm_ams_finish(port);
4578 if (port->pwr_role == TYPEC_SOURCE) {
4579 port->upcoming_state = SRC_SEND_CAPABILITIES;
4580 tcpm_ams_start(port, POWER_NEGOTIATION);
4582 tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
4585 case SRC_SOFT_RESET_WAIT_SNK_TX:
4586 case SNK_SOFT_RESET:
4587 if (port->ams != NONE_AMS)
4588 tcpm_ams_finish(port);
4589 port->upcoming_state = SOFT_RESET_SEND;
4590 tcpm_ams_start(port, SOFT_RESET_AMS);
4592 case SOFT_RESET_SEND:
4593 port->message_id = 0;
4594 port->rx_msgid = -1;
4595 if (tcpm_pd_send_control(port, PD_CTRL_SOFT_RESET))
4596 tcpm_set_state_cond(port, hard_reset_state(port), 0);
4598 tcpm_set_state_cond(port, hard_reset_state(port),
4599 PD_T_SENDER_RESPONSE);
4602 /* DR_Swap states */
4604 tcpm_pd_send_control(port, PD_CTRL_DR_SWAP);
4605 if (port->data_role == TYPEC_DEVICE || port->negotiated_rev > PD_REV20)
4606 port->send_discover = true;
4607 tcpm_set_state_cond(port, DR_SWAP_SEND_TIMEOUT,
4608 PD_T_SENDER_RESPONSE);
4610 case DR_SWAP_ACCEPT:
4611 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
4612 if (port->data_role == TYPEC_DEVICE || port->negotiated_rev > PD_REV20)
4613 port->send_discover = true;
4614 tcpm_set_state_cond(port, DR_SWAP_CHANGE_DR, 0);
4616 case DR_SWAP_SEND_TIMEOUT:
4617 tcpm_swap_complete(port, -ETIMEDOUT);
4618 port->send_discover = false;
4619 tcpm_ams_finish(port);
4620 tcpm_set_state(port, ready_state(port), 0);
4622 case DR_SWAP_CHANGE_DR:
4623 tcpm_unregister_altmodes(port);
4624 if (port->data_role == TYPEC_HOST)
4625 tcpm_set_roles(port, true, port->pwr_role,
4628 tcpm_set_roles(port, true, port->pwr_role,
4630 tcpm_ams_finish(port);
4631 tcpm_set_state(port, ready_state(port), 0);
4635 if (tcpm_pd_send_control(port, PD_CTRL_FR_SWAP)) {
4636 tcpm_set_state(port, ERROR_RECOVERY, 0);
4639 tcpm_set_state_cond(port, FR_SWAP_SEND_TIMEOUT, PD_T_SENDER_RESPONSE);
4641 case FR_SWAP_SEND_TIMEOUT:
4642 tcpm_set_state(port, ERROR_RECOVERY, 0);
4644 case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
4645 tcpm_set_state(port, ERROR_RECOVERY, PD_T_PS_SOURCE_OFF);
4647 case FR_SWAP_SNK_SRC_NEW_SINK_READY:
4648 if (port->vbus_source)
4649 tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
4651 tcpm_set_state(port, ERROR_RECOVERY, PD_T_RECEIVER_RESPONSE);
4653 case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
4654 tcpm_set_pwr_role(port, TYPEC_SOURCE);
4655 if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY)) {
4656 tcpm_set_state(port, ERROR_RECOVERY, 0);
4659 tcpm_set_cc(port, tcpm_rp_cc(port));
4660 tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
4663 /* PR_Swap states */
4664 case PR_SWAP_ACCEPT:
4665 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
4666 tcpm_set_state(port, PR_SWAP_START, 0);
4669 tcpm_pd_send_control(port, PD_CTRL_PR_SWAP);
4670 tcpm_set_state_cond(port, PR_SWAP_SEND_TIMEOUT,
4671 PD_T_SENDER_RESPONSE);
4673 case PR_SWAP_SEND_TIMEOUT:
4674 tcpm_swap_complete(port, -ETIMEDOUT);
4675 tcpm_set_state(port, ready_state(port), 0);
4678 tcpm_apply_rc(port);
4679 if (port->pwr_role == TYPEC_SOURCE)
4680 tcpm_set_state(port, PR_SWAP_SRC_SNK_TRANSITION_OFF,
4681 PD_T_SRC_TRANSITION);
4683 tcpm_set_state(port, PR_SWAP_SNK_SRC_SINK_OFF, 0);
4685 case PR_SWAP_SRC_SNK_TRANSITION_OFF:
4687 * Prevent vbus discharge circuit from turning on during PR_SWAP
4688 * as this is not a disconnect.
4690 tcpm_set_vbus(port, false);
4691 port->explicit_contract = false;
4692 /* allow time for Vbus discharge, must be < tSrcSwapStdby */
4693 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF,
4696 case PR_SWAP_SRC_SNK_SOURCE_OFF:
4697 tcpm_set_cc(port, TYPEC_CC_RD);
4698 /* allow CC debounce */
4699 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED,
4702 case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
4704 * USB-PD standard, 6.2.1.4, Port Power Role:
4705 * "During the Power Role Swap Sequence, for the initial Source
4706 * Port, the Port Power Role field shall be set to Sink in the
4707 * PS_RDY Message indicating that the initial Source’s power
4708 * supply is turned off"
4710 tcpm_set_pwr_role(port, TYPEC_SINK);
4711 if (tcpm_pd_send_control(port, PD_CTRL_PS_RDY)) {
4712 tcpm_set_state(port, ERROR_RECOVERY, 0);
4715 tcpm_set_state(port, ERROR_RECOVERY, PD_T_PS_SOURCE_ON_PRS);
4717 case PR_SWAP_SRC_SNK_SINK_ON:
4718 tcpm_enable_auto_vbus_discharge(port, true);
4719 /* Set the vbus disconnect threshold for implicit contract */
4720 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, VSAFE5V);
4721 tcpm_set_state(port, SNK_STARTUP, 0);
4723 case PR_SWAP_SNK_SRC_SINK_OFF:
4725 * Prevent vbus discharge circuit from turning on during PR_SWAP
4726 * as this is not a disconnect.
4728 tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB,
4729 port->pps_data.active, 0);
4730 tcpm_set_charge(port, false);
4731 tcpm_set_state(port, hard_reset_state(port),
4732 PD_T_PS_SOURCE_OFF);
4734 case PR_SWAP_SNK_SRC_SOURCE_ON:
4735 tcpm_enable_auto_vbus_discharge(port, true);
4736 tcpm_set_cc(port, tcpm_rp_cc(port));
4737 tcpm_set_vbus(port, true);
4739 * allow time VBUS ramp-up, must be < tNewSrc
4740 * Also, this window overlaps with CC debounce as well.
4741 * So, Wait for the max of two which is PD_T_NEWSRC
4743 tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP,
4746 case PR_SWAP_SNK_SRC_SOURCE_ON_VBUS_RAMPED_UP:
4748 * USB PD standard, 6.2.1.4:
4749 * "Subsequent Messages initiated by the Policy Engine,
4750 * such as the PS_RDY Message sent to indicate that Vbus
4751 * is ready, will have the Port Power Role field set to
4754 tcpm_set_pwr_role(port, TYPEC_SOURCE);
4755 tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
4756 tcpm_set_state(port, SRC_STARTUP, PD_T_SWAP_SRC_START);
4759 case VCONN_SWAP_ACCEPT:
4760 tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
4761 tcpm_ams_finish(port);
4762 tcpm_set_state(port, VCONN_SWAP_START, 0);
4764 case VCONN_SWAP_SEND:
4765 tcpm_pd_send_control(port, PD_CTRL_VCONN_SWAP);
4766 tcpm_set_state(port, VCONN_SWAP_SEND_TIMEOUT,
4767 PD_T_SENDER_RESPONSE);
4769 case VCONN_SWAP_SEND_TIMEOUT:
4770 tcpm_swap_complete(port, -ETIMEDOUT);
4771 tcpm_set_state(port, ready_state(port), 0);
4773 case VCONN_SWAP_START:
4774 if (port->vconn_role == TYPEC_SOURCE)
4775 tcpm_set_state(port, VCONN_SWAP_WAIT_FOR_VCONN, 0);
4777 tcpm_set_state(port, VCONN_SWAP_TURN_ON_VCONN, 0);
4779 case VCONN_SWAP_WAIT_FOR_VCONN:
4780 tcpm_set_state(port, hard_reset_state(port),
4781 PD_T_VCONN_SOURCE_ON);
4783 case VCONN_SWAP_TURN_ON_VCONN:
4784 tcpm_set_vconn(port, true);
4785 tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
4786 tcpm_set_state(port, ready_state(port), 0);
4788 case VCONN_SWAP_TURN_OFF_VCONN:
4789 tcpm_set_vconn(port, false);
4790 tcpm_set_state(port, ready_state(port), 0);
4793 case DR_SWAP_CANCEL:
4794 case PR_SWAP_CANCEL:
4795 case VCONN_SWAP_CANCEL:
4796 tcpm_swap_complete(port, port->swap_status);
4797 if (port->pwr_role == TYPEC_SOURCE)
4798 tcpm_set_state(port, SRC_READY, 0);
4800 tcpm_set_state(port, SNK_READY, 0);
4802 case FR_SWAP_CANCEL:
4803 if (port->pwr_role == TYPEC_SOURCE)
4804 tcpm_set_state(port, SRC_READY, 0);
4806 tcpm_set_state(port, SNK_READY, 0);
4810 switch (BDO_MODE_MASK(port->bist_request)) {
4811 case BDO_MODE_CARRIER2:
4812 tcpm_pd_transmit(port, TCPC_TX_BIST_MODE_2, NULL);
4813 tcpm_set_state(port, unattached_state(port),
4814 PD_T_BIST_CONT_MODE);
4816 case BDO_MODE_TESTDATA:
4817 if (port->tcpc->set_bist_data) {
4818 tcpm_log(port, "Enable BIST MODE TESTDATA");
4819 port->tcpc->set_bist_data(port->tcpc, true);
4826 case GET_STATUS_SEND:
4827 tcpm_pd_send_control(port, PD_CTRL_GET_STATUS);
4828 tcpm_set_state(port, GET_STATUS_SEND_TIMEOUT,
4829 PD_T_SENDER_RESPONSE);
4831 case GET_STATUS_SEND_TIMEOUT:
4832 tcpm_set_state(port, ready_state(port), 0);
4834 case GET_PPS_STATUS_SEND:
4835 tcpm_pd_send_control(port, PD_CTRL_GET_PPS_STATUS);
4836 tcpm_set_state(port, GET_PPS_STATUS_SEND_TIMEOUT,
4837 PD_T_SENDER_RESPONSE);
4839 case GET_PPS_STATUS_SEND_TIMEOUT:
4840 tcpm_set_state(port, ready_state(port), 0);
4843 tcpm_pd_send_control(port, PD_CTRL_GET_SINK_CAP);
4844 tcpm_set_state(port, GET_SINK_CAP_TIMEOUT, PD_T_SENDER_RESPONSE);
4846 case GET_SINK_CAP_TIMEOUT:
4847 port->sink_cap_done = true;
4848 tcpm_set_state(port, ready_state(port), 0);
4850 case ERROR_RECOVERY:
4851 tcpm_swap_complete(port, -EPROTO);
4852 tcpm_pps_complete(port, -EPROTO);
4853 tcpm_set_state(port, PORT_RESET, 0);
4856 tcpm_reset_port(port);
4857 tcpm_set_cc(port, TYPEC_CC_OPEN);
4858 tcpm_set_state(port, PORT_RESET_WAIT_OFF,
4859 PD_T_ERROR_RECOVERY);
4861 case PORT_RESET_WAIT_OFF:
4862 tcpm_set_state(port,
4863 tcpm_default_state(port),
4864 port->vbus_present ? PD_T_PS_SOURCE_OFF : 0);
4867 /* AMS intermediate state */
4869 if (port->upcoming_state == INVALID_STATE) {
4870 tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
4871 SRC_READY : SNK_READY, 0);
4875 upcoming_state = port->upcoming_state;
4876 port->upcoming_state = INVALID_STATE;
4877 tcpm_set_state(port, upcoming_state, 0);
4881 case CHUNK_NOT_SUPP:
4882 tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP);
4883 tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ? SRC_READY : SNK_READY, 0);
4886 WARN(1, "Unexpected port state %d\n", port->state);
4891 static void tcpm_state_machine_work(struct kthread_work *work)
4893 struct tcpm_port *port = container_of(work, struct tcpm_port, state_machine);
4894 enum tcpm_state prev_state;
4896 mutex_lock(&port->lock);
4897 port->state_machine_running = true;
4899 if (port->queued_message && tcpm_send_queued_message(port))
4902 /* If we were queued due to a delayed state change, update it now */
4903 if (port->delayed_state) {
4904 tcpm_log(port, "state change %s -> %s [delayed %ld ms]",
4905 tcpm_states[port->state],
4906 tcpm_states[port->delayed_state], port->delay_ms);
4907 port->prev_state = port->state;
4908 port->state = port->delayed_state;
4909 port->delayed_state = INVALID_STATE;
4913 * Continue running as long as we have (non-delayed) state changes
4917 prev_state = port->state;
4918 run_state_machine(port);
4919 if (port->queued_message)
4920 tcpm_send_queued_message(port);
4921 } while (port->state != prev_state && !port->delayed_state);
4924 port->state_machine_running = false;
4925 mutex_unlock(&port->lock);
4928 static void _tcpm_cc_change(struct tcpm_port *port, enum typec_cc_status cc1,
4929 enum typec_cc_status cc2)
4931 enum typec_cc_status old_cc1, old_cc2;
4932 enum tcpm_state new_state;
4934 old_cc1 = port->cc1;
4935 old_cc2 = port->cc2;
4939 tcpm_log_force(port,
4940 "CC1: %u -> %u, CC2: %u -> %u [state %s, polarity %d, %s]",
4941 old_cc1, cc1, old_cc2, cc2, tcpm_states[port->state],
4943 tcpm_port_is_disconnected(port) ? "disconnected"
4946 switch (port->state) {
4948 if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
4949 tcpm_port_is_source(port))
4950 tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
4951 else if (tcpm_port_is_sink(port))
4952 tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
4954 case CHECK_CONTAMINANT:
4955 /* Wait for Toggling to be resumed */
4957 case SRC_UNATTACHED:
4958 case ACC_UNATTACHED:
4959 if (tcpm_port_is_debug(port) || tcpm_port_is_audio(port) ||
4960 tcpm_port_is_source(port))
4961 tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
4963 case SRC_ATTACH_WAIT:
4964 if (tcpm_port_is_disconnected(port) ||
4965 tcpm_port_is_audio_detached(port))
4966 tcpm_set_state(port, SRC_UNATTACHED, 0);
4967 else if (cc1 != old_cc1 || cc2 != old_cc2)
4968 tcpm_set_state(port, SRC_ATTACH_WAIT, 0);
4972 case SRC_SEND_CAPABILITIES:
4974 if (tcpm_port_is_disconnected(port) ||
4975 !tcpm_port_is_source(port)) {
4976 if (port->port_type == TYPEC_PORT_SRC)
4977 tcpm_set_state(port, SRC_UNATTACHED, tcpm_wait_for_discharge(port));
4979 tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
4982 case SNK_UNATTACHED:
4983 if (tcpm_port_is_sink(port))
4984 tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
4986 case SNK_ATTACH_WAIT:
4987 if ((port->cc1 == TYPEC_CC_OPEN &&
4988 port->cc2 != TYPEC_CC_OPEN) ||
4989 (port->cc1 != TYPEC_CC_OPEN &&
4990 port->cc2 == TYPEC_CC_OPEN))
4991 new_state = SNK_DEBOUNCED;
4992 else if (tcpm_port_is_disconnected(port))
4993 new_state = SNK_UNATTACHED;
4996 if (new_state != port->delayed_state)
4997 tcpm_set_state(port, SNK_ATTACH_WAIT, 0);
5000 if (tcpm_port_is_disconnected(port))
5001 new_state = SNK_UNATTACHED;
5002 else if (port->vbus_present)
5003 new_state = tcpm_try_src(port) ? SRC_TRY : SNK_ATTACHED;
5005 new_state = SNK_UNATTACHED;
5006 if (new_state != port->delayed_state)
5007 tcpm_set_state(port, SNK_DEBOUNCED, 0);
5011 * EXIT condition is based primarily on vbus disconnect and CC is secondary.
5012 * "A port that has entered into USB PD communications with the Source and
5013 * has seen the CC voltage exceed vRd-USB may monitor the CC pin to detect
5014 * cable disconnect in addition to monitoring VBUS.
5016 * A port that is monitoring the CC voltage for disconnect (but is not in
5017 * the process of a USB PD PR_Swap or USB PD FR_Swap) shall transition to
5018 * Unattached.SNK within tSinkDisconnect after the CC voltage remains below
5019 * vRd-USB for tPDDebounce."
5021 * When set_auto_vbus_discharge_threshold is enabled, CC pins go
5022 * away before vbus decays to disconnect threshold. Allow
5023 * disconnect to be driven by vbus disconnect when auto vbus
5024 * discharge is enabled.
5026 if (!port->auto_vbus_discharge_enabled && tcpm_port_is_disconnected(port))
5027 tcpm_set_state(port, unattached_state(port), 0);
5028 else if (!port->pd_capable &&
5029 (cc1 != old_cc1 || cc2 != old_cc2))
5030 tcpm_set_current_limit(port,
5031 tcpm_get_current_limit(port),
5035 case AUDIO_ACC_ATTACHED:
5036 if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
5037 tcpm_set_state(port, AUDIO_ACC_DEBOUNCE, 0);
5039 case AUDIO_ACC_DEBOUNCE:
5040 if (tcpm_port_is_audio(port))
5041 tcpm_set_state(port, AUDIO_ACC_ATTACHED, 0);
5044 case DEBUG_ACC_ATTACHED:
5045 if (cc1 == TYPEC_CC_OPEN || cc2 == TYPEC_CC_OPEN)
5046 tcpm_set_state(port, ACC_UNATTACHED, 0);
5050 /* Do nothing, waiting for timeout */
5054 /* CC line is unstable, wait for debounce */
5055 if (tcpm_port_is_disconnected(port))
5056 tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE, 0);
5058 case SNK_DISCOVERY_DEBOUNCE:
5062 /* Hand over to state machine if needed */
5063 if (!port->vbus_present && tcpm_port_is_source(port))
5064 tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
5066 case SRC_TRYWAIT_DEBOUNCE:
5067 if (port->vbus_present || !tcpm_port_is_source(port))
5068 tcpm_set_state(port, SRC_TRYWAIT, 0);
5070 case SNK_TRY_WAIT_DEBOUNCE:
5071 if (!tcpm_port_is_sink(port)) {
5073 tcpm_set_state(port, SRC_TRYWAIT, 0);
5077 if (tcpm_port_is_source(port))
5078 tcpm_set_state(port, SRC_TRY_DEBOUNCE, 0);
5080 case SRC_TRY_DEBOUNCE:
5081 tcpm_set_state(port, SRC_TRY_WAIT, 0);
5083 case SNK_TRYWAIT_DEBOUNCE:
5084 if (tcpm_port_is_sink(port))
5085 tcpm_set_state(port, SNK_TRYWAIT_VBUS, 0);
5087 case SNK_TRYWAIT_VBUS:
5088 if (!tcpm_port_is_sink(port))
5089 tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
5091 case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
5092 if (!tcpm_port_is_sink(port))
5093 tcpm_set_state(port, SRC_TRYWAIT, PD_T_TRY_CC_DEBOUNCE);
5095 tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS, 0);
5098 /* Do nothing, waiting for tCCDebounce */
5100 case PR_SWAP_SNK_SRC_SINK_OFF:
5101 case PR_SWAP_SRC_SNK_TRANSITION_OFF:
5102 case PR_SWAP_SRC_SNK_SOURCE_OFF:
5103 case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
5104 case PR_SWAP_SNK_SRC_SOURCE_ON:
5106 * CC state change is expected in PR_SWAP
5111 case FR_SWAP_SEND_TIMEOUT:
5112 case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5113 case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5114 case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5115 /* Do nothing, CC change expected */
5119 case PORT_RESET_WAIT_OFF:
5121 * State set back to default mode once the timer completes.
5122 * Ignore CC changes here.
5127 * While acting as sink and auto vbus discharge is enabled, Allow disconnect
5128 * to be driven by vbus disconnect.
5130 if (tcpm_port_is_disconnected(port) && !(port->pwr_role == TYPEC_SINK &&
5131 port->auto_vbus_discharge_enabled))
5132 tcpm_set_state(port, unattached_state(port), 0);
5137 static void _tcpm_pd_vbus_on(struct tcpm_port *port)
5139 tcpm_log_force(port, "VBUS on");
5140 port->vbus_present = true;
5142 * When vbus_present is true i.e. Voltage at VBUS is greater than VSAFE5V implicitly
5143 * states that vbus is not at VSAFE0V, hence clear the vbus_vsafe0v flag here.
5145 port->vbus_vsafe0v = false;
5147 switch (port->state) {
5148 case SNK_TRANSITION_SINK_VBUS:
5149 port->explicit_contract = true;
5150 tcpm_set_state(port, SNK_READY, 0);
5153 tcpm_set_state(port, SNK_DISCOVERY, 0);
5157 tcpm_set_state(port, tcpm_try_src(port) ? SRC_TRY
5161 case SNK_HARD_RESET_WAIT_VBUS:
5162 tcpm_set_state(port, SNK_HARD_RESET_SINK_ON, 0);
5165 tcpm_set_state(port, SRC_STARTUP, 0);
5167 case SRC_HARD_RESET_VBUS_ON:
5168 tcpm_set_state(port, SRC_STARTUP, 0);
5172 /* Do nothing, waiting for timeout */
5175 /* Do nothing, Waiting for Rd to be detected */
5177 case SRC_TRYWAIT_DEBOUNCE:
5178 tcpm_set_state(port, SRC_TRYWAIT, 0);
5180 case SNK_TRY_WAIT_DEBOUNCE:
5181 /* Do nothing, waiting for PD_DEBOUNCE to do be done */
5184 /* Do nothing, waiting for tCCDebounce */
5186 case SNK_TRYWAIT_VBUS:
5187 if (tcpm_port_is_sink(port))
5188 tcpm_set_state(port, SNK_ATTACHED, 0);
5190 case SNK_TRYWAIT_DEBOUNCE:
5191 /* Do nothing, waiting for Rp */
5193 case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
5194 if (port->vbus_present && tcpm_port_is_sink(port))
5195 tcpm_set_state(port, SNK_ATTACHED, 0);
5198 case SRC_TRY_DEBOUNCE:
5199 /* Do nothing, waiting for sink detection */
5202 case FR_SWAP_SEND_TIMEOUT:
5203 case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5204 case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5205 if (port->tcpc->frs_sourcing_vbus)
5206 port->tcpc->frs_sourcing_vbus(port->tcpc);
5208 case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5209 if (port->tcpc->frs_sourcing_vbus)
5210 port->tcpc->frs_sourcing_vbus(port->tcpc);
5211 tcpm_set_state(port, FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED, 0);
5215 case PORT_RESET_WAIT_OFF:
5217 * State set back to default mode once the timer completes.
5218 * Ignore vbus changes here.
5227 static void _tcpm_pd_vbus_off(struct tcpm_port *port)
5229 tcpm_log_force(port, "VBUS off");
5230 port->vbus_present = false;
5231 port->vbus_never_low = false;
5232 switch (port->state) {
5233 case SNK_HARD_RESET_SINK_OFF:
5234 tcpm_set_state(port, SNK_HARD_RESET_WAIT_VBUS, 0);
5236 case HARD_RESET_SEND:
5239 /* Do nothing, waiting for timeout */
5242 /* Hand over to state machine if needed */
5243 if (tcpm_port_is_source(port))
5244 tcpm_set_state(port, SRC_TRYWAIT_DEBOUNCE, 0);
5246 case SNK_TRY_WAIT_DEBOUNCE:
5247 /* Do nothing, waiting for PD_DEBOUNCE to do be done */
5250 case SNK_TRYWAIT_VBUS:
5251 case SNK_TRYWAIT_DEBOUNCE:
5253 case SNK_ATTACH_WAIT:
5255 /* Do nothing, as TCPM is still waiting for vbus to reaach VSAFE5V to connect */
5258 case SNK_NEGOTIATE_CAPABILITIES:
5261 case PR_SWAP_SRC_SNK_TRANSITION_OFF:
5262 tcpm_set_state(port, PR_SWAP_SRC_SNK_SOURCE_OFF, 0);
5265 case PR_SWAP_SNK_SRC_SINK_OFF:
5266 /* Do nothing, expected */
5269 case PR_SWAP_SNK_SRC_SOURCE_ON:
5271 * Do nothing when vbus off notification is received.
5272 * TCPM can wait for PD_T_NEWSRC in PR_SWAP_SNK_SRC_SOURCE_ON
5273 * for the vbus source to ramp up.
5277 case PORT_RESET_WAIT_OFF:
5278 tcpm_set_state(port, tcpm_default_state(port), 0);
5282 case SRC_TRY_DEBOUNCE:
5283 /* Do nothing, waiting for sink detection */
5287 case SRC_SEND_CAPABILITIES:
5288 case SRC_SEND_CAPABILITIES_TIMEOUT:
5289 case SRC_NEGOTIATE_CAPABILITIES:
5290 case SRC_TRANSITION_SUPPLY:
5292 case SRC_WAIT_NEW_CAPABILITIES:
5294 * Force to unattached state to re-initiate connection.
5295 * DRP port should move to Unattached.SNK instead of Unattached.SRC if
5296 * sink removed. Although sink removal here is due to source's vbus collapse,
5297 * treat it the same way for consistency.
5299 if (port->port_type == TYPEC_PORT_SRC)
5300 tcpm_set_state(port, SRC_UNATTACHED, tcpm_wait_for_discharge(port));
5302 tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
5307 * State set back to default mode once the timer completes.
5308 * Ignore vbus changes here.
5313 case FR_SWAP_SEND_TIMEOUT:
5314 case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
5315 case FR_SWAP_SNK_SRC_NEW_SINK_READY:
5316 case FR_SWAP_SNK_SRC_SOURCE_VBUS_APPLIED:
5317 /* Do nothing, vbus drop expected */
5321 if (port->pwr_role == TYPEC_SINK && port->attached)
5322 tcpm_set_state(port, SNK_UNATTACHED, tcpm_wait_for_discharge(port));
5327 static void _tcpm_pd_vbus_vsafe0v(struct tcpm_port *port)
5329 tcpm_log_force(port, "VBUS VSAFE0V");
5330 port->vbus_vsafe0v = true;
5331 switch (port->state) {
5332 case SRC_HARD_RESET_VBUS_OFF:
5334 * After establishing the vSafe0V voltage condition on VBUS, the Source Shall wait
5335 * tSrcRecover before re-applying VCONN and restoring VBUS to vSafe5V.
5337 tcpm_set_state(port, SRC_HARD_RESET_VBUS_ON, PD_T_SRC_RECOVER);
5339 case SRC_ATTACH_WAIT:
5340 if (tcpm_port_is_source(port))
5341 tcpm_set_state(port, tcpm_try_snk(port) ? SNK_TRY : SRC_ATTACHED,
5345 case SRC_SEND_CAPABILITIES:
5346 case SRC_SEND_CAPABILITIES_TIMEOUT:
5347 case SRC_NEGOTIATE_CAPABILITIES:
5348 case SRC_TRANSITION_SUPPLY:
5350 case SRC_WAIT_NEW_CAPABILITIES:
5351 if (port->auto_vbus_discharge_enabled) {
5352 if (port->port_type == TYPEC_PORT_SRC)
5353 tcpm_set_state(port, SRC_UNATTACHED, 0);
5355 tcpm_set_state(port, SNK_UNATTACHED, 0);
5358 case PR_SWAP_SNK_SRC_SINK_OFF:
5359 case PR_SWAP_SNK_SRC_SOURCE_ON:
5360 /* Do nothing, vsafe0v is expected during transition */
5362 case SNK_ATTACH_WAIT:
5364 /*Do nothing, still waiting for VSAFE5V for connect */
5367 if (port->pwr_role == TYPEC_SINK && port->auto_vbus_discharge_enabled)
5368 tcpm_set_state(port, SNK_UNATTACHED, 0);
5373 static void _tcpm_pd_hard_reset(struct tcpm_port *port)
5375 tcpm_log_force(port, "Received hard reset");
5376 if (port->bist_request == BDO_MODE_TESTDATA && port->tcpc->set_bist_data)
5377 port->tcpc->set_bist_data(port->tcpc, false);
5379 if (port->ams != NONE_AMS)
5380 port->ams = NONE_AMS;
5381 if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
5382 port->ams = HARD_RESET;
5384 * If we keep receiving hard reset requests, executing the hard reset
5385 * must have failed. Revert to error recovery if that happens.
5387 tcpm_set_state(port,
5388 port->hard_reset_count < PD_N_HARD_RESET_COUNT ?
5389 HARD_RESET_START : ERROR_RECOVERY,
5393 static void tcpm_pd_event_handler(struct kthread_work *work)
5395 struct tcpm_port *port = container_of(work, struct tcpm_port,
5399 mutex_lock(&port->lock);
5401 spin_lock(&port->pd_event_lock);
5402 while (port->pd_events) {
5403 events = port->pd_events;
5404 port->pd_events = 0;
5405 spin_unlock(&port->pd_event_lock);
5406 if (events & TCPM_RESET_EVENT)
5407 _tcpm_pd_hard_reset(port);
5408 if (events & TCPM_VBUS_EVENT) {
5411 vbus = port->tcpc->get_vbus(port->tcpc);
5413 _tcpm_pd_vbus_on(port);
5415 _tcpm_pd_vbus_off(port);
5417 * When TCPC does not support detecting vsafe0v voltage level,
5418 * treat vbus absent as vsafe0v. Else invoke is_vbus_vsafe0v
5419 * to see if vbus has discharge to VSAFE0V.
5421 if (!port->tcpc->is_vbus_vsafe0v ||
5422 port->tcpc->is_vbus_vsafe0v(port->tcpc))
5423 _tcpm_pd_vbus_vsafe0v(port);
5426 if (events & TCPM_CC_EVENT) {
5427 enum typec_cc_status cc1, cc2;
5429 if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
5430 _tcpm_cc_change(port, cc1, cc2);
5432 if (events & TCPM_FRS_EVENT) {
5433 if (port->state == SNK_READY) {
5436 port->upcoming_state = FR_SWAP_SEND;
5437 ret = tcpm_ams_start(port, FAST_ROLE_SWAP);
5439 port->upcoming_state = INVALID_STATE;
5441 tcpm_log(port, "Discarding FRS_SIGNAL! Not in sink ready");
5444 if (events & TCPM_SOURCING_VBUS) {
5445 tcpm_log(port, "sourcing vbus");
5447 * In fast role swap case TCPC autonomously sources vbus. Set vbus_source
5448 * true as TCPM wouldn't have called tcpm_set_vbus.
5450 * When vbus is sourced on the command on TCPM i.e. TCPM called
5451 * tcpm_set_vbus to source vbus, vbus_source would already be true.
5453 port->vbus_source = true;
5454 _tcpm_pd_vbus_on(port);
5456 if (events & TCPM_PORT_CLEAN) {
5457 tcpm_log(port, "port clean");
5458 if (port->state == CHECK_CONTAMINANT) {
5459 if (tcpm_start_toggling(port, tcpm_rp_cc(port)))
5460 tcpm_set_state(port, TOGGLING, 0);
5462 tcpm_set_state(port, tcpm_default_state(port), 0);
5466 spin_lock(&port->pd_event_lock);
5468 spin_unlock(&port->pd_event_lock);
5469 mutex_unlock(&port->lock);
5472 void tcpm_cc_change(struct tcpm_port *port)
5474 spin_lock(&port->pd_event_lock);
5475 port->pd_events |= TCPM_CC_EVENT;
5476 spin_unlock(&port->pd_event_lock);
5477 kthread_queue_work(port->wq, &port->event_work);
5479 EXPORT_SYMBOL_GPL(tcpm_cc_change);
5481 void tcpm_vbus_change(struct tcpm_port *port)
5483 spin_lock(&port->pd_event_lock);
5484 port->pd_events |= TCPM_VBUS_EVENT;
5485 spin_unlock(&port->pd_event_lock);
5486 kthread_queue_work(port->wq, &port->event_work);
5488 EXPORT_SYMBOL_GPL(tcpm_vbus_change);
5490 void tcpm_pd_hard_reset(struct tcpm_port *port)
5492 spin_lock(&port->pd_event_lock);
5493 port->pd_events = TCPM_RESET_EVENT;
5494 spin_unlock(&port->pd_event_lock);
5495 kthread_queue_work(port->wq, &port->event_work);
5497 EXPORT_SYMBOL_GPL(tcpm_pd_hard_reset);
5499 void tcpm_sink_frs(struct tcpm_port *port)
5501 spin_lock(&port->pd_event_lock);
5502 port->pd_events |= TCPM_FRS_EVENT;
5503 spin_unlock(&port->pd_event_lock);
5504 kthread_queue_work(port->wq, &port->event_work);
5506 EXPORT_SYMBOL_GPL(tcpm_sink_frs);
5508 void tcpm_sourcing_vbus(struct tcpm_port *port)
5510 spin_lock(&port->pd_event_lock);
5511 port->pd_events |= TCPM_SOURCING_VBUS;
5512 spin_unlock(&port->pd_event_lock);
5513 kthread_queue_work(port->wq, &port->event_work);
5515 EXPORT_SYMBOL_GPL(tcpm_sourcing_vbus);
5517 void tcpm_port_clean(struct tcpm_port *port)
5519 spin_lock(&port->pd_event_lock);
5520 port->pd_events |= TCPM_PORT_CLEAN;
5521 spin_unlock(&port->pd_event_lock);
5522 kthread_queue_work(port->wq, &port->event_work);
5524 EXPORT_SYMBOL_GPL(tcpm_port_clean);
5526 bool tcpm_port_is_toggling(struct tcpm_port *port)
5528 return port->port_type == TYPEC_PORT_DRP && port->state == TOGGLING;
5530 EXPORT_SYMBOL_GPL(tcpm_port_is_toggling);
5532 static void tcpm_enable_frs_work(struct kthread_work *work)
5534 struct tcpm_port *port = container_of(work, struct tcpm_port, enable_frs);
5537 mutex_lock(&port->lock);
5538 /* Not FRS capable */
5539 if (!port->connected || port->port_type != TYPEC_PORT_DRP ||
5540 port->pwr_opmode != TYPEC_PWR_MODE_PD ||
5541 !port->tcpc->enable_frs ||
5542 /* Sink caps queried */
5543 port->sink_cap_done || port->negotiated_rev < PD_REV30)
5546 /* Send when the state machine is idle */
5547 if (port->state != SNK_READY || port->vdm_sm_running || port->send_discover)
5550 port->upcoming_state = GET_SINK_CAP;
5551 ret = tcpm_ams_start(port, GET_SINK_CAPABILITIES);
5552 if (ret == -EAGAIN) {
5553 port->upcoming_state = INVALID_STATE;
5555 port->sink_cap_done = true;
5559 mod_enable_frs_delayed_work(port, GET_SINK_CAP_RETRY_MS);
5561 mutex_unlock(&port->lock);
5564 static void tcpm_send_discover_work(struct kthread_work *work)
5566 struct tcpm_port *port = container_of(work, struct tcpm_port, send_discover_work);
5568 mutex_lock(&port->lock);
5569 /* No need to send DISCOVER_IDENTITY anymore */
5570 if (!port->send_discover)
5573 if (port->data_role == TYPEC_DEVICE && port->negotiated_rev < PD_REV30) {
5574 port->send_discover = false;
5578 /* Retry if the port is not idle */
5579 if ((port->state != SRC_READY && port->state != SNK_READY) || port->vdm_sm_running) {
5580 mod_send_discover_delayed_work(port, SEND_DISCOVER_RETRY_MS);
5584 tcpm_send_vdm(port, USB_SID_PD, CMD_DISCOVER_IDENT, NULL, 0);
5587 mutex_unlock(&port->lock);
5590 static int tcpm_dr_set(struct typec_port *p, enum typec_data_role data)
5592 struct tcpm_port *port = typec_get_drvdata(p);
5595 mutex_lock(&port->swap_lock);
5596 mutex_lock(&port->lock);
5598 if (port->typec_caps.data != TYPEC_PORT_DRD) {
5602 if (port->state != SRC_READY && port->state != SNK_READY) {
5607 if (port->data_role == data) {
5614 * 6.3.9: If an alternate mode is active, a request to swap
5615 * alternate modes shall trigger a port reset.
5616 * Reject data role swap request in this case.
5619 if (!port->pd_capable) {
5621 * If the partner is not PD capable, reset the port to
5622 * trigger a role change. This can only work if a preferred
5623 * role is configured, and if it matches the requested role.
5625 if (port->try_role == TYPEC_NO_PREFERRED_ROLE ||
5626 port->try_role == port->pwr_role) {
5630 port->non_pd_role_swap = true;
5631 tcpm_set_state(port, PORT_RESET, 0);
5633 port->upcoming_state = DR_SWAP_SEND;
5634 ret = tcpm_ams_start(port, DATA_ROLE_SWAP);
5635 if (ret == -EAGAIN) {
5636 port->upcoming_state = INVALID_STATE;
5641 port->swap_status = 0;
5642 port->swap_pending = true;
5643 reinit_completion(&port->swap_complete);
5644 mutex_unlock(&port->lock);
5646 if (!wait_for_completion_timeout(&port->swap_complete,
5647 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
5650 ret = port->swap_status;
5652 port->non_pd_role_swap = false;
5656 mutex_unlock(&port->lock);
5658 mutex_unlock(&port->swap_lock);
5662 static int tcpm_pr_set(struct typec_port *p, enum typec_role role)
5664 struct tcpm_port *port = typec_get_drvdata(p);
5667 mutex_lock(&port->swap_lock);
5668 mutex_lock(&port->lock);
5670 if (port->port_type != TYPEC_PORT_DRP) {
5674 if (port->state != SRC_READY && port->state != SNK_READY) {
5679 if (role == port->pwr_role) {
5684 port->upcoming_state = PR_SWAP_SEND;
5685 ret = tcpm_ams_start(port, POWER_ROLE_SWAP);
5686 if (ret == -EAGAIN) {
5687 port->upcoming_state = INVALID_STATE;
5691 port->swap_status = 0;
5692 port->swap_pending = true;
5693 reinit_completion(&port->swap_complete);
5694 mutex_unlock(&port->lock);
5696 if (!wait_for_completion_timeout(&port->swap_complete,
5697 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
5700 ret = port->swap_status;
5705 mutex_unlock(&port->lock);
5707 mutex_unlock(&port->swap_lock);
5711 static int tcpm_vconn_set(struct typec_port *p, enum typec_role role)
5713 struct tcpm_port *port = typec_get_drvdata(p);
5716 mutex_lock(&port->swap_lock);
5717 mutex_lock(&port->lock);
5719 if (port->state != SRC_READY && port->state != SNK_READY) {
5724 if (role == port->vconn_role) {
5729 port->upcoming_state = VCONN_SWAP_SEND;
5730 ret = tcpm_ams_start(port, VCONN_SWAP);
5731 if (ret == -EAGAIN) {
5732 port->upcoming_state = INVALID_STATE;
5736 port->swap_status = 0;
5737 port->swap_pending = true;
5738 reinit_completion(&port->swap_complete);
5739 mutex_unlock(&port->lock);
5741 if (!wait_for_completion_timeout(&port->swap_complete,
5742 msecs_to_jiffies(PD_ROLE_SWAP_TIMEOUT)))
5745 ret = port->swap_status;
5750 mutex_unlock(&port->lock);
5752 mutex_unlock(&port->swap_lock);
5756 static int tcpm_try_role(struct typec_port *p, int role)
5758 struct tcpm_port *port = typec_get_drvdata(p);
5759 struct tcpc_dev *tcpc = port->tcpc;
5762 mutex_lock(&port->lock);
5764 ret = tcpc->try_role(tcpc, role);
5766 port->try_role = role;
5767 port->try_src_count = 0;
5768 port->try_snk_count = 0;
5769 mutex_unlock(&port->lock);
5774 static int tcpm_pps_set_op_curr(struct tcpm_port *port, u16 req_op_curr)
5776 unsigned int target_mw;
5779 mutex_lock(&port->swap_lock);
5780 mutex_lock(&port->lock);
5782 if (!port->pps_data.active) {
5787 if (port->state != SNK_READY) {
5792 if (req_op_curr > port->pps_data.max_curr) {
5797 target_mw = (req_op_curr * port->supply_voltage) / 1000;
5798 if (target_mw < port->operating_snk_mw) {
5803 port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
5804 ret = tcpm_ams_start(port, POWER_NEGOTIATION);
5805 if (ret == -EAGAIN) {
5806 port->upcoming_state = INVALID_STATE;
5810 /* Round down operating current to align with PPS valid steps */
5811 req_op_curr = req_op_curr - (req_op_curr % RDO_PROG_CURR_MA_STEP);
5813 reinit_completion(&port->pps_complete);
5814 port->pps_data.req_op_curr = req_op_curr;
5815 port->pps_status = 0;
5816 port->pps_pending = true;
5817 mutex_unlock(&port->lock);
5819 if (!wait_for_completion_timeout(&port->pps_complete,
5820 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
5823 ret = port->pps_status;
5828 mutex_unlock(&port->lock);
5830 mutex_unlock(&port->swap_lock);
5835 static int tcpm_pps_set_out_volt(struct tcpm_port *port, u16 req_out_volt)
5837 unsigned int target_mw;
5840 mutex_lock(&port->swap_lock);
5841 mutex_lock(&port->lock);
5843 if (!port->pps_data.active) {
5848 if (port->state != SNK_READY) {
5853 if (req_out_volt < port->pps_data.min_volt ||
5854 req_out_volt > port->pps_data.max_volt) {
5859 target_mw = (port->current_limit * req_out_volt) / 1000;
5860 if (target_mw < port->operating_snk_mw) {
5865 port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
5866 ret = tcpm_ams_start(port, POWER_NEGOTIATION);
5867 if (ret == -EAGAIN) {
5868 port->upcoming_state = INVALID_STATE;
5872 /* Round down output voltage to align with PPS valid steps */
5873 req_out_volt = req_out_volt - (req_out_volt % RDO_PROG_VOLT_MV_STEP);
5875 reinit_completion(&port->pps_complete);
5876 port->pps_data.req_out_volt = req_out_volt;
5877 port->pps_status = 0;
5878 port->pps_pending = true;
5879 mutex_unlock(&port->lock);
5881 if (!wait_for_completion_timeout(&port->pps_complete,
5882 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
5885 ret = port->pps_status;
5890 mutex_unlock(&port->lock);
5892 mutex_unlock(&port->swap_lock);
5897 static int tcpm_pps_activate(struct tcpm_port *port, bool activate)
5901 mutex_lock(&port->swap_lock);
5902 mutex_lock(&port->lock);
5904 if (!port->pps_data.supported) {
5909 /* Trying to deactivate PPS when already deactivated so just bail */
5910 if (!port->pps_data.active && !activate)
5913 if (port->state != SNK_READY) {
5919 port->upcoming_state = SNK_NEGOTIATE_PPS_CAPABILITIES;
5921 port->upcoming_state = SNK_NEGOTIATE_CAPABILITIES;
5922 ret = tcpm_ams_start(port, POWER_NEGOTIATION);
5923 if (ret == -EAGAIN) {
5924 port->upcoming_state = INVALID_STATE;
5928 reinit_completion(&port->pps_complete);
5929 port->pps_status = 0;
5930 port->pps_pending = true;
5932 /* Trigger PPS request or move back to standard PDO contract */
5934 port->pps_data.req_out_volt = port->supply_voltage;
5935 port->pps_data.req_op_curr = port->current_limit;
5937 mutex_unlock(&port->lock);
5939 if (!wait_for_completion_timeout(&port->pps_complete,
5940 msecs_to_jiffies(PD_PPS_CTRL_TIMEOUT)))
5943 ret = port->pps_status;
5948 mutex_unlock(&port->lock);
5950 mutex_unlock(&port->swap_lock);
5955 static void tcpm_init(struct tcpm_port *port)
5957 enum typec_cc_status cc1, cc2;
5959 port->tcpc->init(port->tcpc);
5961 tcpm_reset_port(port);
5965 * Should possibly wait for VBUS to settle if it was enabled locally
5966 * since tcpm_reset_port() will disable VBUS.
5968 port->vbus_present = port->tcpc->get_vbus(port->tcpc);
5969 if (port->vbus_present)
5970 port->vbus_never_low = true;
5973 * 1. When vbus_present is true, voltage on VBUS is already at VSAFE5V.
5974 * So implicitly vbus_vsafe0v = false.
5976 * 2. When vbus_present is false and TCPC does NOT support querying
5977 * vsafe0v status, then, it's best to assume vbus is at VSAFE0V i.e.
5978 * vbus_vsafe0v is true.
5980 * 3. When vbus_present is false and TCPC does support querying vsafe0v,
5981 * then, query tcpc for vsafe0v status.
5983 if (port->vbus_present)
5984 port->vbus_vsafe0v = false;
5985 else if (!port->tcpc->is_vbus_vsafe0v)
5986 port->vbus_vsafe0v = true;
5988 port->vbus_vsafe0v = port->tcpc->is_vbus_vsafe0v(port->tcpc);
5990 tcpm_set_state(port, tcpm_default_state(port), 0);
5992 if (port->tcpc->get_cc(port->tcpc, &cc1, &cc2) == 0)
5993 _tcpm_cc_change(port, cc1, cc2);
5996 * Some adapters need a clean slate at startup, and won't recover
5997 * otherwise. So do not try to be fancy and force a clean disconnect.
5999 tcpm_set_state(port, PORT_RESET, 0);
6002 static int tcpm_port_type_set(struct typec_port *p, enum typec_port_type type)
6004 struct tcpm_port *port = typec_get_drvdata(p);
6006 mutex_lock(&port->lock);
6007 if (type == port->port_type)
6010 port->port_type = type;
6012 if (!port->connected) {
6013 tcpm_set_state(port, PORT_RESET, 0);
6014 } else if (type == TYPEC_PORT_SNK) {
6015 if (!(port->pwr_role == TYPEC_SINK &&
6016 port->data_role == TYPEC_DEVICE))
6017 tcpm_set_state(port, PORT_RESET, 0);
6018 } else if (type == TYPEC_PORT_SRC) {
6019 if (!(port->pwr_role == TYPEC_SOURCE &&
6020 port->data_role == TYPEC_HOST))
6021 tcpm_set_state(port, PORT_RESET, 0);
6025 mutex_unlock(&port->lock);
6029 static const struct typec_operations tcpm_ops = {
6030 .try_role = tcpm_try_role,
6031 .dr_set = tcpm_dr_set,
6032 .pr_set = tcpm_pr_set,
6033 .vconn_set = tcpm_vconn_set,
6034 .port_type_set = tcpm_port_type_set
6037 void tcpm_tcpc_reset(struct tcpm_port *port)
6039 mutex_lock(&port->lock);
6040 /* XXX: Maintain PD connection if possible? */
6042 mutex_unlock(&port->lock);
6044 EXPORT_SYMBOL_GPL(tcpm_tcpc_reset);
6046 static void tcpm_port_unregister_pd(struct tcpm_port *port)
6048 usb_power_delivery_unregister_capabilities(port->port_sink_caps);
6049 port->port_sink_caps = NULL;
6050 usb_power_delivery_unregister_capabilities(port->port_source_caps);
6051 port->port_source_caps = NULL;
6052 usb_power_delivery_unregister(port->pd);
6056 static int tcpm_port_register_pd(struct tcpm_port *port)
6058 struct usb_power_delivery_desc desc = { port->typec_caps.pd_revision };
6059 struct usb_power_delivery_capabilities_desc caps = { };
6060 struct usb_power_delivery_capabilities *cap;
6063 if (!port->nr_src_pdo && !port->nr_snk_pdo)
6066 port->pd = usb_power_delivery_register(port->dev, &desc);
6067 if (IS_ERR(port->pd)) {
6068 ret = PTR_ERR(port->pd);
6069 goto err_unregister;
6072 if (port->nr_src_pdo) {
6073 memcpy_and_pad(caps.pdo, sizeof(caps.pdo), port->src_pdo,
6074 port->nr_src_pdo * sizeof(u32), 0);
6075 caps.role = TYPEC_SOURCE;
6077 cap = usb_power_delivery_register_capabilities(port->pd, &caps);
6080 goto err_unregister;
6083 port->port_source_caps = cap;
6086 if (port->nr_snk_pdo) {
6087 memcpy_and_pad(caps.pdo, sizeof(caps.pdo), port->snk_pdo,
6088 port->nr_snk_pdo * sizeof(u32), 0);
6089 caps.role = TYPEC_SINK;
6091 cap = usb_power_delivery_register_capabilities(port->pd, &caps);
6094 goto err_unregister;
6097 port->port_sink_caps = cap;
6103 tcpm_port_unregister_pd(port);
6108 static int tcpm_fw_get_caps(struct tcpm_port *port,
6109 struct fwnode_handle *fwnode)
6111 const char *opmode_str;
6113 u32 mw, frs_current;
6119 * This fwnode has a "compatible" property, but is never populated as a
6120 * struct device. Instead we simply parse it to read the properties.
6121 * This it breaks fw_devlink=on. To maintain backward compatibility
6122 * with existing DT files, we work around this by deleting any
6123 * fwnode_links to/from this fwnode.
6125 fw_devlink_purge_absent_suppliers(fwnode);
6127 ret = typec_get_fw_cap(&port->typec_caps, fwnode);
6131 port->port_type = port->typec_caps.type;
6132 port->pd_supported = !fwnode_property_read_bool(fwnode, "pd-disable");
6134 port->slow_charger_loop = fwnode_property_read_bool(fwnode, "slow-charger-loop");
6135 if (port->port_type == TYPEC_PORT_SNK)
6138 /* Get Source PDOs for the PD port or Source Rp value for the non-PD port */
6139 if (port->pd_supported) {
6140 ret = fwnode_property_count_u32(fwnode, "source-pdos");
6146 port->nr_src_pdo = min(ret, PDO_MAX_OBJECTS);
6147 ret = fwnode_property_read_u32_array(fwnode, "source-pdos",
6148 port->src_pdo, port->nr_src_pdo);
6151 ret = tcpm_validate_caps(port, port->src_pdo, port->nr_src_pdo);
6155 ret = fwnode_property_read_string(fwnode, "typec-power-opmode", &opmode_str);
6158 ret = typec_find_pwr_opmode(opmode_str);
6161 port->src_rp = tcpm_pwr_opmode_to_rp(ret);
6164 if (port->port_type == TYPEC_PORT_SRC)
6168 port->self_powered = fwnode_property_read_bool(fwnode, "self-powered");
6170 if (!port->pd_supported)
6174 ret = fwnode_property_count_u32(fwnode, "sink-pdos");
6178 port->nr_snk_pdo = min(ret, PDO_MAX_OBJECTS);
6179 ret = fwnode_property_read_u32_array(fwnode, "sink-pdos",
6180 port->snk_pdo, port->nr_snk_pdo);
6181 if ((ret < 0) || tcpm_validate_caps(port, port->snk_pdo,
6185 if (fwnode_property_read_u32(fwnode, "op-sink-microwatt", &mw) < 0)
6187 port->operating_snk_mw = mw / 1000;
6189 /* FRS can only be supported by DRP ports */
6190 if (port->port_type == TYPEC_PORT_DRP) {
6191 ret = fwnode_property_read_u32(fwnode, "new-source-frs-typec-current",
6193 if (ret >= 0 && frs_current <= FRS_5V_3A)
6194 port->new_source_frs_current = frs_current;
6197 /* sink-vdos is optional */
6198 ret = fwnode_property_count_u32(fwnode, "sink-vdos");
6202 port->nr_snk_vdo = min(ret, VDO_MAX_OBJECTS);
6203 if (port->nr_snk_vdo) {
6204 ret = fwnode_property_read_u32_array(fwnode, "sink-vdos",
6211 /* If sink-vdos is found, sink-vdos-v1 is expected for backward compatibility. */
6212 if (port->nr_snk_vdo) {
6213 ret = fwnode_property_count_u32(fwnode, "sink-vdos-v1");
6219 port->nr_snk_vdo_v1 = min(ret, VDO_MAX_OBJECTS);
6220 ret = fwnode_property_read_u32_array(fwnode, "sink-vdos-v1",
6222 port->nr_snk_vdo_v1);
6230 /* Power Supply access to expose source power information */
6231 enum tcpm_psy_online_states {
6232 TCPM_PSY_OFFLINE = 0,
6233 TCPM_PSY_FIXED_ONLINE,
6234 TCPM_PSY_PROG_ONLINE,
6237 static enum power_supply_property tcpm_psy_props[] = {
6238 POWER_SUPPLY_PROP_USB_TYPE,
6239 POWER_SUPPLY_PROP_ONLINE,
6240 POWER_SUPPLY_PROP_VOLTAGE_MIN,
6241 POWER_SUPPLY_PROP_VOLTAGE_MAX,
6242 POWER_SUPPLY_PROP_VOLTAGE_NOW,
6243 POWER_SUPPLY_PROP_CURRENT_MAX,
6244 POWER_SUPPLY_PROP_CURRENT_NOW,
6247 static int tcpm_psy_get_online(struct tcpm_port *port,
6248 union power_supply_propval *val)
6250 if (port->vbus_charge) {
6251 if (port->pps_data.active)
6252 val->intval = TCPM_PSY_PROG_ONLINE;
6254 val->intval = TCPM_PSY_FIXED_ONLINE;
6256 val->intval = TCPM_PSY_OFFLINE;
6262 static int tcpm_psy_get_voltage_min(struct tcpm_port *port,
6263 union power_supply_propval *val)
6265 if (port->pps_data.active)
6266 val->intval = port->pps_data.min_volt * 1000;
6268 val->intval = port->supply_voltage * 1000;
6273 static int tcpm_psy_get_voltage_max(struct tcpm_port *port,
6274 union power_supply_propval *val)
6276 if (port->pps_data.active)
6277 val->intval = port->pps_data.max_volt * 1000;
6279 val->intval = port->supply_voltage * 1000;
6284 static int tcpm_psy_get_voltage_now(struct tcpm_port *port,
6285 union power_supply_propval *val)
6287 val->intval = port->supply_voltage * 1000;
6292 static int tcpm_psy_get_current_max(struct tcpm_port *port,
6293 union power_supply_propval *val)
6295 if (port->pps_data.active)
6296 val->intval = port->pps_data.max_curr * 1000;
6298 val->intval = port->current_limit * 1000;
6303 static int tcpm_psy_get_current_now(struct tcpm_port *port,
6304 union power_supply_propval *val)
6306 val->intval = port->current_limit * 1000;
6311 static int tcpm_psy_get_prop(struct power_supply *psy,
6312 enum power_supply_property psp,
6313 union power_supply_propval *val)
6315 struct tcpm_port *port = power_supply_get_drvdata(psy);
6319 case POWER_SUPPLY_PROP_USB_TYPE:
6320 val->intval = port->usb_type;
6322 case POWER_SUPPLY_PROP_ONLINE:
6323 ret = tcpm_psy_get_online(port, val);
6325 case POWER_SUPPLY_PROP_VOLTAGE_MIN:
6326 ret = tcpm_psy_get_voltage_min(port, val);
6328 case POWER_SUPPLY_PROP_VOLTAGE_MAX:
6329 ret = tcpm_psy_get_voltage_max(port, val);
6331 case POWER_SUPPLY_PROP_VOLTAGE_NOW:
6332 ret = tcpm_psy_get_voltage_now(port, val);
6334 case POWER_SUPPLY_PROP_CURRENT_MAX:
6335 ret = tcpm_psy_get_current_max(port, val);
6337 case POWER_SUPPLY_PROP_CURRENT_NOW:
6338 ret = tcpm_psy_get_current_now(port, val);
6348 static int tcpm_psy_set_online(struct tcpm_port *port,
6349 const union power_supply_propval *val)
6353 switch (val->intval) {
6354 case TCPM_PSY_FIXED_ONLINE:
6355 ret = tcpm_pps_activate(port, false);
6357 case TCPM_PSY_PROG_ONLINE:
6358 ret = tcpm_pps_activate(port, true);
6368 static int tcpm_psy_set_prop(struct power_supply *psy,
6369 enum power_supply_property psp,
6370 const union power_supply_propval *val)
6372 struct tcpm_port *port = power_supply_get_drvdata(psy);
6376 * All the properties below are related to USB PD. The check needs to be
6377 * property specific when a non-pd related property is added.
6379 if (!port->pd_supported)
6383 case POWER_SUPPLY_PROP_ONLINE:
6384 ret = tcpm_psy_set_online(port, val);
6386 case POWER_SUPPLY_PROP_VOLTAGE_NOW:
6387 if (val->intval < port->pps_data.min_volt * 1000 ||
6388 val->intval > port->pps_data.max_volt * 1000)
6391 ret = tcpm_pps_set_out_volt(port, val->intval / 1000);
6393 case POWER_SUPPLY_PROP_CURRENT_NOW:
6394 if (val->intval > port->pps_data.max_curr * 1000)
6397 ret = tcpm_pps_set_op_curr(port, val->intval / 1000);
6403 power_supply_changed(port->psy);
6407 static int tcpm_psy_prop_writeable(struct power_supply *psy,
6408 enum power_supply_property psp)
6411 case POWER_SUPPLY_PROP_ONLINE:
6412 case POWER_SUPPLY_PROP_VOLTAGE_NOW:
6413 case POWER_SUPPLY_PROP_CURRENT_NOW:
6420 static enum power_supply_usb_type tcpm_psy_usb_types[] = {
6421 POWER_SUPPLY_USB_TYPE_C,
6422 POWER_SUPPLY_USB_TYPE_PD,
6423 POWER_SUPPLY_USB_TYPE_PD_PPS,
6426 static const char *tcpm_psy_name_prefix = "tcpm-source-psy-";
6428 static int devm_tcpm_psy_register(struct tcpm_port *port)
6430 struct power_supply_config psy_cfg = {};
6431 const char *port_dev_name = dev_name(port->dev);
6432 size_t psy_name_len = strlen(tcpm_psy_name_prefix) +
6433 strlen(port_dev_name) + 1;
6436 psy_cfg.drv_data = port;
6437 psy_cfg.fwnode = dev_fwnode(port->dev);
6438 psy_name = devm_kzalloc(port->dev, psy_name_len, GFP_KERNEL);
6442 snprintf(psy_name, psy_name_len, "%s%s", tcpm_psy_name_prefix,
6444 port->psy_desc.name = psy_name;
6445 port->psy_desc.type = POWER_SUPPLY_TYPE_USB;
6446 port->psy_desc.usb_types = tcpm_psy_usb_types;
6447 port->psy_desc.num_usb_types = ARRAY_SIZE(tcpm_psy_usb_types);
6448 port->psy_desc.properties = tcpm_psy_props;
6449 port->psy_desc.num_properties = ARRAY_SIZE(tcpm_psy_props);
6450 port->psy_desc.get_property = tcpm_psy_get_prop;
6451 port->psy_desc.set_property = tcpm_psy_set_prop;
6452 port->psy_desc.property_is_writeable = tcpm_psy_prop_writeable;
6454 port->usb_type = POWER_SUPPLY_USB_TYPE_C;
6456 port->psy = devm_power_supply_register(port->dev, &port->psy_desc,
6459 return PTR_ERR_OR_ZERO(port->psy);
6462 static enum hrtimer_restart state_machine_timer_handler(struct hrtimer *timer)
6464 struct tcpm_port *port = container_of(timer, struct tcpm_port, state_machine_timer);
6466 if (port->registered)
6467 kthread_queue_work(port->wq, &port->state_machine);
6468 return HRTIMER_NORESTART;
6471 static enum hrtimer_restart vdm_state_machine_timer_handler(struct hrtimer *timer)
6473 struct tcpm_port *port = container_of(timer, struct tcpm_port, vdm_state_machine_timer);
6475 if (port->registered)
6476 kthread_queue_work(port->wq, &port->vdm_state_machine);
6477 return HRTIMER_NORESTART;
6480 static enum hrtimer_restart enable_frs_timer_handler(struct hrtimer *timer)
6482 struct tcpm_port *port = container_of(timer, struct tcpm_port, enable_frs_timer);
6484 if (port->registered)
6485 kthread_queue_work(port->wq, &port->enable_frs);
6486 return HRTIMER_NORESTART;
6489 static enum hrtimer_restart send_discover_timer_handler(struct hrtimer *timer)
6491 struct tcpm_port *port = container_of(timer, struct tcpm_port, send_discover_timer);
6493 if (port->registered)
6494 kthread_queue_work(port->wq, &port->send_discover_work);
6495 return HRTIMER_NORESTART;
6498 struct tcpm_port *tcpm_register_port(struct device *dev, struct tcpc_dev *tcpc)
6500 struct tcpm_port *port;
6503 if (!dev || !tcpc ||
6504 !tcpc->get_vbus || !tcpc->set_cc || !tcpc->get_cc ||
6505 !tcpc->set_polarity || !tcpc->set_vconn || !tcpc->set_vbus ||
6506 !tcpc->set_pd_rx || !tcpc->set_roles || !tcpc->pd_transmit)
6507 return ERR_PTR(-EINVAL);
6509 port = devm_kzalloc(dev, sizeof(*port), GFP_KERNEL);
6511 return ERR_PTR(-ENOMEM);
6516 mutex_init(&port->lock);
6517 mutex_init(&port->swap_lock);
6519 port->wq = kthread_create_worker(0, dev_name(dev));
6520 if (IS_ERR(port->wq))
6521 return ERR_CAST(port->wq);
6522 sched_set_fifo(port->wq->task);
6524 kthread_init_work(&port->state_machine, tcpm_state_machine_work);
6525 kthread_init_work(&port->vdm_state_machine, vdm_state_machine_work);
6526 kthread_init_work(&port->event_work, tcpm_pd_event_handler);
6527 kthread_init_work(&port->enable_frs, tcpm_enable_frs_work);
6528 kthread_init_work(&port->send_discover_work, tcpm_send_discover_work);
6529 hrtimer_init(&port->state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6530 port->state_machine_timer.function = state_machine_timer_handler;
6531 hrtimer_init(&port->vdm_state_machine_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6532 port->vdm_state_machine_timer.function = vdm_state_machine_timer_handler;
6533 hrtimer_init(&port->enable_frs_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6534 port->enable_frs_timer.function = enable_frs_timer_handler;
6535 hrtimer_init(&port->send_discover_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6536 port->send_discover_timer.function = send_discover_timer_handler;
6538 spin_lock_init(&port->pd_event_lock);
6540 init_completion(&port->tx_complete);
6541 init_completion(&port->swap_complete);
6542 init_completion(&port->pps_complete);
6543 tcpm_debugfs_init(port);
6545 err = tcpm_fw_get_caps(port, tcpc->fwnode);
6547 goto out_destroy_wq;
6549 port->try_role = port->typec_caps.prefer_role;
6551 port->typec_caps.fwnode = tcpc->fwnode;
6552 port->typec_caps.revision = 0x0120; /* Type-C spec release 1.2 */
6553 port->typec_caps.pd_revision = 0x0300; /* USB-PD spec release 3.0 */
6554 port->typec_caps.svdm_version = SVDM_VER_2_0;
6555 port->typec_caps.driver_data = port;
6556 port->typec_caps.ops = &tcpm_ops;
6557 port->typec_caps.orientation_aware = 1;
6559 port->partner_desc.identity = &port->partner_ident;
6560 port->port_type = port->typec_caps.type;
6562 port->role_sw = usb_role_switch_get(port->dev);
6563 if (IS_ERR(port->role_sw)) {
6564 err = PTR_ERR(port->role_sw);
6565 goto out_destroy_wq;
6568 err = devm_tcpm_psy_register(port);
6570 goto out_role_sw_put;
6571 power_supply_changed(port->psy);
6573 err = tcpm_port_register_pd(port);
6575 goto out_role_sw_put;
6577 port->typec_caps.pd = port->pd;
6579 port->typec_port = typec_register_port(port->dev, &port->typec_caps);
6580 if (IS_ERR(port->typec_port)) {
6581 err = PTR_ERR(port->typec_port);
6582 goto out_unregister_pd;
6585 typec_port_register_altmodes(port->typec_port,
6586 &tcpm_altmode_ops, port,
6587 port->port_altmode, ALTMODE_DISCOVERY_MAX);
6588 port->registered = true;
6590 mutex_lock(&port->lock);
6592 mutex_unlock(&port->lock);
6594 tcpm_log(port, "%s: registered", dev_name(dev));
6598 tcpm_port_unregister_pd(port);
6600 usb_role_switch_put(port->role_sw);
6602 tcpm_debugfs_exit(port);
6603 kthread_destroy_worker(port->wq);
6604 return ERR_PTR(err);
6606 EXPORT_SYMBOL_GPL(tcpm_register_port);
6608 void tcpm_unregister_port(struct tcpm_port *port)
6612 port->registered = false;
6613 kthread_destroy_worker(port->wq);
6615 hrtimer_cancel(&port->send_discover_timer);
6616 hrtimer_cancel(&port->enable_frs_timer);
6617 hrtimer_cancel(&port->vdm_state_machine_timer);
6618 hrtimer_cancel(&port->state_machine_timer);
6620 tcpm_reset_port(port);
6622 tcpm_port_unregister_pd(port);
6624 for (i = 0; i < ARRAY_SIZE(port->port_altmode); i++)
6625 typec_unregister_altmode(port->port_altmode[i]);
6626 typec_unregister_port(port->typec_port);
6627 usb_role_switch_put(port->role_sw);
6628 tcpm_debugfs_exit(port);
6630 EXPORT_SYMBOL_GPL(tcpm_unregister_port);
6632 MODULE_AUTHOR("Guenter Roeck <groeck@chromium.org>");
6633 MODULE_DESCRIPTION("USB Type-C Port Manager");
6634 MODULE_LICENSE("GPL");