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        /* Set to true when Discover_Identity Command is expected to be sent in Ready states. */
 345        bool send_discover;
 346        bool op_vsafe5v;
 347
 348        int try_role;
 349        int try_snk_count;
 350        int try_src_count;
 351
 352        enum pd_msg_request queued_message;
 353
 354        enum tcpm_state enter_state;
 355        enum tcpm_state prev_state;
 356        enum tcpm_state state;
 357        enum tcpm_state delayed_state;
 358        ktime_t delayed_runtime;
 359        unsigned long delay_ms;
 360
 361        spinlock_t pd_event_lock;
 362        u32 pd_events;
 363
 364        struct kthread_work event_work;
 365        struct hrtimer state_machine_timer;
 366        struct kthread_work state_machine;
 367        struct hrtimer vdm_state_machine_timer;
 368        struct kthread_work vdm_state_machine;
 369        struct hrtimer enable_frs_timer;
 370        struct kthread_work enable_frs;
 371        struct hrtimer send_discover_timer;
 372        struct kthread_work send_discover_work;
 373        bool state_machine_running;
 374        /* Set to true when VDM State Machine has following actions. */
 375        bool vdm_sm_running;
 376
 377        struct completion tx_complete;
 378        enum tcpm_transmit_status tx_status;
 379
 380        struct mutex swap_lock;         /* swap command lock */
 381        bool swap_pending;
 382        bool non_pd_role_swap;
 383        struct completion swap_complete;
 384        int swap_status;
 385
 386        unsigned int negotiated_rev;
 387        unsigned int message_id;
 388        unsigned int caps_count;
 389        unsigned int hard_reset_count;
 390        bool pd_capable;
 391        bool explicit_contract;
 392        unsigned int rx_msgid;
 393
 394        /* Partner capabilities/requests */
 395        u32 sink_request;
 396        u32 source_caps[PDO_MAX_OBJECTS];
 397        unsigned int nr_source_caps;
 398        u32 sink_caps[PDO_MAX_OBJECTS];
 399        unsigned int nr_sink_caps;
 400
 401        /* Local capabilities */
 402        u32 src_pdo[PDO_MAX_OBJECTS];
 403        unsigned int nr_src_pdo;
 404        u32 snk_pdo[PDO_MAX_OBJECTS];
 405        unsigned int nr_snk_pdo;
 406        u32 snk_vdo_v1[VDO_MAX_OBJECTS];
 407        unsigned int nr_snk_vdo_v1;
 408        u32 snk_vdo[VDO_MAX_OBJECTS];
 409        unsigned int nr_snk_vdo;
 410
 411        unsigned int operating_snk_mw;
 412        bool update_sink_caps;
 413
 414        /* Requested current / voltage to the port partner */
 415        u32 req_current_limit;
 416        u32 req_supply_voltage;
 417        /* Actual current / voltage limit of the local port */
 418        u32 current_limit;
 419        u32 supply_voltage;
 420
 421        /* Used to export TA voltage and current */
 422        struct power_supply *psy;
 423        struct power_supply_desc psy_desc;
 424        enum power_supply_usb_type usb_type;
 425
 426        u32 bist_request;
 427
 428        /* PD state for Vendor Defined Messages */
 429        enum vdm_states vdm_state;
 430        u32 vdm_retries;
 431        /* next Vendor Defined Message to send */
 432        u32 vdo_data[VDO_MAX_SIZE];
 433        u8 vdo_count;
 434        /* VDO to retry if UFP responder replied busy */
 435        u32 vdo_retry;
 436
 437        /* PPS */
 438        struct pd_pps_data pps_data;
 439        struct completion pps_complete;
 440        bool pps_pending;
 441        int pps_status;
 442
 443        /* Alternate mode data */
 444        struct pd_mode_data mode_data;
 445        struct typec_altmode *partner_altmode[ALTMODE_DISCOVERY_MAX];
 446        struct typec_altmode *port_altmode[ALTMODE_DISCOVERY_MAX];
 447
 448        /* Deadline in jiffies to exit src_try_wait state */
 449        unsigned long max_wait;
 450
 451        /* port belongs to a self powered device */
 452        bool self_powered;
 453
 454        /* Sink FRS */
 455        enum frs_typec_current new_source_frs_current;
 456
 457        /* Sink caps have been queried */
 458        bool sink_cap_done;
 459
 460        /* Collision Avoidance and Atomic Message Sequence */
 461        enum tcpm_state upcoming_state;
 462        enum tcpm_ams ams;
 463        enum tcpm_ams next_ams;
 464        bool in_ams;
 465
 466        /* Auto vbus discharge status */
 467        bool auto_vbus_discharge_enabled;
 468
 469        /*
 470         * When set, port requests PD_P_SNK_STDBY_MW upon entering SNK_DISCOVERY and
 471         * the actual currrent limit after RX of PD_CTRL_PSRDY for PD link,
 472         * SNK_READY for non-pd link.
 473         */
 474        bool slow_charger_loop;
 475#ifdef CONFIG_DEBUG_FS
 476        struct dentry *dentry;
 477        struct mutex logbuffer_lock;    /* log buffer access lock */
 478        int logbuffer_head;
 479        int logbuffer_tail;
 480        u8 *logbuffer[LOG_BUFFER_ENTRIES];
 481#endif
 482};
 483
 484struct pd_rx_event {
 485        struct kthread_work work;
 486        struct tcpm_port *port;
 487        struct pd_message msg;
 488};
 489
 490static const char * const pd_rev[] = {
 491        [PD_REV10]              = "rev1",
 492        [PD_REV20]              = "rev2",
 493        [PD_REV30]              = "rev3",
 494};
 495
 496#define tcpm_cc_is_sink(cc) \
 497        ((cc) == TYPEC_CC_RP_DEF || (cc) == TYPEC_CC_RP_1_5 || \
 498         (cc) == TYPEC_CC_RP_3_0)
 499
 500#define tcpm_port_is_sink(port) \
 501        ((tcpm_cc_is_sink((port)->cc1) && !tcpm_cc_is_sink((port)->cc2)) || \
 502         (tcpm_cc_is_sink((port)->cc2) && !tcpm_cc_is_sink((port)->cc1)))
 503
 504#define tcpm_cc_is_source(cc) ((cc) == TYPEC_CC_RD)
 505#define tcpm_cc_is_audio(cc) ((cc) == TYPEC_CC_RA)
 506#define tcpm_cc_is_open(cc) ((cc) == TYPEC_CC_OPEN)
 507
 508#define tcpm_port_is_source(port) \
 509        ((tcpm_cc_is_source((port)->cc1) && \
 510         !tcpm_cc_is_source((port)->cc2)) || \
 511         (tcpm_cc_is_source((port)->cc2) && \
 512          !tcpm_cc_is_source((port)->cc1)))
 513
 514#define tcpm_port_is_debug(port) \
 515        (tcpm_cc_is_source((port)->cc1) && tcpm_cc_is_source((port)->cc2))
 516
 517#define tcpm_port_is_audio(port) \
 518        (tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_audio((port)->cc2))
 519
 520#define tcpm_port_is_audio_detached(port) \
 521        ((tcpm_cc_is_audio((port)->cc1) && tcpm_cc_is_open((port)->cc2)) || \
 522         (tcpm_cc_is_audio((port)->cc2) && tcpm_cc_is_open((port)->cc1)))
 523
 524#define tcpm_try_snk(port) \
 525        ((port)->try_snk_count == 0 && (port)->try_role == TYPEC_SINK && \
 526        (port)->port_type == TYPEC_PORT_DRP)
 527
 528#define tcpm_try_src(port) \
 529        ((port)->try_src_count == 0 && (port)->try_role == TYPEC_SOURCE && \
 530        (port)->port_type == TYPEC_PORT_DRP)
 531
 532#define tcpm_data_role_for_source(port) \
 533        ((port)->typec_caps.data == TYPEC_PORT_UFP ? \
 534        TYPEC_DEVICE : TYPEC_HOST)
 535
 536#define tcpm_data_role_for_sink(port) \
 537        ((port)->typec_caps.data == TYPEC_PORT_DFP ? \
 538        TYPEC_HOST : TYPEC_DEVICE)
 539
 540#define tcpm_sink_tx_ok(port) \
 541        (tcpm_port_is_sink(port) && \
 542        ((port)->cc1 == TYPEC_CC_RP_3_0 || (port)->cc2 == TYPEC_CC_RP_3_0))
 543
 544#define tcpm_wait_for_discharge(port) \
 545        (((port)->auto_vbus_discharge_enabled && !(port)->vbus_vsafe0v) ? PD_T_SAFE_0V : 0)
 546
 547static enum tcpm_state tcpm_default_state(struct tcpm_port *port)
 548{
 549        if (port->port_type == TYPEC_PORT_DRP) {
 550                if (port->try_role == TYPEC_SINK)
 551                        return SNK_UNATTACHED;
 552                else if (port->try_role == TYPEC_SOURCE)
 553                        return SRC_UNATTACHED;
 554                /* Fall through to return SRC_UNATTACHED */
 555        } else if (port->port_type == TYPEC_PORT_SNK) {
 556                return SNK_UNATTACHED;
 557        }
 558        return SRC_UNATTACHED;
 559}
 560
 561static bool tcpm_port_is_disconnected(struct tcpm_port *port)
 562{
 563        return (!port->attached && port->cc1 == TYPEC_CC_OPEN &&
 564                port->cc2 == TYPEC_CC_OPEN) ||
 565               (port->attached && ((port->polarity == TYPEC_POLARITY_CC1 &&
 566                                    port->cc1 == TYPEC_CC_OPEN) ||
 567                                   (port->polarity == TYPEC_POLARITY_CC2 &&
 568                                    port->cc2 == TYPEC_CC_OPEN)));
 569}
 570
 571/*
 572 * Logging
 573 */
 574
 575#ifdef CONFIG_DEBUG_FS
 576
 577static bool tcpm_log_full(struct tcpm_port *port)
 578{
 579        return port->logbuffer_tail ==
 580                (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
 581}
 582
 583__printf(2, 0)
 584static void _tcpm_log(struct tcpm_port *port, const char *fmt, va_list args)
 585{
 586        char tmpbuffer[LOG_BUFFER_ENTRY_SIZE];
 587        u64 ts_nsec = local_clock();
 588        unsigned long rem_nsec;
 589
 590        mutex_lock(&port->logbuffer_lock);
 591        if (!port->logbuffer[port->logbuffer_head]) {
 592                port->logbuffer[port->logbuffer_head] =
 593                                kzalloc(LOG_BUFFER_ENTRY_SIZE, GFP_KERNEL);
 594                if (!port->logbuffer[port->logbuffer_head]) {
 595                        mutex_unlock(&port->logbuffer_lock);
 596                        return;
 597                }
 598        }
 599
 600        vsnprintf(tmpbuffer, sizeof(tmpbuffer), fmt, args);
 601
 602        if (tcpm_log_full(port)) {
 603                port->logbuffer_head = max(port->logbuffer_head - 1, 0);
 604                strcpy(tmpbuffer, "overflow");
 605        }
 606
 607        if (port->logbuffer_head < 0 ||
 608            port->logbuffer_head >= LOG_BUFFER_ENTRIES) {
 609                dev_warn(port->dev,
 610                         "Bad log buffer index %d\n", port->logbuffer_head);
 611                goto abort;
 612        }
 613
 614        if (!port->logbuffer[port->logbuffer_head]) {
 615                dev_warn(port->dev,
 616                         "Log buffer index %d is NULL\n", port->logbuffer_head);
 617                goto abort;
 618        }
 619
 620        rem_nsec = do_div(ts_nsec, 1000000000);
 621        scnprintf(port->logbuffer[port->logbuffer_head],
 622                  LOG_BUFFER_ENTRY_SIZE, "[%5lu.%06lu] %s",
 623                  (unsigned long)ts_nsec, rem_nsec / 1000,
 624                  tmpbuffer);
 625        port->logbuffer_head = (port->logbuffer_head + 1) % LOG_BUFFER_ENTRIES;
 626
 627abort:
 628        mutex_unlock(&port->logbuffer_lock);
 629}
 630
 631__printf(2, 3)
 632static void tcpm_log(struct tcpm_port *port, const char *fmt, ...)
 633{
 634        va_list args;
 635
 636        /* Do not log while disconnected and unattached */
 637        if (tcpm_port_is_disconnected(port) &&
 638            (port->state == SRC_UNATTACHED || port->state == SNK_UNATTACHED ||
 639             port->state == TOGGLING))
 640                return;
 641
 642        va_start(args, fmt);
 643        _tcpm_log(port, fmt, args);
 644        va_end(args);
 645}
 646
 647__printf(2, 3)
 648static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...)
 649{
 650        va_list args;
 651
 652        va_start(args, fmt);
 653        _tcpm_log(port, fmt, args);
 654        va_end(args);
 655}
 656
 657static void tcpm_log_source_caps(struct tcpm_port *port)
 658{
 659        int i;
 660
 661        for (i = 0; i < port->nr_source_caps; i++) {
 662                u32 pdo = port->source_caps[i];
 663                enum pd_pdo_type type = pdo_type(pdo);
 664                char msg[64];
 665
 666                switch (type) {
 667                case PDO_TYPE_FIXED:
 668                        scnprintf(msg, sizeof(msg),
 669                                  "%u mV, %u mA [%s%s%s%s%s%s]",
 670                                  pdo_fixed_voltage(pdo),
 671                                  pdo_max_current(pdo),
 672                                  (pdo & PDO_FIXED_DUAL_ROLE) ?
 673                                                        "R" : "",
 674                                  (pdo & PDO_FIXED_SUSPEND) ?
 675                                                        "S" : "",
 676                                  (pdo & PDO_FIXED_HIGHER_CAP) ?
 677                                                        "H" : "",
 678                                  (pdo & PDO_FIXED_USB_COMM) ?
 679                                                        "U" : "",
 680                                  (pdo & PDO_FIXED_DATA_SWAP) ?
 681                                                        "D" : "",
 682                                  (pdo & PDO_FIXED_EXTPOWER) ?
 683                                                        "E" : "");
 684                        break;
 685                case PDO_TYPE_VAR:
 686                        scnprintf(msg, sizeof(msg),
 687                                  "%u-%u mV, %u mA",
 688                                  pdo_min_voltage(pdo),
 689                                  pdo_max_voltage(pdo),
 690                                  pdo_max_current(pdo));
 691                        break;
 692                case PDO_TYPE_BATT:
 693                        scnprintf(msg, sizeof(msg),
 694                                  "%u-%u mV, %u mW",
 695                                  pdo_min_voltage(pdo),
 696                                  pdo_max_voltage(pdo),
 697                                  pdo_max_power(pdo));
 698                        break;
 699                case PDO_TYPE_APDO:
 700                        if (pdo_apdo_type(pdo) == APDO_TYPE_PPS)
 701                                scnprintf(msg, sizeof(msg),
 702                                          "%u-%u mV, %u mA",
 703                                          pdo_pps_apdo_min_voltage(pdo),
 704                                          pdo_pps_apdo_max_voltage(pdo),
 705                                          pdo_pps_apdo_max_current(pdo));
 706                        else
 707                                strcpy(msg, "undefined APDO");
 708                        break;
 709                default:
 710                        strcpy(msg, "undefined");
 711                        break;
 712                }
 713                tcpm_log(port, " PDO %d: type %d, %s",
 714                         i, type, msg);
 715        }
 716}
 717
 718static int tcpm_debug_show(struct seq_file *s, void *v)
 719{
 720        struct tcpm_port *port = (struct tcpm_port *)s->private;
 721        int tail;
 722
 723        mutex_lock(&port->logbuffer_lock);
 724        tail = port->logbuffer_tail;
 725        while (tail != port->logbuffer_head) {
 726                seq_printf(s, "%s\n", port->logbuffer[tail]);
 727                tail = (tail + 1) % LOG_BUFFER_ENTRIES;
 728        }
 729        if (!seq_has_overflowed(s))
 730                port->logbuffer_tail = tail;
 731        mutex_unlock(&port->logbuffer_lock);
 732
 733        return 0;
 734}
 735DEFINE_SHOW_ATTRIBUTE(tcpm_debug);
 736
 737static void tcpm_debugfs_init(struct tcpm_port *port)
 738{
 739        char name[NAME_MAX];
 740
 741        mutex_init(&port->logbuffer_lock);
 742        snprintf(name, NAME_MAX, "tcpm-%s", dev_name(port->dev));
 743        port->dentry = debugfs_create_dir(name, usb_debug_root);
 744        debugfs_create_file("log", S_IFREG | 0444, port->dentry, port,
 745                            &tcpm_debug_fops);
 746}
 747
 748static void tcpm_debugfs_exit(struct tcpm_port *port)
 749{
 750        int i;
 751
 752        mutex_lock(&port->logbuffer_lock);
 753        for (i = 0; i < LOG_BUFFER_ENTRIES; i++) {
 754                kfree(port->logbuffer[i]);
 755                port->logbuffer[i] = NULL;
 756        }
 757        mutex_unlock(&port->logbuffer_lock);
 758
 759        debugfs_remove(port->dentry);
 760}
 761
 762#else
 763
 764__printf(2, 3)
 765static void tcpm_log(const struct tcpm_port *port, const char *fmt, ...) { }
 766__printf(2, 3)
 767static void tcpm_log_force(struct tcpm_port *port, const char *fmt, ...) { }
 768static void tcpm_log_source_caps(struct tcpm_port *port) { }
 769static void tcpm_debugfs_init(const struct tcpm_port *port) { }
 770static void tcpm_debugfs_exit(const struct tcpm_port *port) { }
 771
 772#endif
 773
 774static void tcpm_set_cc(struct tcpm_port *port, enum typec_cc_status cc)
 775{
 776        tcpm_log(port, "cc:=%d", cc);
 777        port->cc_req = cc;
 778        port->tcpc->set_cc(port->tcpc, cc);
 779}
 780
 781static int tcpm_enable_auto_vbus_discharge(struct tcpm_port *port, bool enable)
 782{
 783        int ret = 0;
 784
 785        if (port->tcpc->enable_auto_vbus_discharge) {
 786                ret = port->tcpc->enable_auto_vbus_discharge(port->tcpc, enable);
 787                tcpm_log_force(port, "%s vbus discharge ret:%d", enable ? "enable" : "disable",
 788                               ret);
 789                if (!ret)
 790                        port->auto_vbus_discharge_enabled = enable;
 791        }
 792
 793        return ret;
 794}
 795
 796static void tcpm_apply_rc(struct tcpm_port *port)
 797{
 798        /*
 799         * TCPCI: Move to APPLY_RC state to prevent disconnect during PR_SWAP
 800         * when Vbus auto discharge on disconnect is enabled.
 801         */
 802        if (port->tcpc->enable_auto_vbus_discharge && port->tcpc->apply_rc) {
 803                tcpm_log(port, "Apply_RC");
 804                port->tcpc->apply_rc(port->tcpc, port->cc_req, port->polarity);
 805                tcpm_enable_auto_vbus_discharge(port, false);
 806        }
 807}
 808
 809/*
 810 * Determine RP value to set based on maximum current supported
 811 * by a port if configured as source.
 812 * Returns CC value to report to link partner.
 813 */
 814static enum typec_cc_status tcpm_rp_cc(struct tcpm_port *port)
 815{
 816        const u32 *src_pdo = port->src_pdo;
 817        int nr_pdo = port->nr_src_pdo;
 818        int i;
 819
 820        /*
 821         * Search for first entry with matching voltage.
 822         * It should report the maximum supported current.
 823         */
 824        for (i = 0; i < nr_pdo; i++) {
 825                const u32 pdo = src_pdo[i];
 826
 827                if (pdo_type(pdo) == PDO_TYPE_FIXED &&
 828                    pdo_fixed_voltage(pdo) == 5000) {
 829                        unsigned int curr = pdo_max_current(pdo);
 830
 831                        if (curr >= 3000)
 832                                return TYPEC_CC_RP_3_0;
 833                        else if (curr >= 1500)
 834                                return TYPEC_CC_RP_1_5;
 835                        return TYPEC_CC_RP_DEF;
 836                }
 837        }
 838
 839        return TYPEC_CC_RP_DEF;
 840}
 841
 842static void tcpm_ams_finish(struct tcpm_port *port)
 843{
 844        tcpm_log(port, "AMS %s finished", tcpm_ams_str[port->ams]);
 845
 846        if (port->pd_capable && port->pwr_role == TYPEC_SOURCE) {
 847                if (port->negotiated_rev >= PD_REV30)
 848                        tcpm_set_cc(port, SINK_TX_OK);
 849                else
 850                        tcpm_set_cc(port, SINK_TX_NG);
 851        } else if (port->pwr_role == TYPEC_SOURCE) {
 852                tcpm_set_cc(port, tcpm_rp_cc(port));
 853        }
 854
 855        port->in_ams = false;
 856        port->ams = NONE_AMS;
 857}
 858
 859static int tcpm_pd_transmit(struct tcpm_port *port,
 860                            enum tcpm_transmit_type type,
 861                            const struct pd_message *msg)
 862{
 863        unsigned long timeout;
 864        int ret;
 865
 866        if (msg)
 867                tcpm_log(port, "PD TX, header: %#x", le16_to_cpu(msg->header));
 868        else
 869                tcpm_log(port, "PD TX, type: %#x", type);
 870
 871        reinit_completion(&port->tx_complete);
 872        ret = port->tcpc->pd_transmit(port->tcpc, type, msg, port->negotiated_rev);
 873        if (ret < 0)
 874                return ret;
 875
 876        mutex_unlock(&port->lock);
 877        timeout = wait_for_completion_timeout(&port->tx_complete,
 878                                msecs_to_jiffies(PD_T_TCPC_TX_TIMEOUT));
 879        mutex_lock(&port->lock);
 880        if (!timeout)
 881                return -ETIMEDOUT;
 882
 883        switch (port->tx_status) {
 884        case TCPC_TX_SUCCESS:
 885                port->message_id = (port->message_id + 1) & PD_HEADER_ID_MASK;
 886                /*
 887                 * USB PD rev 2.0, 8.3.2.2.1:
 888                 * USB PD rev 3.0, 8.3.2.1.3:
 889                 * "... Note that every AMS is Interruptible until the first
 890                 * Message in the sequence has been successfully sent (GoodCRC
 891                 * Message received)."
 892                 */
 893                if (port->ams != NONE_AMS)
 894                        port->in_ams = true;
 895                break;
 896        case TCPC_TX_DISCARDED:
 897                ret = -EAGAIN;
 898                break;
 899        case TCPC_TX_FAILED:
 900        default:
 901                ret = -EIO;
 902                break;
 903        }
 904
 905        /* Some AMS don't expect responses. Finish them here. */
 906        if (port->ams == ATTENTION || port->ams == SOURCE_ALERT)
 907                tcpm_ams_finish(port);
 908
 909        return ret;
 910}
 911
 912void tcpm_pd_transmit_complete(struct tcpm_port *port,
 913                               enum tcpm_transmit_status status)
 914{
 915        tcpm_log(port, "PD TX complete, status: %u", status);
 916        port->tx_status = status;
 917        complete(&port->tx_complete);
 918}
 919EXPORT_SYMBOL_GPL(tcpm_pd_transmit_complete);
 920
 921static int tcpm_mux_set(struct tcpm_port *port, int state,
 922                        enum usb_role usb_role,
 923                        enum typec_orientation orientation)
 924{
 925        int ret;
 926
 927        tcpm_log(port, "Requesting mux state %d, usb-role %d, orientation %d",
 928                 state, usb_role, orientation);
 929
 930        ret = typec_set_orientation(port->typec_port, orientation);
 931        if (ret)
 932                return ret;
 933
 934        if (port->role_sw) {
 935                ret = usb_role_switch_set_role(port->role_sw, usb_role);
 936                if (ret)
 937                        return ret;
 938        }
 939
 940        return typec_set_mode(port->typec_port, state);
 941}
 942
 943static int tcpm_set_polarity(struct tcpm_port *port,
 944                             enum typec_cc_polarity polarity)
 945{
 946        int ret;
 947
 948        tcpm_log(port, "polarity %d", polarity);
 949
 950        ret = port->tcpc->set_polarity(port->tcpc, polarity);
 951        if (ret < 0)
 952                return ret;
 953
 954        port->polarity = polarity;
 955
 956        return 0;
 957}
 958
 959static int tcpm_set_vconn(struct tcpm_port *port, bool enable)
 960{
 961        int ret;
 962
 963        tcpm_log(port, "vconn:=%d", enable);
 964
 965        ret = port->tcpc->set_vconn(port->tcpc, enable);
 966        if (!ret) {
 967                port->vconn_role = enable ? TYPEC_SOURCE : TYPEC_SINK;
 968                typec_set_vconn_role(port->typec_port, port->vconn_role);
 969        }
 970
 971        return ret;
 972}
 973
 974static u32 tcpm_get_current_limit(struct tcpm_port *port)
 975{
 976        enum typec_cc_status cc;
 977        u32 limit;
 978
 979        cc = port->polarity ? port->cc2 : port->cc1;
 980        switch (cc) {
 981        case TYPEC_CC_RP_1_5:
 982                limit = 1500;
 983                break;
 984        case TYPEC_CC_RP_3_0:
 985                limit = 3000;
 986                break;
 987        case TYPEC_CC_RP_DEF:
 988        default:
 989                if (port->tcpc->get_current_limit)
 990                        limit = port->tcpc->get_current_limit(port->tcpc);
 991                else
 992                        limit = 0;
 993                break;
 994        }
 995
 996        return limit;
 997}
 998
 999static int tcpm_set_current_limit(struct tcpm_port *port, u32 max_ma, u32 mv)
1000{
1001        int ret = -EOPNOTSUPP;
1002
1003        tcpm_log(port, "Setting voltage/current limit %u mV %u mA", mv, max_ma);
1004
1005        port->supply_voltage = mv;
1006        port->current_limit = max_ma;
1007        power_supply_changed(port->psy);
1008
1009        if (port->tcpc->set_current_limit)
1010                ret = port->tcpc->set_current_limit(port->tcpc, max_ma, mv);
1011
1012        return ret;
1013}
1014
1015static int tcpm_set_attached_state(struct tcpm_port *port, bool attached)
1016{
1017        return port->tcpc->set_roles(port->tcpc, attached, port->pwr_role,
1018                                     port->data_role);
1019}
1020
1021static int tcpm_set_roles(struct tcpm_port *port, bool attached,
1022                          enum typec_role role, enum typec_data_role data)
1023{
1024        enum typec_orientation orientation;
1025        enum usb_role usb_role;
1026        int ret;
1027
1028        if (port->polarity == TYPEC_POLARITY_CC1)
1029                orientation = TYPEC_ORIENTATION_NORMAL;
1030        else
1031                orientation = TYPEC_ORIENTATION_REVERSE;
1032
1033        if (port->typec_caps.data == TYPEC_PORT_DRD) {
1034                if (data == TYPEC_HOST)
1035                        usb_role = USB_ROLE_HOST;
1036                else
1037                        usb_role = USB_ROLE_DEVICE;
1038        } else if (port->typec_caps.data == TYPEC_PORT_DFP) {
1039                if (data == TYPEC_HOST) {
1040                        if (role == TYPEC_SOURCE)
1041                                usb_role = USB_ROLE_HOST;
1042                        else
1043                                usb_role = USB_ROLE_NONE;
1044                } else {
1045                        return -ENOTSUPP;
1046                }
1047        } else {
1048                if (data == TYPEC_DEVICE) {
1049                        if (role == TYPEC_SINK)
1050                                usb_role = USB_ROLE_DEVICE;
1051                        else
1052                                usb_role = USB_ROLE_NONE;
1053                } else {
1054                        return -ENOTSUPP;
1055                }
1056        }
1057
1058        ret = tcpm_mux_set(port, TYPEC_STATE_USB, usb_role, orientation);
1059        if (ret < 0)
1060                return ret;
1061
1062        ret = port->tcpc->set_roles(port->tcpc, attached, role, data);
1063        if (ret < 0)
1064                return ret;
1065
1066        port->pwr_role = role;
1067        port->data_role = data;
1068        typec_set_data_role(port->typec_port, data);
1069        typec_set_pwr_role(port->typec_port, role);
1070
1071        return 0;
1072}
1073
1074static int tcpm_set_pwr_role(struct tcpm_port *port, enum typec_role role)
1075{
1076        int ret;
1077
1078        ret = port->tcpc->set_roles(port->tcpc, true, role,
1079                                    port->data_role);
1080        if (ret < 0)
1081                return ret;
1082
1083        port->pwr_role = role;
1084        typec_set_pwr_role(port->typec_port, role);
1085
1086        return 0;
1087}
1088
1089/*
1090 * Transform the PDO to be compliant to PD rev2.0.
1091 * Return 0 if the PDO type is not defined in PD rev2.0.
1092 * Otherwise, return the converted PDO.
1093 */
1094static u32 tcpm_forge_legacy_pdo(struct tcpm_port *port, u32 pdo, enum typec_role role)
1095{
1096        switch (pdo_type(pdo)) {
1097        case PDO_TYPE_FIXED:
1098                if (role == TYPEC_SINK)
1099                        return pdo & ~PDO_FIXED_FRS_CURR_MASK;
1100                else
1101                        return pdo & ~PDO_FIXED_UNCHUNK_EXT;
1102        case PDO_TYPE_VAR:
1103        case PDO_TYPE_BATT:
1104                return pdo;
1105        case PDO_TYPE_APDO:
1106        default:
1107                return 0;
1108        }
1109}
1110
1111static int tcpm_pd_send_source_caps(struct tcpm_port *port)
1112{
1113        struct pd_message msg;
1114        u32 pdo;
1115        unsigned int i, nr_pdo = 0;
1116
1117        memset(&msg, 0, sizeof(msg));
1118
1119        for (i = 0; i < port->nr_src_pdo; i++) {
1120                if (port->negotiated_rev >= PD_REV30) {
1121                        msg.payload[nr_pdo++] = cpu_to_le32(port->src_pdo[i]);
1122                } else {
1123                        pdo = tcpm_forge_legacy_pdo(port, port->src_pdo[i], TYPEC_SOURCE);
1124                        if (pdo)
1125                                msg.payload[nr_pdo++] = cpu_to_le32(pdo);
1126                }
1127        }
1128
1129        if (!nr_pdo) {
1130                /* No source capabilities defined, sink only */
1131                msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
1132                                          port->pwr_role,
1133                                          port->data_role,
1134                                          port->negotiated_rev,
1135                                          port->message_id, 0);
1136        } else {
1137                msg.header = PD_HEADER_LE(PD_DATA_SOURCE_CAP,
1138                                          port->pwr_role,
1139                                          port->data_role,
1140                                          port->negotiated_rev,
1141                                          port->message_id,
1142                                          nr_pdo);
1143        }
1144
1145        return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1146}
1147
1148static int tcpm_pd_send_sink_caps(struct tcpm_port *port)
1149{
1150        struct pd_message msg;
1151        u32 pdo;
1152        unsigned int i, nr_pdo = 0;
1153
1154        memset(&msg, 0, sizeof(msg));
1155
1156        for (i = 0; i < port->nr_snk_pdo; i++) {
1157                if (port->negotiated_rev >= PD_REV30) {
1158                        msg.payload[nr_pdo++] = cpu_to_le32(port->snk_pdo[i]);
1159                } else {
1160                        pdo = tcpm_forge_legacy_pdo(port, port->snk_pdo[i], TYPEC_SINK);
1161                        if (pdo)
1162                                msg.payload[nr_pdo++] = cpu_to_le32(pdo);
1163                }
1164        }
1165
1166        if (!nr_pdo) {
1167                /* No sink capabilities defined, source only */
1168                msg.header = PD_HEADER_LE(PD_CTRL_REJECT,
1169                                          port->pwr_role,
1170                                          port->data_role,
1171                                          port->negotiated_rev,
1172                                          port->message_id, 0);
1173        } else {
1174                msg.header = PD_HEADER_LE(PD_DATA_SINK_CAP,
1175                                          port->pwr_role,
1176                                          port->data_role,
1177                                          port->negotiated_rev,
1178                                          port->message_id,
1179                                          nr_pdo);
1180        }
1181
1182        return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
1183}
1184
1185static void mod_tcpm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1186{
1187        if (delay_ms) {
1188                hrtimer_start(&port->state_machine_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1189        } else {
1190                hrtimer_cancel(&port->state_machine_timer);
1191                kthread_queue_work(port->wq, &port->state_machine);
1192        }
1193}
1194
1195static void mod_vdm_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1196{
1197        if (delay_ms) {
1198                hrtimer_start(&port->vdm_state_machine_timer, ms_to_ktime(delay_ms),
1199                              HRTIMER_MODE_REL);
1200        } else {
1201                hrtimer_cancel(&port->vdm_state_machine_timer);
1202                kthread_queue_work(port->wq, &port->vdm_state_machine);
1203        }
1204}
1205
1206static void mod_enable_frs_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1207{
1208        if (delay_ms) {
1209                hrtimer_start(&port->enable_frs_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1210        } else {
1211                hrtimer_cancel(&port->enable_frs_timer);
1212                kthread_queue_work(port->wq, &port->enable_frs);
1213        }
1214}
1215
1216static void mod_send_discover_delayed_work(struct tcpm_port *port, unsigned int delay_ms)
1217{
1218        if (delay_ms) {
1219                hrtimer_start(&port->send_discover_timer, ms_to_ktime(delay_ms), HRTIMER_MODE_REL);
1220        } else {
1221                hrtimer_cancel(&port->send_discover_timer);
1222                kthread_queue_work(port->wq, &port->send_discover_work);
1223        }
1224}
1225
1226static void tcpm_set_state(struct tcpm_port *port, enum tcpm_state state,
1227                           unsigned int delay_ms)
1228{
1229        if (delay_ms) {
1230                tcpm_log(port, "pending state change %s -> %s @ %u ms [%s %s]",
1231                         tcpm_states[port->state], tcpm_states[state], delay_ms,
1232                         pd_rev[port->negotiated_rev], tcpm_ams_str[port->ams]);
1233                port->delayed_state = state;
1234                mod_tcpm_delayed_work(port, delay_ms);
1235                port->delayed_runtime = ktime_add(ktime_get(), ms_to_ktime(delay_ms));
1236                port->delay_ms = delay_ms;
1237        } else {
1238                tcpm_log(port, "state change %s -> %s [%s %s]",
1239                         tcpm_states[port->state], tcpm_states[state],
1240                         pd_rev[port->negotiated_rev], tcpm_ams_str[port->ams]);
1241                port->delayed_state = INVALID_STATE;
1242                port->prev_state = port->state;
1243                port->state = state;
1244                /*
1245                 * Don't re-queue the state machine work item if we're currently
1246                 * in the state machine and we're immediately changing states.
1247                 * tcpm_state_machine_work() will continue running the state
1248                 * machine.
1249                 */
1250                if (!port->state_machine_running)
1251                        mod_tcpm_delayed_work(port, 0);
1252        }
1253}
1254
1255static void tcpm_set_state_cond(struct tcpm_port *port, enum tcpm_state state,
1256                                unsigned int delay_ms)
1257{
1258        if (port->enter_state == port->state)
1259                tcpm_set_state(port, state, delay_ms);
1260        else
1261                tcpm_log(port,
1262                         "skipped %sstate change %s -> %s [%u ms], context state %s [%s %s]",
1263                         delay_ms ? "delayed " : "",
1264                         tcpm_states[port->state], tcpm_states[state],
1265                         delay_ms, tcpm_states[port->enter_state],
1266                         pd_rev[port->negotiated_rev], tcpm_ams_str[port->ams]);
1267}
1268
1269static void tcpm_queue_message(struct tcpm_port *port,
1270                               enum pd_msg_request message)
1271{
1272        port->queued_message = message;
1273        mod_tcpm_delayed_work(port, 0);
1274}
1275
1276static bool tcpm_vdm_ams(struct tcpm_port *port)
1277{
1278        switch (port->ams) {
1279        case DISCOVER_IDENTITY:
1280        case SOURCE_STARTUP_CABLE_PLUG_DISCOVER_IDENTITY:
1281        case DISCOVER_SVIDS:
1282        case DISCOVER_MODES:
1283        case DFP_TO_UFP_ENTER_MODE:
1284        case DFP_TO_UFP_EXIT_MODE:
1285        case DFP_TO_CABLE_PLUG_ENTER_MODE:
1286        case DFP_TO_CABLE_PLUG_EXIT_MODE:
1287        case ATTENTION:
1288        case UNSTRUCTURED_VDMS:
1289        case STRUCTURED_VDMS:
1290                break;
1291        default:
1292                return false;
1293        }
1294
1295        return true;
1296}
1297
1298static bool tcpm_ams_interruptible(struct tcpm_port *port)
1299{
1300        switch (port->ams) {
1301        /* Interruptible AMS */
1302        case NONE_AMS:
1303        case SECURITY:
1304        case FIRMWARE_UPDATE:
1305        case DISCOVER_IDENTITY:
1306        case SOURCE_STARTUP_CABLE_PLUG_DISCOVER_IDENTITY:
1307        case DISCOVER_SVIDS:
1308        case DISCOVER_MODES:
1309        case DFP_TO_UFP_ENTER_MODE:
1310        case DFP_TO_UFP_EXIT_MODE:
1311        case DFP_TO_CABLE_PLUG_ENTER_MODE:
1312        case DFP_TO_CABLE_PLUG_EXIT_MODE:
1313        case UNSTRUCTURED_VDMS:
1314        case STRUCTURED_VDMS:
1315        case COUNTRY_INFO:
1316        case COUNTRY_CODES:
1317                break;
1318        /* Non-Interruptible AMS */
1319        default:
1320                if (port->in_ams)
1321                        return false;
1322                break;
1323        }
1324
1325        return true;
1326}
1327
1328static int tcpm_ams_start(struct tcpm_port *port, enum tcpm_ams ams)
1329{
1330        int ret = 0;
1331
1332        tcpm_log(port, "AMS %s start", tcpm_ams_str[ams]);
1333
1334        if (!tcpm_ams_interruptible(port) &&
1335            !(ams == HARD_RESET || ams == SOFT_RESET_AMS)) {
1336                port->upcoming_state = INVALID_STATE;
1337                tcpm_log(port, "AMS %s not interruptible, aborting",
1338                         tcpm_ams_str[port->ams]);
1339                return -EAGAIN;
1340        }
1341
1342        if (port->pwr_role == TYPEC_SOURCE) {
1343                enum typec_cc_status cc_req = port->cc_req;
1344
1345                port->ams = ams;
1346
1347                if (ams == HARD_RESET) {
1348                        tcpm_set_cc(port, tcpm_rp_cc(port));
1349                        tcpm_pd_transmit(port, TCPC_TX_HARD_RESET, NULL);
1350                        tcpm_set_state(port, HARD_RESET_START, 0);
1351                        return ret;
1352                } else if (ams == SOFT_RESET_AMS) {
1353                        if (!port->explicit_contract)
1354                                tcpm_set_cc(port, tcpm_rp_cc(port));
1355                        tcpm_set_state(port, SOFT_RESET_SEND, 0);
1356                        return ret;
1357                } else if (tcpm_vdm_ams(port)) {
1358                        /* tSinkTx is enforced in vdm_run_state_machine */
1359                        if (port->negotiated_rev >= PD_REV30)
1360                                tcpm_set_cc(port, SINK_TX_NG);
1361                        return ret;
1362                }
1363
1364                if (port->negotiated_rev >= PD_REV30)
1365                        tcpm_set_cc(port, SINK_TX_NG);
1366
1367                switch (port->state) {
1368                case SRC_READY:
1369                case SRC_STARTUP:
1370                case SRC_SOFT_RESET_WAIT_SNK_TX:
1371                case SOFT_RESET:
1372                case SOFT_RESET_SEND:
1373                        if (port->negotiated_rev >= PD_REV30)
1374                                tcpm_set_state(port, AMS_START,
1375                                               cc_req == SINK_TX_OK ?
1376                                               PD_T_SINK_TX : 0);
1377                        else
1378                                tcpm_set_state(port, AMS_START, 0);
1379                        break;
1380                default:
1381                        if (port->negotiated_rev >= PD_REV30)
1382                                tcpm_set_state(port, SRC_READY,
1383                                               cc_req == SINK_TX_OK ?
1384                                               PD_T_SINK_TX : 0);
1385                        else
1386                                tcpm_set_state(port, SRC_READY, 0);
1387                        break;
1388                }
1389        } else {
1390                if (port->negotiated_rev >= PD_REV30 &&
1391                    !tcpm_sink_tx_ok(port) &&
1392                    ams != SOFT_RESET_AMS &&
1393                    ams != HARD_RESET) {
1394                        port->upcoming_state = INVALID_STATE;
1395                        tcpm_log(port, "Sink TX No Go");
1396                        return -EAGAIN;
1397                }
1398
1399                port->ams = ams;
1400
1401                if (ams == HARD_RESET) {
1402                        tcpm_pd_transmit(port, TCPC_TX_HARD_RESET, NULL);
1403                        tcpm_set_state(port, HARD_RESET_START, 0);
1404                        return ret;
1405                } else if (tcpm_vdm_ams(port)) {
1406                        return ret;
1407                }
1408
1409                if (port->state == SNK_READY ||
1410                    port->state == SNK_SOFT_RESET)
1411                        tcpm_set_state(port, AMS_START, 0);
1412                else
1413                        tcpm_set_state(port, SNK_READY, 0);
1414        }
1415
1416        return ret;
1417}
1418
1419/*
1420 * VDM/VDO handling functions
1421 */
1422static void tcpm_queue_vdm(struct tcpm_port *port, const u32 header,
1423                           const u32 *data, int cnt)
1424{
1425        WARN_ON(!mutex_is_locked(&port->lock));
1426
1427        /* Make sure we are not still processing a previous VDM packet */
1428        WARN_ON(port->vdm_state > VDM_STATE_DONE);
1429
1430        port->vdo_count = cnt + 1;
1431        port->vdo_data[0] = header;
1432        memcpy(&port->vdo_data[1], data, sizeof(u32) * cnt);
1433        /* Set ready, vdm state machine will actually send */
1434        port->vdm_retries = 0;
1435        port->vdm_state = VDM_STATE_READY;
1436        port->vdm_sm_running = true;
1437
1438        mod_vdm_delayed_work(port, 0);
1439}
1440
1441static void tcpm_queue_vdm_unlocked(struct tcpm_port *port, const u32 header,
1442                                    const u32 *data, int cnt)
1443{
1444        mutex_lock(&port->lock);
1445        tcpm_queue_vdm(port, header, data, cnt);
1446        mutex_unlock(&port->lock);
1447}
1448
1449static void svdm_consume_identity(struct tcpm_port *port, const u32 *p, int cnt)
1450{
1451        u32 vdo = p[VDO_INDEX_IDH];
1452        u32 product = p[VDO_INDEX_PRODUCT];
1453
1454        memset(&port->mode_data, 0, sizeof(port->mode_data));
1455
1456        port->partner_ident.id_header = vdo;
1457        port->partner_ident.cert_stat = p[VDO_INDEX_CSTAT];
1458        port->partner_ident.product = product;
1459
1460        typec_partner_set_identity(port->partner);
1461
1462        tcpm_log(port, "Identity: %04x:%04x.%04x",
1463                 PD_IDH_VID(vdo),
1464                 PD_PRODUCT_PID(product), product & 0xffff);
1465}
1466
1467static bool svdm_consume_svids(struct tcpm_port *port, const u32 *p, int cnt)
1468{
1469        struct pd_mode_data *pmdata = &port->mode_data;
1470        int i;
1471
1472        for (i = 1; i < cnt; i++) {
1473                u16 svid;
1474
1475                svid = (p[i] >> 16) & 0xffff;
1476                if (!svid)
1477                        return false;
1478
1479                if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1480                        goto abort;
1481
1482                pmdata->svids[pmdata->nsvids++] = svid;
1483                tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1484
1485                svid = p[i] & 0xffff;
1486                if (!svid)
1487                        return false;
1488
1489                if (pmdata->nsvids >= SVID_DISCOVERY_MAX)
1490                        goto abort;
1491
1492                pmdata->svids[pmdata->nsvids++] = svid;
1493                tcpm_log(port, "SVID %d: 0x%x", pmdata->nsvids, svid);
1494        }
1495        return true;
1496abort:
1497        tcpm_log(port, "SVID_DISCOVERY_MAX(%d) too low!", SVID_DISCOVERY_MAX);
1498        return false;
1499}
1500
1501static void svdm_consume_modes(struct tcpm_port *port, const u32 *p, int cnt)
1502{
1503        struct pd_mode_data *pmdata = &port->mode_data;
1504        struct typec_altmode_desc *paltmode;
1505        int i;
1506
1507        if (pmdata->altmodes >= ARRAY_SIZE(port->partner_altmode)) {
1508                /* Already logged in svdm_consume_svids() */
1509                return;
1510        }
1511
1512        for (i = 1; i < cnt; i++) {
1513                paltmode = &pmdata->altmode_desc[pmdata->altmodes];
1514                memset(paltmode, 0, sizeof(*paltmode));
1515
1516                paltmode->svid = pmdata->svids[pmdata->svid_index];
1517                paltmode->mode = i;
1518                paltmode->vdo = p[i];
1519
1520                tcpm_log(port, " Alternate mode %d: SVID 0x%04x, VDO %d: 0x%08x",
1521                         pmdata->altmodes, paltmode->svid,
1522                         paltmode->mode, paltmode->vdo);
1523
1524                pmdata->altmodes++;
1525        }
1526}
1527
1528static void tcpm_register_partner_altmodes(struct tcpm_port *port)
1529{
1530        struct pd_mode_data *modep = &port->mode_data;
1531        struct typec_altmode *altmode;
1532        int i;
1533
1534        for (i = 0; i < modep->altmodes; i++) {
1535                altmode = typec_partner_register_altmode(port->partner,
1536                                                &modep->altmode_desc[i]);
1537                if (IS_ERR(altmode)) {
1538                        tcpm_log(port, "Failed to register partner SVID 0x%04x",
1539                                 modep->altmode_desc[i].svid);
1540                        altmode = NULL;
1541                }
1542                port->partner_altmode[i] = altmode;
1543        }
1544}
1545
1546#define supports_modal(port)    PD_IDH_MODAL_SUPP((port)->partner_ident.id_header)
1547
1548static int tcpm_pd_svdm(struct tcpm_port *port, struct typec_altmode *adev,
1549                        const u32 *p, int cnt, u32 *response,
1550                        enum adev_actions *adev_action)
1551{
1552        struct typec_port *typec = port->typec_port;
1553        struct typec_altmode *pdev;
1554        struct pd_mode_data *modep;
1555        int svdm_version;
1556        int rlen = 0;
1557        int cmd_type;
1558        int cmd;
1559        int i;
1560
1561        cmd_type = PD_VDO_CMDT(p[0]);
1562        cmd = PD_VDO_CMD(p[0]);
1563
1564        tcpm_log(port, "Rx VDM cmd 0x%x type %d cmd %d len %d",
1565                 p[0], cmd_type, cmd, cnt);
1566
1567        modep = &port->mode_data;
1568
1569        pdev = typec_match_altmode(port->partner_altmode, ALTMODE_DISCOVERY_MAX,
1570                                   PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1571
1572        svdm_version = typec_get_negotiated_svdm_version(typec);
1573        if (svdm_version < 0)
1574                return 0;
1575
1576        switch (cmd_type) {
1577        case CMDT_INIT:
1578                switch (cmd) {
1579                case CMD_DISCOVER_IDENT:
1580                        if (PD_VDO_VID(p[0]) != USB_SID_PD)
1581                                break;
1582
1583                        if (PD_VDO_SVDM_VER(p[0]) < svdm_version) {
1584                                typec_partner_set_svdm_version(port->partner,
1585                                                               PD_VDO_SVDM_VER(p[0]));
1586                                svdm_version = PD_VDO_SVDM_VER(p[0]);
1587                        }
1588
1589                        port->ams = DISCOVER_IDENTITY;
1590                        /*
1591                         * PD2.0 Spec 6.10.3: respond with NAK as DFP (data host)
1592                         * PD3.1 Spec 6.4.4.2.5.1: respond with NAK if "invalid field" or
1593                         * "wrong configuation" or "Unrecognized"
1594                         */
1595                        if ((port->data_role == TYPEC_DEVICE || svdm_version >= SVDM_VER_2_0) &&
1596                            port->nr_snk_vdo) {
1597                                if (svdm_version < SVDM_VER_2_0) {
1598                                        for (i = 0; i < port->nr_snk_vdo_v1; i++)
1599                                                response[i + 1] = port->snk_vdo_v1[i];
1600                                        rlen = port->nr_snk_vdo_v1 + 1;
1601
1602                                } else {
1603                                        for (i = 0; i < port->nr_snk_vdo; i++)
1604                                                response[i + 1] = port->snk_vdo[i];
1605                                        rlen = port->nr_snk_vdo + 1;
1606                                }
1607                        }
1608                        break;
1609                case CMD_DISCOVER_SVID:
1610                        port->ams = DISCOVER_SVIDS;
1611                        break;
1612                case CMD_DISCOVER_MODES:
1613                        port->ams = DISCOVER_MODES;
1614                        break;
1615                case CMD_ENTER_MODE:
1616                        port->ams = DFP_TO_UFP_ENTER_MODE;
1617                        break;
1618                case CMD_EXIT_MODE:
1619                        port->ams = DFP_TO_UFP_EXIT_MODE;
1620                        break;
1621                case CMD_ATTENTION:
1622                        /* Attention command does not have response */
1623                        *adev_action = ADEV_ATTENTION;
1624                        return 0;
1625                default:
1626                        break;
1627                }
1628                if (rlen >= 1) {
1629                        response[0] = p[0] | VDO_CMDT(CMDT_RSP_ACK);
1630                } else if (rlen == 0) {
1631                        response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1632                        rlen = 1;
1633                } else {
1634                        response[0] = p[0] | VDO_CMDT(CMDT_RSP_BUSY);
1635                        rlen = 1;
1636                }
1637                response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
1638                              (VDO_SVDM_VERS(typec_get_negotiated_svdm_version(typec)));
1639                break;
1640        case CMDT_RSP_ACK:
1641                /* silently drop message if we are not connected */
1642                if (IS_ERR_OR_NULL(port->partner))
1643                        break;
1644
1645                tcpm_ams_finish(port);
1646
1647                switch (cmd) {
1648                case CMD_DISCOVER_IDENT:
1649                        if (PD_VDO_SVDM_VER(p[0]) < svdm_version)
1650                                typec_partner_set_svdm_version(port->partner,
1651                                                               PD_VDO_SVDM_VER(p[0]));
1652                        /* 6.4.4.3.1 */
1653                        svdm_consume_identity(port, p, cnt);
1654                        response[0] = VDO(USB_SID_PD, 1, typec_get_negotiated_svdm_version(typec),
1655                                          CMD_DISCOVER_SVID);
1656                        rlen = 1;
1657                        break;
1658                case CMD_DISCOVER_SVID:
1659                        /* 6.4.4.3.2 */
1660                        if (svdm_consume_svids(port, p, cnt)) {
1661                                response[0] = VDO(USB_SID_PD, 1, svdm_version, CMD_DISCOVER_SVID);
1662                                rlen = 1;
1663                        } else if (modep->nsvids && supports_modal(port)) {
1664                                response[0] = VDO(modep->svids[0], 1, svdm_version,
1665                                                  CMD_DISCOVER_MODES);
1666                                rlen = 1;
1667                        }
1668                        break;
1669                case CMD_DISCOVER_MODES:
1670                        /* 6.4.4.3.3 */
1671                        svdm_consume_modes(port, p, cnt);
1672                        modep->svid_index++;
1673                        if (modep->svid_index < modep->nsvids) {
1674                                u16 svid = modep->svids[modep->svid_index];
1675                                response[0] = VDO(svid, 1, svdm_version, CMD_DISCOVER_MODES);
1676                                rlen = 1;
1677                        } else {
1678                                tcpm_register_partner_altmodes(port);
1679                        }
1680                        break;
1681                case CMD_ENTER_MODE:
1682                        if (adev && pdev) {
1683                                typec_altmode_update_active(pdev, true);
1684                                *adev_action = ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL;
1685                        }
1686                        return 0;
1687                case CMD_EXIT_MODE:
1688                        if (adev && pdev) {
1689                                typec_altmode_update_active(pdev, false);
1690                                /* Back to USB Operation */
1691                                *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
1692                                return 0;
1693                        }
1694                        break;
1695                case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
1696                        break;
1697                default:
1698                        /* Unrecognized SVDM */
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                        break;
1704                }
1705                break;
1706        case CMDT_RSP_NAK:
1707                tcpm_ams_finish(port);
1708                switch (cmd) {
1709                case CMD_DISCOVER_IDENT:
1710                case CMD_DISCOVER_SVID:
1711                case CMD_DISCOVER_MODES:
1712                case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
1713                        break;
1714                case CMD_ENTER_MODE:
1715                        /* Back to USB Operation */
1716                        *adev_action = ADEV_NOTIFY_USB_AND_QUEUE_VDM;
1717                        return 0;
1718                default:
1719                        /* Unrecognized SVDM */
1720                        response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1721                        rlen = 1;
1722                        response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
1723                                      (VDO_SVDM_VERS(svdm_version));
1724                        break;
1725                }
1726                break;
1727        default:
1728                response[0] = p[0] | VDO_CMDT(CMDT_RSP_NAK);
1729                rlen = 1;
1730                response[0] = (response[0] & ~VDO_SVDM_VERS_MASK) |
1731                              (VDO_SVDM_VERS(svdm_version));
1732                break;
1733        }
1734
1735        /* Informing the alternate mode drivers about everything */
1736        *adev_action = ADEV_QUEUE_VDM;
1737        return rlen;
1738}
1739
1740static void tcpm_pd_handle_msg(struct tcpm_port *port,
1741                               enum pd_msg_request message,
1742                               enum tcpm_ams ams);
1743
1744static void tcpm_handle_vdm_request(struct tcpm_port *port,
1745                                    const __le32 *payload, int cnt)
1746{
1747        enum adev_actions adev_action = ADEV_NONE;
1748        struct typec_altmode *adev;
1749        u32 p[PD_MAX_PAYLOAD];
1750        u32 response[8] = { };
1751        int i, rlen = 0;
1752
1753        for (i = 0; i < cnt; i++)
1754                p[i] = le32_to_cpu(payload[i]);
1755
1756        adev = typec_match_altmode(port->port_altmode, ALTMODE_DISCOVERY_MAX,
1757                                   PD_VDO_VID(p[0]), PD_VDO_OPOS(p[0]));
1758
1759        if (port->vdm_state == VDM_STATE_BUSY) {
1760                /* If UFP responded busy retry after timeout */
1761                if (PD_VDO_CMDT(p[0]) == CMDT_RSP_BUSY) {
1762                        port->vdm_state = VDM_STATE_WAIT_RSP_BUSY;
1763                        port->vdo_retry = (p[0] & ~VDO_CMDT_MASK) |
1764                                CMDT_INIT;
1765                        mod_vdm_delayed_work(port, PD_T_VDM_BUSY);
1766                        return;
1767                }
1768                port->vdm_state = VDM_STATE_DONE;
1769        }
1770
1771        if (PD_VDO_SVDM(p[0]) && (adev || tcpm_vdm_ams(port) || port->nr_snk_vdo)) {
1772                /*
1773                 * Here a SVDM is received (INIT or RSP or unknown). Set the vdm_sm_running in
1774                 * advance because we are dropping the lock but may send VDMs soon.
1775                 * For the cases of INIT received:
1776                 *  - If no response to send, it will be cleared later in this function.
1777                 *  - If there are responses to send, it will be cleared in the state machine.
1778                 * For the cases of RSP received:
1779                 *  - If no further INIT to send, it will be cleared later in this function.
1780                 *  - Otherwise, it will be cleared in the state machine if timeout or it will go
1781                 *    back here until no further INIT to send.
1782                 * For the cases of unknown type received:
1783                 *  - We will send NAK and the flag will be cleared in the state machine.
1784                 */
1785                port->vdm_sm_running = true;
1786                rlen = tcpm_pd_svdm(port, adev, p, cnt, response, &adev_action);
1787        } else {
1788                if (port->negotiated_rev >= PD_REV30)
1789                        tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
1790        }
1791
1792        /*
1793         * We are done with any state stored in the port struct now, except
1794         * for any port struct changes done by the tcpm_queue_vdm() call
1795         * below, which is a separate operation.
1796         *
1797         * So we can safely release the lock here; and we MUST release the
1798         * lock here to avoid an AB BA lock inversion:
1799         *
1800         * If we keep the lock here then the lock ordering in this path is:
1801         * 1. tcpm_pd_rx_handler take the tcpm port lock
1802         * 2. One of the typec_altmode_* calls below takes the alt-mode's lock
1803         *
1804         * And we also have this ordering:
1805         * 1. alt-mode driver takes the alt-mode's lock
1806         * 2. alt-mode driver calls tcpm_altmode_enter which takes the
1807         *    tcpm port lock
1808         *
1809         * Dropping our lock here avoids this.
1810         */
1811        mutex_unlock(&port->lock);
1812
1813        if (adev) {
1814                switch (adev_action) {
1815                case ADEV_NONE:
1816                        break;
1817                case ADEV_NOTIFY_USB_AND_QUEUE_VDM:
1818                        WARN_ON(typec_altmode_notify(adev, TYPEC_STATE_USB, NULL));
1819                        typec_altmode_vdm(adev, p[0], &p[1], cnt);
1820                        break;
1821                case ADEV_QUEUE_VDM:
1822                        typec_altmode_vdm(adev, p[0], &p[1], cnt);
1823                        break;
1824                case ADEV_QUEUE_VDM_SEND_EXIT_MODE_ON_FAIL:
1825                        if (typec_altmode_vdm(adev, p[0], &p[1], cnt)) {
1826                                int svdm_version = typec_get_negotiated_svdm_version(
1827                                                                        port->typec_port);
1828                                if (svdm_version < 0)
1829                                        break;
1830
1831                                response[0] = VDO(adev->svid, 1, svdm_version,
1832                                                  CMD_EXIT_MODE);
1833                                response[0] |= VDO_OPOS(adev->mode);
1834                                rlen = 1;
1835                        }
1836                        break;
1837                case ADEV_ATTENTION:
1838                        typec_altmode_attention(adev, p[1]);
1839                        break;
1840                }
1841        }
1842
1843        /*
1844         * We must re-take the lock here to balance the unlock in
1845         * tcpm_pd_rx_handler, note that no changes, other then the
1846         * tcpm_queue_vdm call, are made while the lock is held again.
1847         * All that is done after the call is unwinding the call stack until
1848         * we return to tcpm_pd_rx_handler and do the unlock there.
1849         */
1850        mutex_lock(&port->lock);
1851
1852        if (rlen > 0)
1853                tcpm_queue_vdm(port, response[0], &response[1], rlen - 1);
1854        else
1855                port->vdm_sm_running = false;
1856}
1857
1858static void tcpm_send_vdm(struct tcpm_port *port, u32 vid, int cmd,
1859                          const u32 *data, int count)
1860{
1861        int svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
1862        u32 header;
1863
1864        if (svdm_version < 0)
1865                return;
1866
1867        if (WARN_ON(count > VDO_MAX_SIZE - 1))
1868                count = VDO_MAX_SIZE - 1;
1869
1870        /* set VDM header with VID & CMD */
1871        header = VDO(vid, ((vid & USB_SID_PD) == USB_SID_PD) ?
1872                        1 : (PD_VDO_CMD(cmd) <= CMD_ATTENTION),
1873                        svdm_version, cmd);
1874        tcpm_queue_vdm(port, header, data, count);
1875}
1876
1877static unsigned int vdm_ready_timeout(u32 vdm_hdr)
1878{
1879        unsigned int timeout;
1880        int cmd = PD_VDO_CMD(vdm_hdr);
1881
1882        /* its not a structured VDM command */
1883        if (!PD_VDO_SVDM(vdm_hdr))
1884                return PD_T_VDM_UNSTRUCTURED;
1885
1886        switch (PD_VDO_CMDT(vdm_hdr)) {
1887        case CMDT_INIT:
1888                if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1889                        timeout = PD_T_VDM_WAIT_MODE_E;
1890                else
1891                        timeout = PD_T_VDM_SNDR_RSP;
1892                break;
1893        default:
1894                if (cmd == CMD_ENTER_MODE || cmd == CMD_EXIT_MODE)
1895                        timeout = PD_T_VDM_E_MODE;
1896                else
1897                        timeout = PD_T_VDM_RCVR_RSP;
1898                break;
1899        }
1900        return timeout;
1901}
1902
1903static void vdm_run_state_machine(struct tcpm_port *port)
1904{
1905        struct pd_message msg;
1906        int i, res = 0;
1907        u32 vdo_hdr = port->vdo_data[0];
1908
1909        switch (port->vdm_state) {
1910        case VDM_STATE_READY:
1911                /* Only transmit VDM if attached */
1912                if (!port->attached) {
1913                        port->vdm_state = VDM_STATE_ERR_BUSY;
1914                        break;
1915                }
1916
1917                /*
1918                 * if there's traffic or we're not in PDO ready state don't send
1919                 * a VDM.
1920                 */
1921                if (port->state != SRC_READY && port->state != SNK_READY) {
1922                        port->vdm_sm_running = false;
1923                        break;
1924                }
1925
1926                /* TODO: AMS operation for Unstructured VDM */
1927                if (PD_VDO_SVDM(vdo_hdr) && PD_VDO_CMDT(vdo_hdr) == CMDT_INIT) {
1928                        switch (PD_VDO_CMD(vdo_hdr)) {
1929                        case CMD_DISCOVER_IDENT:
1930                                res = tcpm_ams_start(port, DISCOVER_IDENTITY);
1931                                if (res == 0)
1932                                        port->send_discover = false;
1933                                else if (res == -EAGAIN)
1934                                        mod_send_discover_delayed_work(port,
1935                                                                       SEND_DISCOVER_RETRY_MS);
1936                                break;
1937                        case CMD_DISCOVER_SVID:
1938                                res = tcpm_ams_start(port, DISCOVER_SVIDS);
1939                                break;
1940                        case CMD_DISCOVER_MODES:
1941                                res = tcpm_ams_start(port, DISCOVER_MODES);
1942                                break;
1943                        case CMD_ENTER_MODE:
1944                                res = tcpm_ams_start(port, DFP_TO_UFP_ENTER_MODE);
1945                                break;
1946                        case CMD_EXIT_MODE:
1947                                res = tcpm_ams_start(port, DFP_TO_UFP_EXIT_MODE);
1948                                break;
1949                        case CMD_ATTENTION:
1950                                res = tcpm_ams_start(port, ATTENTION);
1951                                break;
1952                        case VDO_CMD_VENDOR(0) ... VDO_CMD_VENDOR(15):
1953                                res = tcpm_ams_start(port, STRUCTURED_VDMS);
1954                                break;
1955                        default:
1956                                res = -EOPNOTSUPP;
1957                                break;
1958                        }
1959
1960                        if (res < 0) {
1961                                port->vdm_state = VDM_STATE_ERR_BUSY;
1962                                return;
1963                        }
1964                }
1965
1966                port->vdm_state = VDM_STATE_SEND_MESSAGE;
1967                mod_vdm_delayed_work(port, (port->negotiated_rev >= PD_REV30 &&
1968                                            port->pwr_role == TYPEC_SOURCE &&
1969                                            PD_VDO_SVDM(vdo_hdr) &&
1970                                            PD_VDO_CMDT(vdo_hdr) == CMDT_INIT) ?
1971                                           PD_T_SINK_TX : 0);
1972                break;
1973        case VDM_STATE_WAIT_RSP_BUSY:
1974                port->vdo_data[0] = port->vdo_retry;
1975                port->vdo_count = 1;
1976                port->vdm_state = VDM_STATE_READY;
1977                tcpm_ams_finish(port);
1978                break;
1979        case VDM_STATE_BUSY:
1980                port->vdm_state = VDM_STATE_ERR_TMOUT;
1981                if (port->ams != NONE_AMS)
1982                        tcpm_ams_finish(port);
1983                break;
1984        case VDM_STATE_ERR_SEND:
1985                /*
1986                 * A partner which does not support USB PD will not reply,
1987                 * so this is not a fatal error. At the same time, some
1988                 * devices may not return GoodCRC under some circumstances,
1989                 * so we need to retry.
1990                 */
1991                if (port->vdm_retries < 3) {
1992                        tcpm_log(port, "VDM Tx error, retry");
1993                        port->vdm_retries++;
1994                        port->vdm_state = VDM_STATE_READY;
1995                        if (PD_VDO_SVDM(vdo_hdr) && PD_VDO_CMDT(vdo_hdr) == CMDT_INIT)
1996                                tcpm_ams_finish(port);
1997                } else {
1998                        tcpm_ams_finish(port);
1999                }
2000                break;
2001        case VDM_STATE_SEND_MESSAGE:
2002                /* Prepare and send VDM */
2003                memset(&msg, 0, sizeof(msg));
2004                msg.header = PD_HEADER_LE(PD_DATA_VENDOR_DEF,
2005                                          port->pwr_role,
2006                                          port->data_role,
2007                                          port->negotiated_rev,
2008                                          port->message_id, port->vdo_count);
2009                for (i = 0; i < port->vdo_count; i++)
2010                        msg.payload[i] = cpu_to_le32(port->vdo_data[i]);
2011                res = tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2012                if (res < 0) {
2013                        port->vdm_state = VDM_STATE_ERR_SEND;
2014                } else {
2015                        unsigned long timeout;
2016
2017                        port->vdm_retries = 0;
2018                        port->vdm_state = VDM_STATE_BUSY;
2019                        timeout = vdm_ready_timeout(vdo_hdr);
2020                        mod_vdm_delayed_work(port, timeout);
2021                }
2022                break;
2023        default:
2024                break;
2025        }
2026}
2027
2028static void vdm_state_machine_work(struct kthread_work *work)
2029{
2030        struct tcpm_port *port = container_of(work, struct tcpm_port, vdm_state_machine);
2031        enum vdm_states prev_state;
2032
2033        mutex_lock(&port->lock);
2034
2035        /*
2036         * Continue running as long as the port is not busy and there was
2037         * a state change.
2038         */
2039        do {
2040                prev_state = port->vdm_state;
2041                vdm_run_state_machine(port);
2042        } while (port->vdm_state != prev_state &&
2043                 port->vdm_state != VDM_STATE_BUSY &&
2044                 port->vdm_state != VDM_STATE_SEND_MESSAGE);
2045
2046        if (port->vdm_state < VDM_STATE_READY)
2047                port->vdm_sm_running = false;
2048
2049        mutex_unlock(&port->lock);
2050}
2051
2052enum pdo_err {
2053        PDO_NO_ERR,
2054        PDO_ERR_NO_VSAFE5V,
2055        PDO_ERR_VSAFE5V_NOT_FIRST,
2056        PDO_ERR_PDO_TYPE_NOT_IN_ORDER,
2057        PDO_ERR_FIXED_NOT_SORTED,
2058        PDO_ERR_VARIABLE_BATT_NOT_SORTED,
2059        PDO_ERR_DUPE_PDO,
2060        PDO_ERR_PPS_APDO_NOT_SORTED,
2061        PDO_ERR_DUPE_PPS_APDO,
2062};
2063
2064static const char * const pdo_err_msg[] = {
2065        [PDO_ERR_NO_VSAFE5V] =
2066        " err: source/sink caps should atleast have vSafe5V",
2067        [PDO_ERR_VSAFE5V_NOT_FIRST] =
2068        " err: vSafe5V Fixed Supply Object Shall always be the first object",
2069        [PDO_ERR_PDO_TYPE_NOT_IN_ORDER] =
2070        " err: PDOs should be in the following order: Fixed; Battery; Variable",
2071        [PDO_ERR_FIXED_NOT_SORTED] =
2072        " err: Fixed supply pdos should be in increasing order of their fixed voltage",
2073        [PDO_ERR_VARIABLE_BATT_NOT_SORTED] =
2074        " err: Variable/Battery supply pdos should be in increasing order of their minimum voltage",
2075        [PDO_ERR_DUPE_PDO] =
2076        " err: Variable/Batt supply pdos cannot have same min/max voltage",
2077        [PDO_ERR_PPS_APDO_NOT_SORTED] =
2078        " err: Programmable power supply apdos should be in increasing order of their maximum voltage",
2079        [PDO_ERR_DUPE_PPS_APDO] =
2080        " err: Programmable power supply apdos cannot have same min/max voltage and max current",
2081};
2082
2083static enum pdo_err tcpm_caps_err(struct tcpm_port *port, const u32 *pdo,
2084                                  unsigned int nr_pdo)
2085{
2086        unsigned int i;
2087
2088        /* Should at least contain vSafe5v */
2089        if (nr_pdo < 1)
2090                return PDO_ERR_NO_VSAFE5V;
2091
2092        /* The vSafe5V Fixed Supply Object Shall always be the first object */
2093        if (pdo_type(pdo[0]) != PDO_TYPE_FIXED ||
2094            pdo_fixed_voltage(pdo[0]) != VSAFE5V)
2095                return PDO_ERR_VSAFE5V_NOT_FIRST;
2096
2097        for (i = 1; i < nr_pdo; i++) {
2098                if (pdo_type(pdo[i]) < pdo_type(pdo[i - 1])) {
2099                        return PDO_ERR_PDO_TYPE_NOT_IN_ORDER;
2100                } else if (pdo_type(pdo[i]) == pdo_type(pdo[i - 1])) {
2101                        enum pd_pdo_type type = pdo_type(pdo[i]);
2102
2103                        switch (type) {
2104                        /*
2105                         * The remaining Fixed Supply Objects, if
2106                         * present, shall be sent in voltage order;
2107                         * lowest to highest.
2108                         */
2109                        case PDO_TYPE_FIXED:
2110                                if (pdo_fixed_voltage(pdo[i]) <=
2111                                    pdo_fixed_voltage(pdo[i - 1]))
2112                                        return PDO_ERR_FIXED_NOT_SORTED;
2113                                break;
2114                        /*
2115                         * The Battery Supply Objects and Variable
2116                         * supply, if present shall be sent in Minimum
2117                         * Voltage order; lowest to highest.
2118                         */
2119                        case PDO_TYPE_VAR:
2120                        case PDO_TYPE_BATT:
2121                                if (pdo_min_voltage(pdo[i]) <
2122                                    pdo_min_voltage(pdo[i - 1]))
2123                                        return PDO_ERR_VARIABLE_BATT_NOT_SORTED;
2124                                else if ((pdo_min_voltage(pdo[i]) ==
2125                                          pdo_min_voltage(pdo[i - 1])) &&
2126                                         (pdo_max_voltage(pdo[i]) ==
2127                                          pdo_max_voltage(pdo[i - 1])))
2128                                        return PDO_ERR_DUPE_PDO;
2129                                break;
2130                        /*
2131                         * The Programmable Power Supply APDOs, if present,
2132                         * shall be sent in Maximum Voltage order;
2133                         * lowest to highest.
2134                         */
2135                        case PDO_TYPE_APDO:
2136                                if (pdo_apdo_type(pdo[i]) != APDO_TYPE_PPS)
2137                                        break;
2138
2139                                if (pdo_pps_apdo_max_voltage(pdo[i]) <
2140                                    pdo_pps_apdo_max_voltage(pdo[i - 1]))
2141                                        return PDO_ERR_PPS_APDO_NOT_SORTED;
2142                                else if (pdo_pps_apdo_min_voltage(pdo[i]) ==
2143                                          pdo_pps_apdo_min_voltage(pdo[i - 1]) &&
2144                                         pdo_pps_apdo_max_voltage(pdo[i]) ==
2145                                          pdo_pps_apdo_max_voltage(pdo[i - 1]) &&
2146                                         pdo_pps_apdo_max_current(pdo[i]) ==
2147                                          pdo_pps_apdo_max_current(pdo[i - 1]))
2148                                        return PDO_ERR_DUPE_PPS_APDO;
2149                                break;
2150                        default:
2151                                tcpm_log_force(port, " Unknown pdo type");
2152                        }
2153                }
2154        }
2155
2156        return PDO_NO_ERR;
2157}
2158
2159static int tcpm_validate_caps(struct tcpm_port *port, const u32 *pdo,
2160                              unsigned int nr_pdo)
2161{
2162        enum pdo_err err_index = tcpm_caps_err(port, pdo, nr_pdo);
2163
2164        if (err_index != PDO_NO_ERR) {
2165                tcpm_log_force(port, " %s", pdo_err_msg[err_index]);
2166                return -EINVAL;
2167        }
2168
2169        return 0;
2170}
2171
2172static int tcpm_altmode_enter(struct typec_altmode *altmode, u32 *vdo)
2173{
2174        struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2175        int svdm_version;
2176        u32 header;
2177
2178        svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2179        if (svdm_version < 0)
2180                return svdm_version;
2181
2182        header = VDO(altmode->svid, vdo ? 2 : 1, svdm_version, CMD_ENTER_MODE);
2183        header |= VDO_OPOS(altmode->mode);
2184
2185        tcpm_queue_vdm_unlocked(port, header, vdo, vdo ? 1 : 0);
2186        return 0;
2187}
2188
2189static int tcpm_altmode_exit(struct typec_altmode *altmode)
2190{
2191        struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2192        int svdm_version;
2193        u32 header;
2194
2195        svdm_version = typec_get_negotiated_svdm_version(port->typec_port);
2196        if (svdm_version < 0)
2197                return svdm_version;
2198
2199        header = VDO(altmode->svid, 1, svdm_version, CMD_EXIT_MODE);
2200        header |= VDO_OPOS(altmode->mode);
2201
2202        tcpm_queue_vdm_unlocked(port, header, NULL, 0);
2203        return 0;
2204}
2205
2206static int tcpm_altmode_vdm(struct typec_altmode *altmode,
2207                            u32 header, const u32 *data, int count)
2208{
2209        struct tcpm_port *port = typec_altmode_get_drvdata(altmode);
2210
2211        tcpm_queue_vdm_unlocked(port, header, data, count - 1);
2212
2213        return 0;
2214}
2215
2216static const struct typec_altmode_ops tcpm_altmode_ops = {
2217        .enter = tcpm_altmode_enter,
2218        .exit = tcpm_altmode_exit,
2219        .vdm = tcpm_altmode_vdm,
2220};
2221
2222/*
2223 * PD (data, control) command handling functions
2224 */
2225static inline enum tcpm_state ready_state(struct tcpm_port *port)
2226{
2227        if (port->pwr_role == TYPEC_SOURCE)
2228                return SRC_READY;
2229        else
2230                return SNK_READY;
2231}
2232
2233static int tcpm_pd_send_control(struct tcpm_port *port,
2234                                enum pd_ctrl_msg_type type);
2235
2236static void tcpm_handle_alert(struct tcpm_port *port, const __le32 *payload,
2237                              int cnt)
2238{
2239        u32 p0 = le32_to_cpu(payload[0]);
2240        unsigned int type = usb_pd_ado_type(p0);
2241
2242        if (!type) {
2243                tcpm_log(port, "Alert message received with no type");
2244                tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2245                return;
2246        }
2247
2248        /* Just handling non-battery alerts for now */
2249        if (!(type & USB_PD_ADO_TYPE_BATT_STATUS_CHANGE)) {
2250                if (port->pwr_role == TYPEC_SOURCE) {
2251                        port->upcoming_state = GET_STATUS_SEND;
2252                        tcpm_ams_start(port, GETTING_SOURCE_SINK_STATUS);
2253                } else {
2254                        /*
2255                         * Do not check SinkTxOk here in case the Source doesn't set its Rp to
2256                         * SinkTxOk in time.
2257                         */
2258                        port->ams = GETTING_SOURCE_SINK_STATUS;
2259                        tcpm_set_state(port, GET_STATUS_SEND, 0);
2260                }
2261        } else {
2262                tcpm_queue_message(port, PD_MSG_CTRL_NOT_SUPP);
2263        }
2264}
2265
2266static int tcpm_set_auto_vbus_discharge_threshold(struct tcpm_port *port,
2267                                                  enum typec_pwr_opmode mode, bool pps_active,
2268                                                  u32 requested_vbus_voltage)
2269{
2270        int ret;
2271
2272        if (!port->tcpc->set_auto_vbus_discharge_threshold)
2273                return 0;
2274
2275        ret = port->tcpc->set_auto_vbus_discharge_threshold(port->tcpc, mode, pps_active,
2276                                                            requested_vbus_voltage);
2277        tcpm_log_force(port,
2278                       "set_auto_vbus_discharge_threshold mode:%d pps_active:%c vbus:%u ret:%d",
2279                       mode, pps_active ? 'y' : 'n', requested_vbus_voltage, ret);
2280
2281        return ret;
2282}
2283
2284static void tcpm_pd_handle_state(struct tcpm_port *port,
2285                                 enum tcpm_state state,
2286                                 enum tcpm_ams ams,
2287                                 unsigned int delay_ms)
2288{
2289        switch (port->state) {
2290        case SRC_READY:
2291        case SNK_READY:
2292                port->ams = ams;
2293                tcpm_set_state(port, state, delay_ms);
2294                break;
2295        /* 8.3.3.4.1.1 and 6.8.1 power transitioning */
2296        case SNK_TRANSITION_SINK:
2297        case SNK_TRANSITION_SINK_VBUS:
2298        case SRC_TRANSITION_SUPPLY:
2299                tcpm_set_state(port, HARD_RESET_SEND, 0);
2300                break;
2301        default:
2302                if (!tcpm_ams_interruptible(port)) {
2303                        tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
2304                                       SRC_SOFT_RESET_WAIT_SNK_TX :
2305                                       SNK_SOFT_RESET,
2306                                       0);
2307                } else {
2308                        /* process the Message 6.8.1 */
2309                        port->upcoming_state = state;
2310                        port->next_ams = ams;
2311                        tcpm_set_state(port, ready_state(port), delay_ms);
2312                }
2313                break;
2314        }
2315}
2316
2317static void tcpm_pd_handle_msg(struct tcpm_port *port,
2318                               enum pd_msg_request message,
2319                               enum tcpm_ams ams)
2320{
2321        switch (port->state) {
2322        case SRC_READY:
2323        case SNK_READY:
2324                port->ams = ams;
2325                tcpm_queue_message(port, message);
2326                break;
2327        /* PD 3.0 Spec 8.3.3.4.1.1 and 6.8.1 */
2328        case SNK_TRANSITION_SINK:
2329        case SNK_TRANSITION_SINK_VBUS:
2330        case SRC_TRANSITION_SUPPLY:
2331                tcpm_set_state(port, HARD_RESET_SEND, 0);
2332                break;
2333        default:
2334                if (!tcpm_ams_interruptible(port)) {
2335                        tcpm_set_state(port, port->pwr_role == TYPEC_SOURCE ?
2336                                       SRC_SOFT_RESET_WAIT_SNK_TX :
2337                                       SNK_SOFT_RESET,
2338                                       0);
2339                } else {
2340                        port->next_ams = ams;
2341                        tcpm_set_state(port, ready_state(port), 0);
2342                        /* 6.8.1 process the Message */
2343                        tcpm_queue_message(port, message);
2344                }
2345                break;
2346        }
2347}
2348
2349static void tcpm_pd_data_request(struct tcpm_port *port,
2350                                 const struct pd_message *msg)
2351{
2352        enum pd_data_msg_type type = pd_header_type_le(msg->header);
2353        unsigned int cnt = pd_header_cnt_le(msg->header);
2354        unsigned int rev = pd_header_rev_le(msg->header);
2355        unsigned int i;
2356        enum frs_typec_current partner_frs_current;
2357        bool frs_enable;
2358        int ret;
2359
2360        if (tcpm_vdm_ams(port) && type != PD_DATA_VENDOR_DEF) {
2361                port->vdm_state = VDM_STATE_ERR_BUSY;
2362                tcpm_ams_finish(port);
2363                mod_vdm_delayed_work(port, 0);
2364        }
2365
2366        switch (type) {
2367        case PD_DATA_SOURCE_CAP:
2368                for (i = 0; i < cnt; i++)
2369                        port->source_caps[i] = le32_to_cpu(msg->payload[i]);
2370
2371                port->nr_source_caps = cnt;
2372
2373                tcpm_log_source_caps(port);
2374
2375                tcpm_validate_caps(port, port->source_caps,
2376                                   port->nr_source_caps);
2377
2378                /*
2379                 * Adjust revision in subsequent message headers, as required,
2380                 * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
2381                 * support Rev 1.0 so just do nothing in that scenario.
2382                 */
2383                if (rev == PD_REV10) {
2384                        if (port->ams == GET_SOURCE_CAPABILITIES)
2385                                tcpm_ams_finish(port);
2386                        break;
2387                }
2388
2389                if (rev < PD_MAX_REV)
2390                        port->negotiated_rev = rev;
2391
2392                if (port->pwr_role == TYPEC_SOURCE) {
2393                        if (port->ams == GET_SOURCE_CAPABILITIES)
2394                                tcpm_pd_handle_state(port, SRC_READY, NONE_AMS, 0);
2395                        /* Unexpected Source Capabilities */
2396                        else
2397                                tcpm_pd_handle_msg(port,
2398                                                   port->negotiated_rev < PD_REV30 ?
2399                                                   PD_MSG_CTRL_REJECT :
2400                                                   PD_MSG_CTRL_NOT_SUPP,
2401                                                   NONE_AMS);
2402                } else if (port->state == SNK_WAIT_CAPABILITIES) {
2403                /*
2404                 * This message may be received even if VBUS is not
2405                 * present. This is quite unexpected; see USB PD
2406                 * specification, sections 8.3.3.6.3.1 and 8.3.3.6.3.2.
2407                 * However, at the same time, we must be ready to
2408                 * receive this message and respond to it 15ms after
2409                 * receiving PS_RDY during power swap operations, no matter
2410                 * if VBUS is available or not (USB PD specification,
2411                 * section 6.5.9.2).
2412                 * So we need to accept the message either way,
2413                 * but be prepared to keep waiting for VBUS after it was
2414                 * handled.
2415                 */
2416                        port->ams = POWER_NEGOTIATION;
2417                        port->in_ams = true;
2418                        tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
2419                } else {
2420                        if (port->ams == GET_SOURCE_CAPABILITIES)
2421                                tcpm_ams_finish(port);
2422                        tcpm_pd_handle_state(port, SNK_NEGOTIATE_CAPABILITIES,
2423                                             POWER_NEGOTIATION, 0);
2424                }
2425                break;
2426        case PD_DATA_REQUEST:
2427                /*
2428                 * Adjust revision in subsequent message headers, as required,
2429                 * to comply with 6.2.1.1.5 of the USB PD 3.0 spec. We don't
2430                 * support Rev 1.0 so just reject in that scenario.
2431                 */
2432                if (rev == PD_REV10) {
2433                        tcpm_pd_handle_msg(port,
2434                                           port->negotiated_rev < PD_REV30 ?
2435                                           PD_MSG_CTRL_REJECT :
2436                                           PD_MSG_CTRL_NOT_SUPP,
2437                                           NONE_AMS);
2438                        break;
2439                }
2440
2441                if (rev < PD_MAX_REV)
2442                        port->negotiated_rev = rev;
2443
2444                if (port->pwr_role != TYPEC_SOURCE || cnt != 1) {
2445                        tcpm_pd_handle_msg(port,
2446                                           port->negotiated_rev < PD_REV30 ?
2447                                           PD_MSG_CTRL_REJECT :
2448                                           PD_MSG_CTRL_NOT_SUPP,
2449                                           NONE_AMS);
2450                        break;
2451                }
2452
2453                port->sink_request = le32_to_cpu(msg->payload[0]);
2454
2455                if (port->vdm_sm_running && port->explicit_contract) {
2456                        tcpm_pd_handle_msg(port, PD_MSG_CTRL_WAIT, port->ams);
2457                        break;
2458                }
2459
2460                if (port->state == SRC_SEND_CAPABILITIES)
2461                        tcpm_set_state(port, SRC_NEGOTIATE_CAPABILITIES, 0);
2462                else
2463                        tcpm_pd_handle_state(port, SRC_NEGOTIATE_CAPABILITIES,
2464                                             POWER_NEGOTIATION, 0);
2465                break;
2466        case PD_DATA_SINK_CAP:
2467                /* We don't do anything with this at the moment... */
2468                for (i = 0; i < cnt; i++)
2469                        port->sink_caps[i] = le32_to_cpu(msg->payload[i]);
2470
2471                partner_frs_current = (port->sink_caps[0] & PDO_FIXED_FRS_CURR_MASK) >>
2472                        PDO_FIXED_FRS_CURR_SHIFT;
2473                frs_enable = partner_frs_current && (partner_frs_current <=
2474                                                     port->new_source_frs_current);
2475                tcpm_log(port,
2476                         "Port partner FRS capable partner_frs_current:%u port_frs_current:%u enable:%c",
2477                         partner_frs_current, port->new_source_frs_current, frs_enable ? 'y' : 'n');
2478                if (frs_enable) {
2479                        ret  = port->tcpc->enable_frs(port->tcpc, true);
2480                        tcpm_log(port, "Enable FRS %s, ret:%d\n", ret ? "fail" : "success", ret);
2481                }
2482
2483                port->nr_sink_caps = cnt;
2484                port->sink_cap_done = true;
2485                if (port->ams == GET_SINK_CAPABILITIES)
2486                        tcpm_set_state(port, ready_state(port), 0);
2487                /* Unexpected Sink Capabilities */
2488                else
2489                        tcpm_pd_handle_msg(port,
2490                                           port->negotiated_rev < PD_REV30 ?
2491                                           PD_MSG_CTRL_REJECT :
2492                                           PD_MSG_CTRL_NOT_SUPP,
2493                                           NONE_AMS);
2494                break;
2495        case PD_DATA_VENDOR_DEF:
2496                tcpm_handle_vdm_request(port, msg->payload, cnt);
2497                break;
2498        case PD_DATA_BIST:
2499                port->bist_request = le32_to_cpu(msg->payload[0]);
2500                tcpm_pd_handle_state(port, BIST_RX, BIST, 0);
2501                break;
2502        case PD_DATA_ALERT:
2503                if (port->state != SRC_READY && port->state != SNK_READY)
2504                        tcpm_pd_handle_state(port, port->pwr_role == TYPEC_SOURCE ?
2505                                             SRC_SOFT_RESET_WAIT_SNK_TX : SNK_SOFT_RESET,
2506                                             NONE_AMS, 0);
2507                else
2508                        tcpm_handle_alert(port, msg->payload, cnt);
2509                break;
2510        case PD_DATA_BATT_STATUS:
2511        case PD_DATA_GET_COUNTRY_INFO:
2512                /* Currently unsupported */
2513                tcpm_pd_handle_msg(port, port->negotiated_rev < PD_REV30 ?
2514                                   PD_MSG_CTRL_REJECT :
2515                                   PD_MSG_CTRL_NOT_SUPP,
2516                                   NONE_AMS);
2517                break;
2518        default:
2519                tcpm_pd_handle_msg(port, port->negotiated_rev < PD_REV30 ?
2520                                   PD_MSG_CTRL_REJECT :
2521                                   PD_MSG_CTRL_NOT_SUPP,
2522                                   NONE_AMS);
2523                tcpm_log(port, "Unrecognized data message type %#x", type);
2524                break;
2525        }
2526}
2527
2528static void tcpm_pps_complete(struct tcpm_port *port, int result)
2529{
2530        if (port->pps_pending) {
2531                port->pps_status = result;
2532                port->pps_pending = false;
2533                complete(&port->pps_complete);
2534        }
2535}
2536
2537static void tcpm_pd_ctrl_request(struct tcpm_port *port,
2538                                 const struct pd_message *msg)
2539{
2540        enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
2541        enum tcpm_state next_state;
2542
2543        /*
2544         * Stop VDM state machine if interrupted by other Messages while NOT_SUPP is allowed in
2545         * VDM AMS if waiting for VDM responses and will be handled later.
2546         */
2547        if (tcpm_vdm_ams(port) && type != PD_CTRL_NOT_SUPP && type != PD_CTRL_GOOD_CRC) {
2548                port->vdm_state = VDM_STATE_ERR_BUSY;
2549                tcpm_ams_finish(port);
2550                mod_vdm_delayed_work(port, 0);
2551        }
2552
2553        switch (type) {
2554        case PD_CTRL_GOOD_CRC:
2555        case PD_CTRL_PING:
2556                break;
2557        case PD_CTRL_GET_SOURCE_CAP:
2558                tcpm_pd_handle_msg(port, PD_MSG_DATA_SOURCE_CAP, GET_SOURCE_CAPABILITIES);
2559                break;
2560        case PD_CTRL_GET_SINK_CAP:
2561                tcpm_pd_handle_msg(port, PD_MSG_DATA_SINK_CAP, GET_SINK_CAPABILITIES);
2562                break;
2563        case PD_CTRL_GOTO_MIN:
2564                break;
2565        case PD_CTRL_PS_RDY:
2566                switch (port->state) {
2567                case SNK_TRANSITION_SINK:
2568                        if (port->vbus_present) {
2569                                tcpm_set_current_limit(port,
2570                                                       port->req_current_limit,
2571                                                       port->req_supply_voltage);
2572                                port->explicit_contract = true;
2573                                tcpm_set_auto_vbus_discharge_threshold(port,
2574                                                                       TYPEC_PWR_MODE_PD,
2575                                                                       port->pps_data.active,
2576                                                                       port->supply_voltage);
2577                                tcpm_set_state(port, SNK_READY, 0);
2578                        } else {
2579                                /*
2580                                 * Seen after power swap. Keep waiting for VBUS
2581                                 * in a transitional state.
2582                                 */
2583                                tcpm_set_state(port,
2584                                               SNK_TRANSITION_SINK_VBUS, 0);
2585                        }
2586                        break;
2587                case PR_SWAP_SRC_SNK_SOURCE_OFF_CC_DEBOUNCED:
2588                        tcpm_set_state(port, PR_SWAP_SRC_SNK_SINK_ON, 0);
2589                        break;
2590                case PR_SWAP_SNK_SRC_SINK_OFF:
2591                        tcpm_set_state(port, PR_SWAP_SNK_SRC_SOURCE_ON, 0);
2592                        break;
2593                case VCONN_SWAP_WAIT_FOR_VCONN:
2594                        tcpm_set_state(port, VCONN_SWAP_TURN_OFF_VCONN, 0);
2595                        break;
2596                case FR_SWAP_SNK_SRC_TRANSITION_TO_OFF:
2597                        tcpm_set_state(port, FR_SWAP_SNK_SRC_NEW_SINK_READY, 0);
2598                        break;
2599                default:
2600                        tcpm_pd_handle_state(port,
2601                                             port->pwr_role == TYPEC_SOURCE ?
2602                                             SRC_SOFT_RESET_WAIT_SNK_TX :
2603                                             SNK_SOFT_RESET,
2604                                             NONE_AMS, 0);
2605                        break;
2606                }
2607                break;
2608        case PD_CTRL_REJECT:
2609        case PD_CTRL_WAIT:
2610        case PD_CTRL_NOT_SUPP:
2611                switch (port->state) {
2612                case SNK_NEGOTIATE_CAPABILITIES:
2613                        /* USB PD specification, Figure 8-43 */
2614                        if (port->explicit_contract)
2615                                next_state = SNK_READY;
2616                        else
2617                                next_state = SNK_WAIT_CAPABILITIES;
2618
2619                        /* Threshold was relaxed before sending Request. Restore it back. */
2620                        tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
2621                                                               port->pps_data.active,
2622                                                               port->supply_voltage);
2623                        tcpm_set_state(port, next_state, 0);
2624                        break;
2625                case SNK_NEGOTIATE_PPS_CAPABILITIES:
2626                        /* Revert data back from any requested PPS updates */
2627                        port->pps_data.req_out_volt = port->supply_voltage;
2628                        port->pps_data.req_op_curr = port->current_limit;
2629                        port->pps_status = (type == PD_CTRL_WAIT ?
2630                                            -EAGAIN : -EOPNOTSUPP);
2631
2632                        /* Threshold was relaxed before sending Request. Restore it back. */
2633                        tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
2634                                                               port->pps_data.active,
2635                                                               port->supply_voltage);
2636
2637                        tcpm_set_state(port, SNK_READY, 0);
2638                        break;
2639                case DR_SWAP_SEND:
2640                        port->swap_status = (type == PD_CTRL_WAIT ?
2641                                             -EAGAIN : -EOPNOTSUPP);
2642                        tcpm_set_state(port, DR_SWAP_CANCEL, 0);
2643                        break;
2644                case PR_SWAP_SEND:
2645                        port->swap_status = (type == PD_CTRL_WAIT ?
2646                                             -EAGAIN : -EOPNOTSUPP);
2647                        tcpm_set_state(port, PR_SWAP_CANCEL, 0);
2648                        break;
2649                case VCONN_SWAP_SEND:
2650                        port->swap_status = (type == PD_CTRL_WAIT ?
2651                                             -EAGAIN : -EOPNOTSUPP);
2652                        tcpm_set_state(port, VCONN_SWAP_CANCEL, 0);
2653                        break;
2654                case FR_SWAP_SEND:
2655                        tcpm_set_state(port, FR_SWAP_CANCEL, 0);
2656                        break;
2657                case GET_SINK_CAP:
2658                        port->sink_cap_done = true;
2659                        tcpm_set_state(port, ready_state(port), 0);
2660                        break;
2661                case SRC_READY:
2662                case SNK_READY:
2663                        if (port->vdm_state > VDM_STATE_READY) {
2664                                port->vdm_state = VDM_STATE_DONE;
2665                                if (tcpm_vdm_ams(port))
2666                                        tcpm_ams_finish(port);
2667                                mod_vdm_delayed_work(port, 0);
2668                                break;
2669                        }
2670                        fallthrough;
2671                default:
2672                        tcpm_pd_handle_state(port,
2673                                             port->pwr_role == TYPEC_SOURCE ?
2674                                             SRC_SOFT_RESET_WAIT_SNK_TX :
2675                                             SNK_SOFT_RESET,
2676                                             NONE_AMS, 0);
2677                        break;
2678                }
2679                break;
2680        case PD_CTRL_ACCEPT:
2681                switch (port->state) {
2682                case SNK_NEGOTIATE_CAPABILITIES:
2683                        port->pps_data.active = false;
2684                        tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
2685                        break;
2686                case SNK_NEGOTIATE_PPS_CAPABILITIES:
2687                        port->pps_data.active = true;
2688                        port->pps_data.min_volt = port->pps_data.req_min_volt;
2689                        port->pps_data.max_volt = port->pps_data.req_max_volt;
2690                        port->pps_data.max_curr = port->pps_data.req_max_curr;
2691                        port->req_supply_voltage = port->pps_data.req_out_volt;
2692                        port->req_current_limit = port->pps_data.req_op_curr;
2693                        power_supply_changed(port->psy);
2694                        tcpm_set_state(port, SNK_TRANSITION_SINK, 0);
2695                        break;
2696                case SOFT_RESET_SEND:
2697                        if (port->ams == SOFT_RESET_AMS)
2698                                tcpm_ams_finish(port);
2699                        if (port->pwr_role == TYPEC_SOURCE) {
2700                                port->upcoming_state = SRC_SEND_CAPABILITIES;
2701                                tcpm_ams_start(port, POWER_NEGOTIATION);
2702                        } else {
2703                                tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
2704                        }
2705                        break;
2706                case DR_SWAP_SEND:
2707                        tcpm_set_state(port, DR_SWAP_CHANGE_DR, 0);
2708                        break;
2709                case PR_SWAP_SEND:
2710                        tcpm_set_state(port, PR_SWAP_START, 0);
2711                        break;
2712                case VCONN_SWAP_SEND:
2713                        tcpm_set_state(port, VCONN_SWAP_START, 0);
2714                        break;
2715                case FR_SWAP_SEND:
2716                        tcpm_set_state(port, FR_SWAP_SNK_SRC_TRANSITION_TO_OFF, 0);
2717                        break;
2718                default:
2719                        tcpm_pd_handle_state(port,
2720                                             port->pwr_role == TYPEC_SOURCE ?
2721                                             SRC_SOFT_RESET_WAIT_SNK_TX :
2722                                             SNK_SOFT_RESET,
2723                                             NONE_AMS, 0);
2724                        break;
2725                }
2726                break;
2727        case PD_CTRL_SOFT_RESET:
2728                port->ams = SOFT_RESET_AMS;
2729                tcpm_set_state(port, SOFT_RESET, 0);
2730                break;
2731        case PD_CTRL_DR_SWAP:
2732                /*
2733                 * XXX
2734                 * 6.3.9: If an alternate mode is active, a request to swap
2735                 * alternate modes shall trigger a port reset.
2736                 */
2737                if (port->typec_caps.data != TYPEC_PORT_DRD) {
2738                        tcpm_pd_handle_msg(port,
2739                                           port->negotiated_rev < PD_REV30 ?
2740                                           PD_MSG_CTRL_REJECT :
2741                                           PD_MSG_CTRL_NOT_SUPP,
2742                                           NONE_AMS);
2743                } else {
2744                        if (port->send_discover) {
2745                                tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2746                                break;
2747                        }
2748
2749                        tcpm_pd_handle_state(port, DR_SWAP_ACCEPT, DATA_ROLE_SWAP, 0);
2750                }
2751                break;
2752        case PD_CTRL_PR_SWAP:
2753                if (port->port_type != TYPEC_PORT_DRP) {
2754                        tcpm_pd_handle_msg(port,
2755                                           port->negotiated_rev < PD_REV30 ?
2756                                           PD_MSG_CTRL_REJECT :
2757                                           PD_MSG_CTRL_NOT_SUPP,
2758                                           NONE_AMS);
2759                } else {
2760                        if (port->send_discover) {
2761                                tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2762                                break;
2763                        }
2764
2765                        tcpm_pd_handle_state(port, PR_SWAP_ACCEPT, POWER_ROLE_SWAP, 0);
2766                }
2767                break;
2768        case PD_CTRL_VCONN_SWAP:
2769                if (port->send_discover) {
2770                        tcpm_queue_message(port, PD_MSG_CTRL_WAIT);
2771                        break;
2772                }
2773
2774                tcpm_pd_handle_state(port, VCONN_SWAP_ACCEPT, VCONN_SWAP, 0);
2775                break;
2776        case PD_CTRL_GET_SOURCE_CAP_EXT:
2777        case PD_CTRL_GET_STATUS:
2778        case PD_CTRL_FR_SWAP:
2779        case PD_CTRL_GET_PPS_STATUS:
2780        case PD_CTRL_GET_COUNTRY_CODES:
2781                /* Currently not supported */
2782                tcpm_pd_handle_msg(port,
2783                                   port->negotiated_rev < PD_REV30 ?
2784                                   PD_MSG_CTRL_REJECT :
2785                                   PD_MSG_CTRL_NOT_SUPP,
2786                                   NONE_AMS);
2787                break;
2788        default:
2789                tcpm_pd_handle_msg(port,
2790                                   port->negotiated_rev < PD_REV30 ?
2791                                   PD_MSG_CTRL_REJECT :
2792                                   PD_MSG_CTRL_NOT_SUPP,
2793                                   NONE_AMS);
2794                tcpm_log(port, "Unrecognized ctrl message type %#x", type);
2795                break;
2796        }
2797}
2798
2799static void tcpm_pd_ext_msg_request(struct tcpm_port *port,
2800                                    const struct pd_message *msg)
2801{
2802        enum pd_ext_msg_type type = pd_header_type_le(msg->header);
2803        unsigned int data_size = pd_ext_header_data_size_le(msg->ext_msg.header);
2804
2805        /* stopping VDM state machine if interrupted by other Messages */
2806        if (tcpm_vdm_ams(port)) {
2807                port->vdm_state = VDM_STATE_ERR_BUSY;
2808                tcpm_ams_finish(port);
2809                mod_vdm_delayed_work(port, 0);
2810        }
2811
2812        if (!(le16_to_cpu(msg->ext_msg.header) & PD_EXT_HDR_CHUNKED)) {
2813                tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
2814                tcpm_log(port, "Unchunked extended messages unsupported");
2815                return;
2816        }
2817
2818        if (data_size > PD_EXT_MAX_CHUNK_DATA) {
2819                tcpm_pd_handle_state(port, CHUNK_NOT_SUPP, NONE_AMS, PD_T_CHUNK_NOT_SUPP);
2820                tcpm_log(port, "Chunk handling not yet supported");
2821                return;
2822        }
2823
2824        switch (type) {
2825        case PD_EXT_STATUS:
2826        case PD_EXT_PPS_STATUS:
2827                if (port->ams == GETTING_SOURCE_SINK_STATUS) {
2828                        tcpm_ams_finish(port);
2829                        tcpm_set_state(port, ready_state(port), 0);
2830                } else {
2831                        /* unexpected Status or PPS_Status Message */
2832                        tcpm_pd_handle_state(port, port->pwr_role == TYPEC_SOURCE ?
2833                                             SRC_SOFT_RESET_WAIT_SNK_TX : SNK_SOFT_RESET,
2834                                             NONE_AMS, 0);
2835                }
2836                break;
2837        case PD_EXT_SOURCE_CAP_EXT:
2838        case PD_EXT_GET_BATT_CAP:
2839        case PD_EXT_GET_BATT_STATUS:
2840        case PD_EXT_BATT_CAP:
2841        case PD_EXT_GET_MANUFACTURER_INFO:
2842        case PD_EXT_MANUFACTURER_INFO:
2843        case PD_EXT_SECURITY_REQUEST:
2844        case PD_EXT_SECURITY_RESPONSE:
2845        case PD_EXT_FW_UPDATE_REQUEST:
2846        case PD_EXT_FW_UPDATE_RESPONSE:
2847        case PD_EXT_COUNTRY_INFO:
2848        case PD_EXT_COUNTRY_CODES:
2849                tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
2850                break;
2851        default:
2852                tcpm_pd_handle_msg(port, PD_MSG_CTRL_NOT_SUPP, NONE_AMS);
2853                tcpm_log(port, "Unrecognized extended message type %#x", type);
2854                break;
2855        }
2856}
2857
2858static void tcpm_pd_rx_handler(struct kthread_work *work)
2859{
2860        struct pd_rx_event *event = container_of(work,
2861                                                 struct pd_rx_event, work);
2862        const struct pd_message *msg = &event->msg;
2863        unsigned int cnt = pd_header_cnt_le(msg->header);
2864        struct tcpm_port *port = event->port;
2865
2866        mutex_lock(&port->lock);
2867
2868        tcpm_log(port, "PD RX, header: %#x [%d]", le16_to_cpu(msg->header),
2869                 port->attached);
2870
2871        if (port->attached) {
2872                enum pd_ctrl_msg_type type = pd_header_type_le(msg->header);
2873                unsigned int msgid = pd_header_msgid_le(msg->header);
2874
2875                /*
2876                 * USB PD standard, 6.6.1.2:
2877                 * "... if MessageID value in a received Message is the
2878                 * same as the stored value, the receiver shall return a
2879                 * GoodCRC Message with that MessageID value and drop
2880                 * the Message (this is a retry of an already received
2881                 * Message). Note: this shall not apply to the Soft_Reset
2882                 * Message which always has a MessageID value of zero."
2883                 */
2884                if (msgid == port->rx_msgid && type != PD_CTRL_SOFT_RESET)
2885                        goto done;
2886                port->rx_msgid = msgid;
2887
2888                /*
2889                 * If both ends believe to be DFP/host, we have a data role
2890                 * mismatch.
2891                 */
2892                if (!!(le16_to_cpu(msg->header) & PD_HEADER_DATA_ROLE) ==
2893                    (port->data_role == TYPEC_HOST)) {
2894                        tcpm_log(port,
2895                                 "Data role mismatch, initiating error recovery");
2896                        tcpm_set_state(port, ERROR_RECOVERY, 0);
2897                } else {
2898                        if (le16_to_cpu(msg->header) & PD_HEADER_EXT_HDR)
2899                                tcpm_pd_ext_msg_request(port, msg);
2900                        else if (cnt)
2901                                tcpm_pd_data_request(port, msg);
2902                        else
2903                                tcpm_pd_ctrl_request(port, msg);
2904                }
2905        }
2906
2907done:
2908        mutex_unlock(&port->lock);
2909        kfree(event);
2910}
2911
2912void tcpm_pd_receive(struct tcpm_port *port, const struct pd_message *msg)
2913{
2914        struct pd_rx_event *event;
2915
2916        event = kzalloc(sizeof(*event), GFP_ATOMIC);
2917        if (!event)
2918                return;
2919
2920        kthread_init_work(&event->work, tcpm_pd_rx_handler);
2921        event->port = port;
2922        memcpy(&event->msg, msg, sizeof(*msg));
2923        kthread_queue_work(port->wq, &event->work);
2924}
2925EXPORT_SYMBOL_GPL(tcpm_pd_receive);
2926
2927static int tcpm_pd_send_control(struct tcpm_port *port,
2928                                enum pd_ctrl_msg_type type)
2929{
2930        struct pd_message msg;
2931
2932        memset(&msg, 0, sizeof(msg));
2933        msg.header = PD_HEADER_LE(type, port->pwr_role,
2934                                  port->data_role,
2935                                  port->negotiated_rev,
2936                                  port->message_id, 0);
2937
2938        return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
2939}
2940
2941/*
2942 * Send queued message without affecting state.
2943 * Return true if state machine should go back to sleep,
2944 * false otherwise.
2945 */
2946static bool tcpm_send_queued_message(struct tcpm_port *port)
2947{
2948        enum pd_msg_request queued_message;
2949        int ret;
2950
2951        do {
2952                queued_message = port->queued_message;
2953                port->queued_message = PD_MSG_NONE;
2954
2955                switch (queued_message) {
2956                case PD_MSG_CTRL_WAIT:
2957                        tcpm_pd_send_control(port, PD_CTRL_WAIT);
2958                        break;
2959                case PD_MSG_CTRL_REJECT:
2960                        tcpm_pd_send_control(port, PD_CTRL_REJECT);
2961                        break;
2962                case PD_MSG_CTRL_NOT_SUPP:
2963                        tcpm_pd_send_control(port, PD_CTRL_NOT_SUPP);
2964                        break;
2965                case PD_MSG_DATA_SINK_CAP:
2966                        ret = tcpm_pd_send_sink_caps(port);
2967                        if (ret < 0) {
2968                                tcpm_log(port, "Unable to send snk caps, ret=%d", ret);
2969                                tcpm_set_state(port, SNK_SOFT_RESET, 0);
2970                        }
2971                        tcpm_ams_finish(port);
2972                        break;
2973                case PD_MSG_DATA_SOURCE_CAP:
2974                        ret = tcpm_pd_send_source_caps(port);
2975                        if (ret < 0) {
2976                                tcpm_log(port,
2977                                         "Unable to send src caps, ret=%d",
2978                                         ret);
2979                                tcpm_set_state(port, SOFT_RESET_SEND, 0);
2980                        } else if (port->pwr_role == TYPEC_SOURCE) {
2981                                tcpm_ams_finish(port);
2982                                tcpm_set_state(port, HARD_RESET_SEND,
2983                                               PD_T_SENDER_RESPONSE);
2984                        } else {
2985                                tcpm_ams_finish(port);
2986                        }
2987                        break;
2988                default:
2989                        break;
2990                }
2991        } while (port->queued_message != PD_MSG_NONE);
2992
2993        if (port->delayed_state != INVALID_STATE) {
2994                if (ktime_after(port->delayed_runtime, ktime_get())) {
2995                        mod_tcpm_delayed_work(port, ktime_to_ms(ktime_sub(port->delayed_runtime,
2996                                                                          ktime_get())));
2997                        return true;
2998                }
2999                port->delayed_state = INVALID_STATE;
3000        }
3001        return false;
3002}
3003
3004static int tcpm_pd_check_request(struct tcpm_port *port)
3005{
3006        u32 pdo, rdo = port->sink_request;
3007        unsigned int max, op, pdo_max, index;
3008        enum pd_pdo_type type;
3009
3010        index = rdo_index(rdo);
3011        if (!index || index > port->nr_src_pdo)
3012                return -EINVAL;
3013
3014        pdo = port->src_pdo[index - 1];
3015        type = pdo_type(pdo);
3016        switch (type) {
3017        case PDO_TYPE_FIXED:
3018        case PDO_TYPE_VAR:
3019                max = rdo_max_current(rdo);
3020                op = rdo_op_current(rdo);
3021                pdo_max = pdo_max_current(pdo);
3022
3023                if (op > pdo_max)
3024                        return -EINVAL;
3025                if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
3026                        return -EINVAL;
3027
3028                if (type == PDO_TYPE_FIXED)
3029                        tcpm_log(port,
3030                                 "Requested %u mV, %u mA for %u / %u mA",
3031                                 pdo_fixed_voltage(pdo), pdo_max, op, max);
3032                else
3033                        tcpm_log(port,
3034                                 "Requested %u -> %u mV, %u mA for %u / %u mA",
3035                                 pdo_min_voltage(pdo), pdo_max_voltage(pdo),
3036                                 pdo_max, op, max);
3037                break;
3038        case PDO_TYPE_BATT:
3039                max = rdo_max_power(rdo);
3040                op = rdo_op_power(rdo);
3041                pdo_max = pdo_max_power(pdo);
3042
3043                if (op > pdo_max)
3044                        return -EINVAL;
3045                if (max > pdo_max && !(rdo & RDO_CAP_MISMATCH))
3046                        return -EINVAL;
3047                tcpm_log(port,
3048                         "Requested %u -> %u mV, %u mW for %u / %u mW",
3049                         pdo_min_voltage(pdo), pdo_max_voltage(pdo),
3050                         pdo_max, op, max);
3051                break;
3052        default:
3053                return -EINVAL;
3054        }
3055
3056        port->op_vsafe5v = index == 1;
3057
3058        return 0;
3059}
3060
3061#define min_power(x, y) min(pdo_max_power(x), pdo_max_power(y))
3062#define min_current(x, y) min(pdo_max_current(x), pdo_max_current(y))
3063
3064static int tcpm_pd_select_pdo(struct tcpm_port *port, int *sink_pdo,
3065                              int *src_pdo)
3066{
3067        unsigned int i, j, max_src_mv = 0, min_src_mv = 0, max_mw = 0,
3068                     max_mv = 0, src_mw = 0, src_ma = 0, max_snk_mv = 0,
3069                     min_snk_mv = 0;
3070        int ret = -EINVAL;
3071
3072        port->pps_data.supported = false;
3073        port->usb_type = POWER_SUPPLY_USB_TYPE_PD;
3074        power_supply_changed(port->psy);
3075
3076        /*
3077         * Select the source PDO providing the most power which has a
3078         * matchig sink cap.
3079         */
3080        for (i = 0; i < port->nr_source_caps; i++) {
3081                u32 pdo = port->source_caps[i];
3082                enum pd_pdo_type type = pdo_type(pdo);
3083
3084                switch (type) {
3085                case PDO_TYPE_FIXED:
3086                        max_src_mv = pdo_fixed_voltage(pdo);
3087                        min_src_mv = max_src_mv;
3088                        break;
3089                case PDO_TYPE_BATT:
3090                case PDO_TYPE_VAR:
3091                        max_src_mv = pdo_max_voltage(pdo);
3092                        min_src_mv = pdo_min_voltage(pdo);
3093                        break;
3094                case PDO_TYPE_APDO:
3095                        if (pdo_apdo_type(pdo) == APDO_TYPE_PPS) {
3096                                port->pps_data.supported = true;
3097                                port->usb_type =
3098                                        POWER_SUPPLY_USB_TYPE_PD_PPS;
3099                                power_supply_changed(port->psy);
3100                        }
3101                        continue;
3102                default:
3103                        tcpm_log(port, "Invalid source PDO type, ignoring");
3104                        continue;
3105                }
3106
3107                switch (type) {
3108                case PDO_TYPE_FIXED:
3109                case PDO_TYPE_VAR:
3110                        src_ma = pdo_max_current(pdo);
3111                        src_mw = src_ma * min_src_mv / 1000;
3112                        break;
3113                case PDO_TYPE_BATT:
3114                        src_mw = pdo_max_power(pdo);
3115                        break;
3116                case PDO_TYPE_APDO:
3117                        continue;
3118                default:
3119                        tcpm_log(port, "Invalid source PDO type, ignoring");
3120                        continue;
3121                }
3122
3123                for (j = 0; j < port->nr_snk_pdo; j++) {
3124                        pdo = port->snk_pdo[j];
3125
3126                        switch (pdo_type(pdo)) {
3127                        case PDO_TYPE_FIXED:
3128                                max_snk_mv = pdo_fixed_voltage(pdo);
3129                                min_snk_mv = max_snk_mv;
3130                                break;
3131                        case PDO_TYPE_BATT:
3132                        case PDO_TYPE_VAR:
3133                                max_snk_mv = pdo_max_voltage(pdo);
3134                                min_snk_mv = pdo_min_voltage(pdo);
3135                                break;
3136                        case PDO_TYPE_APDO:
3137                                continue;
3138                        default:
3139                                tcpm_log(port, "Invalid sink PDO type, ignoring");
3140                                continue;
3141                        }
3142
3143                        if (max_src_mv <= max_snk_mv &&
3144                                min_src_mv >= min_snk_mv) {
3145                                /* Prefer higher voltages if available */
3146                                if ((src_mw == max_mw && min_src_mv > max_mv) ||
3147                                                        src_mw > max_mw) {
3148                                        *src_pdo = i;
3149                                        *sink_pdo = j;
3150                                        max_mw = src_mw;
3151                                        max_mv = min_src_mv;
3152                                        ret = 0;
3153                                }
3154                        }
3155                }
3156        }
3157
3158        return ret;
3159}
3160
3161#define min_pps_apdo_current(x, y)      \
3162        min(pdo_pps_apdo_max_current(x), pdo_pps_apdo_max_current(y))
3163
3164static unsigned int tcpm_pd_select_pps_apdo(struct tcpm_port *port)
3165{
3166        unsigned int i, j, max_mw = 0, max_mv = 0;
3167        unsigned int min_src_mv, max_src_mv, src_ma, src_mw;
3168        unsigned int min_snk_mv, max_snk_mv;
3169        unsigned int max_op_mv;
3170        u32 pdo, src, snk;
3171        unsigned int src_pdo = 0, snk_pdo = 0;
3172
3173        /*
3174         * Select the source PPS APDO providing the most power while staying
3175         * within the board's limits. We skip the first PDO as this is always
3176         * 5V 3A.
3177         */
3178        for (i = 1; i < port->nr_source_caps; ++i) {
3179                pdo = port->source_caps[i];
3180
3181                switch (pdo_type(pdo)) {
3182                case PDO_TYPE_APDO:
3183                        if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
3184                                tcpm_log(port, "Not PPS APDO (source), ignoring");
3185                                continue;
3186                        }
3187
3188                        min_src_mv = pdo_pps_apdo_min_voltage(pdo);
3189                        max_src_mv = pdo_pps_apdo_max_voltage(pdo);
3190                        src_ma = pdo_pps_apdo_max_current(pdo);
3191                        src_mw = (src_ma * max_src_mv) / 1000;
3192
3193                        /*
3194                         * Now search through the sink PDOs to find a matching
3195                         * PPS APDO. Again skip the first sink PDO as this will
3196                         * always be 5V 3A.
3197                         */
3198                        for (j = 1; j < port->nr_snk_pdo; j++) {
3199                                pdo = port->snk_pdo[j];
3200
3201                                switch (pdo_type(pdo)) {
3202                                case PDO_TYPE_APDO:
3203                                        if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
3204                                                tcpm_log(port,
3205                                                         "Not PPS APDO (sink), ignoring");
3206                                                continue;
3207                                        }
3208
3209                                        min_snk_mv =
3210                                                pdo_pps_apdo_min_voltage(pdo);
3211                                        max_snk_mv =
3212                                                pdo_pps_apdo_max_voltage(pdo);
3213                                        break;
3214                                default:
3215                                        tcpm_log(port,
3216                                                 "Not APDO type (sink), ignoring");
3217                                        continue;
3218                                }
3219
3220                                if (min_src_mv <= max_snk_mv &&
3221                                    max_src_mv >= min_snk_mv) {
3222                                        max_op_mv = min(max_src_mv, max_snk_mv);
3223                                        src_mw = (max_op_mv * src_ma) / 1000;
3224                                        /* Prefer higher voltages if available */
3225                                        if ((src_mw == max_mw &&
3226                                             max_op_mv > max_mv) ||
3227                                            src_mw > max_mw) {
3228                                                src_pdo = i;
3229                                                snk_pdo = j;
3230                                                max_mw = src_mw;
3231                                                max_mv = max_op_mv;
3232                                        }
3233                                }
3234                        }
3235
3236                        break;
3237                default:
3238                        tcpm_log(port, "Not APDO type (source), ignoring");
3239                        continue;
3240                }
3241        }
3242
3243        if (src_pdo) {
3244                src = port->source_caps[src_pdo];
3245                snk = port->snk_pdo[snk_pdo];
3246
3247                port->pps_data.req_min_volt = max(pdo_pps_apdo_min_voltage(src),
3248                                                  pdo_pps_apdo_min_voltage(snk));
3249                port->pps_data.req_max_volt = min(pdo_pps_apdo_max_voltage(src),
3250                                                  pdo_pps_apdo_max_voltage(snk));
3251                port->pps_data.req_max_curr = min_pps_apdo_current(src, snk);
3252                port->pps_data.req_out_volt = min(port->pps_data.req_max_volt,
3253                                                  max(port->pps_data.req_min_volt,
3254                                                      port->pps_data.req_out_volt));
3255                port->pps_data.req_op_curr = min(port->pps_data.req_max_curr,
3256                                                 port->pps_data.req_op_curr);
3257        }
3258
3259        return src_pdo;
3260}
3261
3262static int tcpm_pd_build_request(struct tcpm_port *port, u32 *rdo)
3263{
3264        unsigned int mv, ma, mw, flags;
3265        unsigned int max_ma, max_mw;
3266        enum pd_pdo_type type;
3267        u32 pdo, matching_snk_pdo;
3268        int src_pdo_index = 0;
3269        int snk_pdo_index = 0;
3270        int ret;
3271
3272        ret = tcpm_pd_select_pdo(port, &snk_pdo_index, &src_pdo_index);
3273        if (ret < 0)
3274                return ret;
3275
3276        pdo = port->source_caps[src_pdo_index];
3277        matching_snk_pdo = port->snk_pdo[snk_pdo_index];
3278        type = pdo_type(pdo);
3279
3280        switch (type) {
3281        case PDO_TYPE_FIXED:
3282                mv = pdo_fixed_voltage(pdo);
3283                break;
3284        case PDO_TYPE_BATT:
3285        case PDO_TYPE_VAR:
3286                mv = pdo_min_voltage(pdo);
3287                break;
3288        default:
3289                tcpm_log(port, "Invalid PDO selected!");
3290                return -EINVAL;
3291        }
3292
3293        /* Select maximum available current within the sink pdo's limit */
3294        if (type == PDO_TYPE_BATT) {
3295                mw = min_power(pdo, matching_snk_pdo);
3296                ma = 1000 * mw / mv;
3297        } else {
3298                ma = min_current(pdo, matching_snk_pdo);
3299                mw = ma * mv / 1000;
3300        }
3301
3302        flags = RDO_USB_COMM | RDO_NO_SUSPEND;
3303
3304        /* Set mismatch bit if offered power is less than operating power */
3305        max_ma = ma;
3306        max_mw = mw;
3307        if (mw < port->operating_snk_mw) {
3308                flags |= RDO_CAP_MISMATCH;
3309                if (type == PDO_TYPE_BATT &&
3310                    (pdo_max_power(matching_snk_pdo) > pdo_max_power(pdo)))
3311                        max_mw = pdo_max_power(matching_snk_pdo);
3312                else if (pdo_max_current(matching_snk_pdo) >
3313                         pdo_max_current(pdo))
3314                        max_ma = pdo_max_current(matching_snk_pdo);
3315        }
3316
3317        tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
3318                 port->cc_req, port->cc1, port->cc2, port->vbus_source,
3319                 port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
3320                 port->polarity);
3321
3322        if (type == PDO_TYPE_BATT) {
3323                *rdo = RDO_BATT(src_pdo_index + 1, mw, max_mw, flags);
3324
3325                tcpm_log(port, "Requesting PDO %d: %u mV, %u mW%s",
3326                         src_pdo_index, mv, mw,
3327                         flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
3328        } else {
3329                *rdo = RDO_FIXED(src_pdo_index + 1, ma, max_ma, flags);
3330
3331                tcpm_log(port, "Requesting PDO %d: %u mV, %u mA%s",
3332                         src_pdo_index, mv, ma,
3333                         flags & RDO_CAP_MISMATCH ? " [mismatch]" : "");
3334        }
3335
3336        port->req_current_limit = ma;
3337        port->req_supply_voltage = mv;
3338
3339        return 0;
3340}
3341
3342static int tcpm_pd_send_request(struct tcpm_port *port)
3343{
3344        struct pd_message msg;
3345        int ret;
3346        u32 rdo;
3347
3348        ret = tcpm_pd_build_request(port, &rdo);
3349        if (ret < 0)
3350                return ret;
3351
3352        /*
3353         * Relax the threshold as voltage will be adjusted after Accept Message plus tSrcTransition.
3354         * It is safer to modify the threshold here.
3355         */
3356        tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
3357
3358        memset(&msg, 0, sizeof(msg));
3359        msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
3360                                  port->pwr_role,
3361                                  port->data_role,
3362                                  port->negotiated_rev,
3363                                  port->message_id, 1);
3364        msg.payload[0] = cpu_to_le32(rdo);
3365
3366        return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
3367}
3368
3369static int tcpm_pd_build_pps_request(struct tcpm_port *port, u32 *rdo)
3370{
3371        unsigned int out_mv, op_ma, op_mw, max_mv, max_ma, flags;
3372        enum pd_pdo_type type;
3373        unsigned int src_pdo_index;
3374        u32 pdo;
3375
3376        src_pdo_index = tcpm_pd_select_pps_apdo(port);
3377        if (!src_pdo_index)
3378                return -EOPNOTSUPP;
3379
3380        pdo = port->source_caps[src_pdo_index];
3381        type = pdo_type(pdo);
3382
3383        switch (type) {
3384        case PDO_TYPE_APDO:
3385                if (pdo_apdo_type(pdo) != APDO_TYPE_PPS) {
3386                        tcpm_log(port, "Invalid APDO selected!");
3387                        return -EINVAL;
3388                }
3389                max_mv = port->pps_data.req_max_volt;
3390                max_ma = port->pps_data.req_max_curr;
3391                out_mv = port->pps_data.req_out_volt;
3392                op_ma = port->pps_data.req_op_curr;
3393                break;
3394        default:
3395                tcpm_log(port, "Invalid PDO selected!");
3396                return -EINVAL;
3397        }
3398
3399        flags = RDO_USB_COMM | RDO_NO_SUSPEND;
3400
3401        op_mw = (op_ma * out_mv) / 1000;
3402        if (op_mw < port->operating_snk_mw) {
3403                /*
3404                 * Try raising current to meet power needs. If that's not enough
3405                 * then try upping the voltage. If that's still not enough
3406                 * then we've obviously chosen a PPS APDO which really isn't
3407                 * suitable so abandon ship.
3408                 */
3409                op_ma = (port->operating_snk_mw * 1000) / out_mv;
3410                if ((port->operating_snk_mw * 1000) % out_mv)
3411                        ++op_ma;
3412                op_ma += RDO_PROG_CURR_MA_STEP - (op_ma % RDO_PROG_CURR_MA_STEP);
3413
3414                if (op_ma > max_ma) {
3415                        op_ma = max_ma;
3416                        out_mv = (port->operating_snk_mw * 1000) / op_ma;
3417                        if ((port->operating_snk_mw * 1000) % op_ma)
3418                                ++out_mv;
3419                        out_mv += RDO_PROG_VOLT_MV_STEP -
3420                                  (out_mv % RDO_PROG_VOLT_MV_STEP);
3421
3422                        if (out_mv > max_mv) {
3423                                tcpm_log(port, "Invalid PPS APDO selected!");
3424                                return -EINVAL;
3425                        }
3426                }
3427        }
3428
3429        tcpm_log(port, "cc=%d cc1=%d cc2=%d vbus=%d vconn=%s polarity=%d",
3430                 port->cc_req, port->cc1, port->cc2, port->vbus_source,
3431                 port->vconn_role == TYPEC_SOURCE ? "source" : "sink",
3432                 port->polarity);
3433
3434        *rdo = RDO_PROG(src_pdo_index + 1, out_mv, op_ma, flags);
3435
3436        tcpm_log(port, "Requesting APDO %d: %u mV, %u mA",
3437                 src_pdo_index, out_mv, op_ma);
3438
3439        port->pps_data.req_op_curr = op_ma;
3440        port->pps_data.req_out_volt = out_mv;
3441
3442        return 0;
3443}
3444
3445static int tcpm_pd_send_pps_request(struct tcpm_port *port)
3446{
3447        struct pd_message msg;
3448        int ret;
3449        u32 rdo;
3450
3451        ret = tcpm_pd_build_pps_request(port, &rdo);
3452        if (ret < 0)
3453                return ret;
3454
3455        /* Relax the threshold as voltage will be adjusted right after Accept Message. */
3456        tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_USB, false, 0);
3457
3458        memset(&msg, 0, sizeof(msg));
3459        msg.header = PD_HEADER_LE(PD_DATA_REQUEST,
3460                                  port->pwr_role,
3461                                  port->data_role,
3462                                  port->negotiated_rev,
3463                                  port->message_id, 1);
3464        msg.payload[0] = cpu_to_le32(rdo);
3465
3466        return tcpm_pd_transmit(port, TCPC_TX_SOP, &msg);
3467}
3468
3469static int tcpm_set_vbus(struct tcpm_port *port, bool enable)
3470{
3471        int ret;
3472
3473        if (enable && port->vbus_charge)
3474                return -EINVAL;
3475
3476        tcpm_log(port, "vbus:=%d charge=%d", enable, port->vbus_charge);
3477
3478        ret = port->tcpc->set_vbus(port->tcpc, enable, port->vbus_charge);
3479        if (ret < 0)
3480                return ret;
3481
3482        port->vbus_source = enable;
3483        return 0;
3484}
3485
3486static int tcpm_set_charge(struct tcpm_port *port, bool charge)
3487{
3488        int ret;
3489
3490        if (charge && port->vbus_source)
3491                return -EINVAL;
3492
3493        if (charge != port->vbus_charge) {
3494                tcpm_log(port, "vbus=%d charge:=%d", port->vbus_source, charge);
3495                ret = port->tcpc->set_vbus(port->tcpc, port->vbus_source,
3496                                           charge);
3497                if (ret < 0)
3498                        return ret;
3499        }
3500        port->vbus_charge = charge;
3501        power_supply_changed(port->psy);
3502        return 0;
3503}
3504
3505static bool tcpm_start_toggling(struct tcpm_port *port, enum typec_cc_status cc)
3506{
3507        int ret;
3508
3509        if (!port->tcpc->start_toggling)
3510                return false;
3511
3512        tcpm_log_force(port, "Start toggling");
3513        ret = port->tcpc->start_toggling(port->tcpc, port->port_type, cc);
3514        return ret == 0;
3515}
3516
3517static int tcpm_init_vbus(struct tcpm_port *port)
3518{
3519        int ret;
3520
3521        ret = port->tcpc->set_vbus(port->tcpc, false, false);
3522        port->vbus_source = false;
3523        port->vbus_charge = false;
3524        return ret;
3525}
3526
3527static int tcpm_init_vconn(struct tcpm_port *port)
3528{
3529        int ret;
3530
3531        ret = port->tcpc->set_vconn(port->tcpc, false);
3532        port->vconn_role = TYPEC_SINK;
3533        return ret;
3534}
3535
3536static void tcpm_typec_connect(struct tcpm_port *port)
3537{
3538        if (!port->connected) {
3539                /* Make sure we don't report stale identity information */
3540                memset(&port->partner_ident, 0, sizeof(port->partner_ident));
3541                port->partner_desc.usb_pd = port->pd_capable;
3542                if (tcpm_port_is_debug(port))
3543                        port->partner_desc.accessory = TYPEC_ACCESSORY_DEBUG;
3544                else if (tcpm_port_is_audio(port))
3545                        port->partner_desc.accessory = TYPEC_ACCESSORY_AUDIO;
3546                else
3547                        port->partner_desc.accessory = TYPEC_ACCESSORY_NONE;
3548                port->partner = typec_register_partner(port->typec_port,
3549                                                       &port->partner_desc);
3550                port->connected = true;
3551        }
3552}
3553
3554static int tcpm_src_attach(struct tcpm_port *port)
3555{
3556        enum typec_cc_polarity polarity =
3557                                port->cc2 == TYPEC_CC_RD ? TYPEC_POLARITY_CC2
3558                                                         : TYPEC_POLARITY_CC1;
3559        int ret;
3560
3561        if (port->attached)
3562                return 0;
3563
3564        ret = tcpm_set_polarity(port, polarity);
3565        if (ret < 0)
3566                return ret;
3567
3568        tcpm_enable_auto_vbus_discharge(port, true);
3569
3570        ret = tcpm_set_roles(port, true, TYPEC_SOURCE, tcpm_data_role_for_source(port));
3571        if (ret < 0)
3572                return ret;
3573
3574        ret = port->tcpc->set_pd_rx(port->tcpc, true);
3575        if (ret < 0)
3576                goto out_disable_mux;
3577
3578        /*
3579         * USB Type-C specification, version 1.2,
3580         * chapter 4.5.2.2.8.1 (Attached.SRC Requirements)
3581         * Enable VCONN only if the non-RD port is set to RA.
3582         */
3583        if ((polarity == TYPEC_POLARITY_CC1 && port->cc2 == TYPEC_CC_RA) ||
3584            (polarity == TYPEC_POLARITY_CC2 && port->cc1 == TYPEC_CC_RA)) {
3585                ret = tcpm_set_vconn(port, true);
3586                if (ret < 0)
3587                        goto out_disable_pd;
3588        }
3589
3590        ret = tcpm_set_vbus(port, true);
3591        if (ret < 0)
3592                goto out_disable_vconn;
3593
3594        port->pd_capable = false;
3595
3596        port->partner = NULL;
3597
3598        port->attached = true;
3599        port->send_discover = true;
3600
3601        return 0;
3602
3603out_disable_vconn:
3604        tcpm_set_vconn(port, false);
3605out_disable_pd:
3606        port->tcpc->set_pd_rx(port->tcpc, false);
3607out_disable_mux:
3608        tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
3609                     TYPEC_ORIENTATION_NONE);
3610        return ret;
3611}
3612
3613static void tcpm_typec_disconnect(struct tcpm_port *port)
3614{
3615        if (port->connected) {
3616                typec_unregister_partner(port->partner);
3617                port->partner = NULL;
3618                port->connected = false;
3619        }
3620}
3621
3622static void tcpm_unregister_altmodes(struct tcpm_port *port)
3623{
3624        struct pd_mode_data *modep = &port->mode_data;
3625        int i;
3626
3627        for (i = 0; i < modep->altmodes; i++) {
3628                typec_unregister_altmode(port->partner_altmode[i]);
3629                port->partner_altmode[i] = NULL;
3630        }
3631
3632        memset(modep, 0, sizeof(*modep));
3633}
3634
3635static void tcpm_set_partner_usb_comm_capable(struct tcpm_port *port, bool capable)
3636{
3637        tcpm_log(port, "Setting usb_comm capable %s", capable ? "true" : "false");
3638
3639        if (port->tcpc->set_partner_usb_comm_capable)
3640                port->tcpc->set_partner_usb_comm_capable(port->tcpc, capable);
3641}
3642
3643static void tcpm_reset_port(struct tcpm_port *port)
3644{
3645        tcpm_enable_auto_vbus_discharge(port, false);
3646        port->in_ams = false;
3647        port->ams = NONE_AMS;
3648        port->vdm_sm_running = false;
3649        tcpm_unregister_altmodes(port);
3650        tcpm_typec_disconnect(port);
3651        port->attached = false;
3652        port->pd_capable = false;
3653        port->pps_data.supported = false;
3654        tcpm_set_partner_usb_comm_capable(port, false);
3655
3656        /*
3657         * First Rx ID should be 0; set this to a sentinel of -1 so that
3658         * we can check tcpm_pd_rx_handler() if we had seen it before.
3659         */
3660        port->rx_msgid = -1;
3661
3662        port->tcpc->set_pd_rx(port->tcpc, false);
3663        tcpm_init_vbus(port);   /* also disables charging */
3664        tcpm_init_vconn(port);
3665        tcpm_set_current_limit(port, 0, 0);
3666        tcpm_set_polarity(port, TYPEC_POLARITY_CC1);
3667        tcpm_mux_set(port, TYPEC_STATE_SAFE, USB_ROLE_NONE,
3668                     TYPEC_ORIENTATION_NONE);
3669        tcpm_set_attached_state(port, false);
3670        port->try_src_count = 0;
3671        port->try_snk_count = 0;
3672        port->usb_type = POWER_SUPPLY_USB_TYPE_C;
3673        power_supply_changed(port->psy);
3674        port->nr_sink_caps = 0;
3675        port->sink_cap_done = false;
3676        if (port->tcpc->enable_frs)
3677                port->tcpc->enable_frs(port->tcpc, false);
3678}
3679
3680static void tcpm_detach(struct tcpm_port *port)
3681{
3682        if (tcpm_port_is_disconnected(port))
3683                port->hard_reset_count = 0;
3684
3685        if (!port->attached)
3686                return;
3687
3688        if (port->tcpc->set_bist_data) {
3689                tcpm_log(port, "disable BIST MODE TESTDATA");
3690                port->tcpc->set_bist_data(port->tcpc, false);
3691        }
3692
3693        tcpm_reset_port(port);
3694}
3695
3696static void tcpm_src_detach(struct tcpm_port *port)
3697{
3698        tcpm_detach(port);
3699}
3700
3701static int tcpm_snk_attach(struct tcpm_port *port)
3702{
3703        int ret;
3704
3705        if (port->attached)
3706                return 0;
3707
3708        ret = tcpm_set_polarity(port, port->cc2 != TYPEC_CC_OPEN ?
3709                                TYPEC_POLARITY_CC2 : TYPEC_POLARITY_CC1);
3710        if (ret < 0)
3711                return ret;
3712
3713        tcpm_enable_auto_vbus_discharge(port, true);
3714
3715        ret = tcpm_set_roles(port, true, TYPEC_SINK, tcpm_data_role_for_sink(port));
3716        if (ret < 0)
3717                return ret;
3718
3719        port->pd_capable = false;
3720
3721        port->partner = NULL;
3722
3723        port->attached = true;
3724        port->send_discover = true;
3725
3726        return 0;
3727}
3728
3729static void tcpm_snk_detach(struct tcpm_port *port)
3730{
3731        tcpm_detach(port);
3732}
3733
3734static int tcpm_acc_attach(struct tcpm_port *port)
3735{
3736        int ret;
3737
3738        if (port->attached)
3739                return 0;
3740
3741        ret = tcpm_set_roles(port, true, TYPEC_SOURCE,
3742                             tcpm_data_role_for_source(port));
3743        if (ret < 0)
3744                return ret;
3745
3746        port->partner = NULL;
3747
3748        tcpm_typec_connect(port);
3749
3750        port->attached = true;
3751
3752        return 0;
3753}
3754
3755static void tcpm_acc_detach(struct tcpm_port *port)
3756{
3757        tcpm_detach(port);
3758}
3759
3760static inline enum tcpm_state hard_reset_state(struct tcpm_port *port)
3761{
3762        if (port->hard_reset_count < PD_N_HARD_RESET_COUNT)
3763                return HARD_RESET_SEND;
3764        if (port->pd_capable)
3765                return ERROR_RECOVERY;
3766        if (port->pwr_role == TYPEC_SOURCE)
3767                return SRC_UNATTACHED;
3768        if (port->state == SNK_WAIT_CAPABILITIES)
3769                return SNK_READY;
3770        return SNK_UNATTACHED;
3771}
3772
3773static inline enum tcpm_state unattached_state(struct tcpm_port *port)
3774{
3775        if (port->port_type == TYPEC_PORT_DRP) {
3776                if (port->pwr_role == TYPEC_SOURCE)
3777                        return SRC_UNATTACHED;
3778                else
3779                        return SNK_UNATTACHED;
3780        } else if (port->port_type == TYPEC_PORT_SRC) {
3781                return SRC_UNATTACHED;
3782        }
3783
3784        return SNK_UNATTACHED;
3785}
3786
3787static void tcpm_swap_complete(struct tcpm_port *port, int result)
3788{
3789        if (port->swap_pending) {
3790                port->swap_status = result;
3791                port->swap_pending = false;
3792                port->non_pd_role_swap = false;
3793                complete(&port->swap_complete);
3794        }
3795}
3796
3797static enum typec_pwr_opmode tcpm_get_pwr_opmode(enum typec_cc_status cc)
3798{
3799        switch (cc) {
3800        case TYPEC_CC_RP_1_5:
3801                return TYPEC_PWR_MODE_1_5A;
3802        case TYPEC_CC_RP_3_0:
3803                return TYPEC_PWR_MODE_3_0A;
3804        case TYPEC_CC_RP_DEF:
3805        default:
3806                return TYPEC_PWR_MODE_USB;
3807        }
3808}
3809
3810static void run_state_machine(struct tcpm_port *port)
3811{
3812        int ret;
3813        enum typec_pwr_opmode opmode;
3814        unsigned int msecs;
3815        enum tcpm_state upcoming_state;
3816
3817        port->enter_state = port->state;
3818        switch (port->state) {
3819        case TOGGLING:
3820                break;
3821        /* SRC states */
3822        case SRC_UNATTACHED:
3823                if (!port->non_pd_role_swap)
3824                        tcpm_swap_complete(port, -ENOTCONN);
3825                tcpm_src_detach(port);
3826                if (tcpm_start_toggling(port, tcpm_rp_cc(port))) {
3827                        tcpm_set_state(port, TOGGLING, 0);
3828                        break;
3829                }
3830                tcpm_set_cc(port, tcpm_rp_cc(port));
3831                if (port->port_type == TYPEC_PORT_DRP)
3832                        tcpm_set_state(port, SNK_UNATTACHED, PD_T_DRP_SNK);
3833                break;
3834        case SRC_ATTACH_WAIT:
3835                if (tcpm_port_is_debug(port))
3836                        tcpm_set_state(port, DEBUG_ACC_ATTACHED,
3837                                       PD_T_CC_DEBOUNCE);
3838                else if (tcpm_port_is_audio(port))
3839                        tcpm_set_state(port, AUDIO_ACC_ATTACHED,
3840                                       PD_T_CC_DEBOUNCE);
3841                else if (tcpm_port_is_source(port) && port->vbus_vsafe0v)
3842                        tcpm_set_state(port,
3843                                       tcpm_try_snk(port) ? SNK_TRY
3844                                                          : SRC_ATTACHED,
3845                                       PD_T_CC_DEBOUNCE);
3846                break;
3847
3848        case SNK_TRY:
3849                port->try_snk_count++;
3850                /*
3851                 * Requirements:
3852                 * - Do not drive vconn or vbus
3853                 * - Terminate CC pins (both) to Rd
3854                 * Action:
3855                 * - Wait for tDRPTry (PD_T_DRP_TRY).
3856                 *   Until then, ignore any state changes.
3857                 */
3858                tcpm_set_cc(port, TYPEC_CC_RD);
3859                tcpm_set_state(port, SNK_TRY_WAIT, PD_T_DRP_TRY);
3860                break;
3861        case SNK_TRY_WAIT:
3862                if (tcpm_port_is_sink(port)) {
3863                        tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE, 0);
3864                } else {
3865                        tcpm_set_state(port, SRC_TRYWAIT, 0);
3866                        port->max_wait = 0;
3867                }
3868                break;
3869        case SNK_TRY_WAIT_DEBOUNCE:
3870                tcpm_set_state(port, SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS,
3871                               PD_T_TRY_CC_DEBOUNCE);
3872                break;
3873        case SNK_TRY_WAIT_DEBOUNCE_CHECK_VBUS:
3874                if (port->vbus_present && tcpm_port_is_sink(port))
3875                        tcpm_set_state(port, SNK_ATTACHED, 0);
3876                else
3877                        port->max_wait = 0;
3878                break;
3879        case SRC_TRYWAIT:
3880                tcpm_set_cc(port, tcpm_rp_cc(port));
3881                if (port->max_wait == 0) {
3882                        port->max_wait = jiffies +
3883                                         msecs_to_jiffies(PD_T_DRP_TRY);
3884                        tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
3885                                       PD_T_DRP_TRY);
3886                } else {
3887                        if (time_is_after_jiffies(port->max_wait))
3888                                tcpm_set_state(port, SRC_TRYWAIT_UNATTACHED,
3889                                               jiffies_to_msecs(port->max_wait -
3890                                                                jiffies));
3891                        else
3892                                tcpm_set_state(port, SNK_UNATTACHED, 0);
3893                }
3894                break;
3895        case SRC_TRYWAIT_DEBOUNCE:
3896                tcpm_set_state(port, SRC_ATTACHED, PD_T_CC_DEBOUNCE);
3897                break;
3898        case SRC_TRYWAIT_UNATTACHED:
3899                tcpm_set_state(port, SNK_UNATTACHED, 0);
3900                break;
3901
3902        case SRC_ATTACHED:
3903                ret = tcpm_src_attach(port);
3904                tcpm_set_state(port, SRC_UNATTACHED,
3905                               ret < 0 ? 0 : PD_T_PS_SOURCE_ON);
3906                break;
3907        case SRC_STARTUP:
3908                opmode =  tcpm_get_pwr_opmode(tcpm_rp_cc(port));
3909                typec_set_pwr_opmode(port->typec_port, opmode);
3910                port->pwr_opmode = TYPEC_PWR_MODE_USB;
3911                port->caps_count = 0;
3912                port->negotiated_rev = PD_MAX_REV;
3913                port->message_id = 0;
3914                port->rx_msgid = -1;
3915                port->explicit_contract = false;
3916                /* SNK -> SRC POWER/FAST_ROLE_SWAP finished */
3917                if (port->ams == POWER_ROLE_SWAP ||
3918                    port->ams == FAST_ROLE_SWAP)
3919                        tcpm_ams_finish(port);
3920                port->upcoming_state = SRC_SEND_CAPABILITIES;
3921                tcpm_ams_start(port, POWER_NEGOTIATION);
3922                break;
3923        case SRC_SEND_CAPABILITIES:
3924                port->caps_count++;
3925                if (port->caps_count > PD_N_CAPS_COUNT) {
3926                        tcpm_set_state(port, SRC_READY, 0);
3927                        break;
3928                }
3929                ret = tcpm_pd_send_source_caps(port);
3930                if (ret < 0) {
3931                        tcpm_set_state(port, SRC_SEND_CAPABILITIES,
3932                                       PD_T_SEND_SOURCE_CAP);
3933                } else {
3934                        /*
3935                         * Per standard, we should clear the reset counter here.
3936                         * However, that can result in state machine hang-ups.
3937                         * Reset it only in READY state to improve stability.
3938                         */
3939                        /* port->hard_reset_count = 0; */
3940                        port->caps_count = 0;
3941                        port->pd_capable = true;
3942                        tcpm_set_state_cond(port, SRC_SEND_CAPABILITIES_TIMEOUT,
3943                                            PD_T_SEND_SOURCE_CAP);
3944                }
3945                break;
3946        case SRC_SEND_CAPABILITIES_TIMEOUT:
3947                /*
3948                 * Error recovery for a PD_DATA_SOURCE_CAP reply timeout.
3949                 *
3950                 * PD 2.0 sinks are supposed to accept src-capabilities with a
3951                 * 3.0 header and simply ignore any src PDOs which the sink does
3952                 * not understand such as PPS but some 2.0 sinks instead ignore
3953                 * the entire PD_DATA_SOURCE_CAP message, causing contract
3954                 * negotiation to fail.
3955                 *
3956                 * After PD_N_HARD_RESET_COUNT hard-reset attempts, we try
3957                 * sending src-capabilities with a lower PD revision to
3958                 * make these broken sinks work.
3959                 */
3960                if (port->hard_reset_count < PD_N_HARD_RESET_COUNT) {
3961                        tcpm_set_state(port, HARD_RESET_SEND, 0);
3962                } else if (port->negotiated_rev > PD_REV20) {
3963                        port->negotiated_rev--;
3964                        port->hard_reset_count = 0;
3965                        tcpm_set_state(port, SRC_SEND_CAPABILITIES, 0);
3966                } else {
3967                        tcpm_set_state(port, hard_reset_state(port), 0);
3968                }
3969                break;
3970        case SRC_NEGOTIATE_CAPABILITIES:
3971                ret = tcpm_pd_check_request(port);
3972                if (ret < 0) {
3973                        tcpm_pd_send_control(port, PD_CTRL_REJECT);
3974                        if (!port->explicit_contract) {
3975                                tcpm_set_state(port,
3976                                               SRC_WAIT_NEW_CAPABILITIES, 0);
3977                        } else {
3978                                tcpm_set_state(port, SRC_READY, 0);
3979                        }
3980                } else {
3981                        tcpm_pd_send_control(port, PD_CTRL_ACCEPT);
3982                        tcpm_set_partner_usb_comm_capable(port,
3983                                                          !!(port->sink_request & RDO_USB_COMM));
3984                        tcpm_set_state(port, SRC_TRANSITION_SUPPLY,
3985                                       PD_T_SRC_TRANSITION);
3986                }
3987                break;
3988        case SRC_TRANSITION_SUPPLY:
3989                /* XXX: regulator_set_voltage(vbus, ...) */
3990                tcpm_pd_send_control(port, PD_CTRL_PS_RDY);
3991                port->explicit_contract = true;
3992                typec_set_pwr_opmode(port->typec_port, TYPEC_PWR_MODE_PD);
3993                port->pwr_opmode = TYPEC_PWR_MODE_PD;
3994                tcpm_set_state_cond(port, SRC_READY, 0);
3995                break;
3996        case SRC_READY:
3997#if 1
3998                port->hard_reset_count = 0;
3999#endif
4000                port->try_src_count = 0;
4001
4002                tcpm_swap_complete(port, 0);
4003                tcpm_typec_connect(port);
4004
4005                if (port->ams != NONE_AMS)
4006                        tcpm_ams_finish(port);
4007                if (port->next_ams != NONE_AMS) {
4008                        port->ams = port->next_ams;
4009                        port->next_ams = NONE_AMS;
4010                }
4011
4012                /*
4013                 * If previous AMS is interrupted, switch to the upcoming
4014                 * state.
4015                 */
4016                if (port->upcoming_state != INVALID_STATE) {
4017                        upcoming_state = port->upcoming_state;
4018                        port->upcoming_state = INVALID_STATE;
4019                        tcpm_set_state(port, upcoming_state, 0);
4020                        break;
4021                }
4022
4023                /*
4024                 * 6.4.4.3.1 Discover Identity
4025                 * "The Discover Identity Command Shall only be sent to SOP when there is an
4026                 * Explicit Contract."
4027                 * For now, this driver only supports SOP for DISCOVER_IDENTITY, thus using
4028                 * port->explicit_contract to decide whether to send the command.
4029                 */
4030                if (port->explicit_contract)
4031                        mod_send_discover_delayed_work(port, 0);
4032                else
4033                        port->send_discover = false;
4034
4035                /*
4036                 * 6.3.5
4037                 * Sending ping messages is not necessary if
4038                 * - the source operates at vSafe5V
4039                 * or
4040                 * - The system is not operating in PD mode
4041                 * or
4042                 * - Both partners are connected using a Type-C connector
4043                 *
4044                 * There is no actual need to send PD messages since the local
4045                 * port type-c and the spec does not clearly say whether PD is
4046                 * possible when type-c is connected to Type-A/B
4047                 */
4048                break;
4049        case SRC_WAIT_NEW_CAPABILITIES:
4050                /* Nothing to do... */
4051                break;
4052
4053        /* SNK states */
4054        case SNK_UNATTACHED:
4055                if (!port->non_pd_role_swap)
4056                        tcpm_swap_complete(port, -ENOTCONN);
4057                tcpm_pps_complete(port, -ENOTCONN);
4058                tcpm_snk_detach(port);
4059                if (tcpm_start_toggling(port, TYPEC_CC_RD)) {
4060                        tcpm_set_state(port, TOGGLING, 0);
4061                        break;
4062                }
4063                tcpm_set_cc(port, TYPEC_CC_RD);
4064                if (port->port_type == TYPEC_PORT_DRP)
4065                        tcpm_set_state(port, SRC_UNATTACHED, PD_T_DRP_SRC);
4066                break;
4067        case SNK_ATTACH_WAIT:
4068                if ((port->cc1 == TYPEC_CC_OPEN &&
4069                     port->cc2 != TYPEC_CC_OPEN) ||
4070                    (port->cc1 != TYPEC_CC_OPEN &&
4071                     port->cc2 == TYPEC_CC_OPEN))
4072                        tcpm_set_state(port, SNK_DEBOUNCED,
4073                                       PD_T_CC_DEBOUNCE);
4074                else if (tcpm_port_is_disconnected(port))
4075                        tcpm_set_state(port, SNK_UNATTACHED,
4076                                       PD_T_PD_DEBOUNCE);
4077                break;
4078        case SNK_DEBOUNCED:
4079                if (tcpm_port_is_disconnected(port))
4080                        tcpm_set_state(port, SNK_UNATTACHED,
4081                                       PD_T_PD_DEBOUNCE);
4082                else if (port->vbus_present)
4083                        tcpm_set_state(port,
4084                                       tcpm_try_src(port) ? SRC_TRY
4085                                                          : SNK_ATTACHED,
4086                                       0);
4087                else
4088                        /* Wait for VBUS, but not forever */
4089                        tcpm_set_state(port, PORT_RESET, PD_T_PS_SOURCE_ON);
4090                break;
4091
4092        case SRC_TRY:
4093                port->try_src_count++;
4094                tcpm_set_cc(port, tcpm_rp_cc(port));
4095                port->max_wait = 0;
4096                tcpm_set_state(port, SRC_TRY_WAIT, 0);
4097                break;
4098        case SRC_TRY_WAIT:
4099                if (port->max_wait == 0) {
4100                        port->max_wait = jiffies +
4101                                         msecs_to_jiffies(PD_T_DRP_TRY);
4102                        msecs = PD_T_DRP_TRY;
4103                } else {
4104                        if (time_is_after_jiffies(port->max_wait))
4105                                msecs = jiffies_to_msecs(port->max_wait -
4106                                                         jiffies);
4107                        else
4108                                msecs = 0;
4109                }
4110                tcpm_set_state(port, SNK_TRYWAIT, msecs);
4111                break;
4112        case SRC_TRY_DEBOUNCE:
4113                tcpm_set_state(port, SRC_ATTACHED, PD_T_PD_DEBOUNCE);
4114                break;
4115        case SNK_TRYWAIT:
4116                tcpm_set_cc(port, TYPEC_CC_RD);
4117                tcpm_set_state(port, SNK_TRYWAIT_VBUS, PD_T_CC_DEBOUNCE);
4118                break;
4119        case SNK_TRYWAIT_VBUS:
4120                /*
4121                 * TCPM stays in this state indefinitely until VBUS
4122                 * is detected as long as Rp is not detected for
4123                 * more than a time period of tPDDebounce.
4124                 */
4125                if (port->vbus_present && tcpm_port_is_sink(port)) {
4126                        tcpm_set_state(port, SNK_ATTACHED, 0);
4127                        break;
4128                }
4129                if (!tcpm_port_is_sink(port))
4130                        tcpm_set_state(port, SNK_TRYWAIT_DEBOUNCE, 0);
4131                break;
4132        case SNK_TRYWAIT_DEBOUNCE:
4133                tcpm_set_state(port, SNK_UNATTACHED, PD_T_PD_DEBOUNCE);
4134                break;
4135        case SNK_ATTACHED:
4136                ret = tcpm_snk_attach(port);
4137                if (ret < 0)
4138                        tcpm_set_state(port, SNK_UNATTACHED, 0);
4139                else
4140                        tcpm_set_state(port, SNK_STARTUP, 0);
4141                break;
4142        case SNK_STARTUP:
4143                opmode =  tcpm_get_pwr_opmode(port->polarity ?
4144                                              port->cc2 : port->cc1);
4145                typec_set_pwr_opmode(port->typec_port, opmode);
4146                port->pwr_opmode = TYPEC_PWR_MODE_USB;
4147                port->negotiated_rev = PD_MAX_REV;
4148                port->message_id = 0;
4149                port->rx_msgid = -1;
4150                port->explicit_contract = false;
4151
4152                if (port->ams == POWER_ROLE_SWAP ||
4153                    port->ams == FAST_ROLE_SWAP)
4154                        /* SRC -> SNK POWER/FAST_ROLE_SWAP finished */
4155                        tcpm_ams_finish(port);
4156
4157                tcpm_set_state(port, SNK_DISCOVERY, 0);
4158                break;
4159        case SNK_DISCOVERY:
4160                if (port->vbus_present) {
4161                        u32 current_lim = tcpm_get_current_limit(port);
4162
4163                        if (port->slow_charger_loop && (current_lim > PD_P_SNK_STDBY_MW / 5))
4164                                current_lim = PD_P_SNK_STDBY_MW / 5;
4165                        tcpm_set_current_limit(port, current_lim, 5000);
4166                        tcpm_set_charge(port, true);
4167                        tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
4168                        break;
4169                }
4170                /*
4171                 * For DRP, timeouts differ. Also, handling is supposed to be
4172                 * different and much more complex (dead battery detection;
4173                 * see USB power delivery specification, section 8.3.3.6.1.5.1).
4174                 */
4175                tcpm_set_state(port, hard_reset_state(port),
4176                               port->port_type == TYPEC_PORT_DRP ?
4177                                        PD_T_DB_DETECT : PD_T_NO_RESPONSE);
4178                break;
4179        case SNK_DISCOVERY_DEBOUNCE:
4180                tcpm_set_state(port, SNK_DISCOVERY_DEBOUNCE_DONE,
4181                               PD_T_CC_DEBOUNCE);
4182                break;
4183        case SNK_DISCOVERY_DEBOUNCE_DONE:
4184                if (!tcpm_port_is_disconnected(port) &&
4185                    tcpm_port_is_sink(port) &&
4186                    ktime_after(port->delayed_runtime, ktime_get())) {
4187                        tcpm_set_state(port, SNK_DISCOVERY,
4188                                       ktime_to_ms(ktime_sub(port->delayed_runtime, ktime_get())));
4189                        break;
4190                }
4191                tcpm_set_state(port, unattached_state(port), 0);
4192                break;
4193        case SNK_WAIT_CAPABILITIES:
4194                ret = port->tcpc->set_pd_rx(port->tcpc, true);
4195                if (ret < 0) {
4196                        tcpm_set_state(port, SNK_READY, 0);
4197                        break;
4198                }
4199                /*
4200                 * If VBUS has never been low, and we time out waiting
4201                 * for source cap, try a soft reset first, in case we
4202                 * were already in a stable contract before this boot.
4203                 * Do this only once.
4204                 */
4205                if (port->vbus_never_low) {
4206                        port->vbus_never_low = false;
4207                        tcpm_set_state(port, SNK_SOFT_RESET,
4208                                       PD_T_SINK_WAIT_CAP);
4209                } else {
4210                        tcpm_set_state(port, hard_reset_state(port),
4211                                       PD_T_SINK_WAIT_CAP);
4212                }
4213                break;
4214        case SNK_NEGOTIATE_CAPABILITIES:
4215                port->pd_capable = true;
4216                tcpm_set_partner_usb_comm_capable(port,
4217                                                  !!(port->source_caps[0] & PDO_FIXED_USB_COMM));
4218                port->hard_reset_count = 0;
4219                ret = tcpm_pd_send_request(port);
4220                if (ret < 0) {
4221                        /* Restore back to the original state */
4222                        tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
4223                                                               port->pps_data.active,
4224                                                               port->supply_voltage);
4225                        /* Let the Source send capabilities again. */
4226                        tcpm_set_state(port, SNK_WAIT_CAPABILITIES, 0);
4227                } else {
4228                        tcpm_set_state_cond(port, hard_reset_state(port),
4229                                            PD_T_SENDER_RESPONSE);
4230                }
4231                break;
4232        case SNK_NEGOTIATE_PPS_CAPABILITIES:
4233                ret = tcpm_pd_send_pps_request(port);
4234                if (ret < 0) {
4235                        /* Restore back to the original state */
4236                        tcpm_set_auto_vbus_discharge_threshold(port, TYPEC_PWR_MODE_PD,
4237                                                               port->pps_data.active,
4238                                                               port->supply_voltage);
4239                        port->pps_status = ret;
4240                        /*
4241                         * If this was called due to updates to sink
4242                         * capabilities, and pps is no longer valid, we should
4243                         * safely fall back to a standard PDO.
4244                         */
4245                        if (port->update_sink_caps)
4246                                tcpm_set_state(port, SNK_NEGOTIATE_CAPABILITIES, 0);
4247                        else
4248                                tcpm_set_state(port, SNK_READY, 0);
4249                } else {
4250                        tcpm_set_state_cond(port, hard_reset_state(port),
4251                                            PD_T_SENDER_RESPONSE);
4252                }
4253                break;
4254        case SNK_TRANSITION_SINK:
4255                /* From the USB PD spec:
4256                 * "The Sink Shall transition to Sink Standby before a positive or
4257                 * negative voltage transition of VBUS. During Sink Standby