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