Debian Codegraph @

drivers/usb/typec/tcpm/tcpm.c

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