Debian Codegraph @

drivers/usb/typec/tcpm/tcpm.c

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