OSDN Git Service

f35360b9523c30148cc3af1d5c9d307731190b5f
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / drivers / usb / pd / policy_engine.c
1 /* Copyright (c) 2016-2017, Linux Foundation. All rights reserved.
2  *
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License version 2 and
5  * only version 2 as published by the Free Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  */
12
13 #include <linux/completion.h>
14 #include <linux/delay.h>
15 #include <linux/hrtimer.h>
16 #include <linux/ipc_logging.h>
17 #include <linux/kernel.h>
18 #include <linux/list.h>
19 #include <linux/module.h>
20 #include <linux/of.h>
21 #include <linux/of_platform.h>
22 #include <linux/power_supply.h>
23 #include <linux/regulator/consumer.h>
24 #include <linux/slab.h>
25 #include <linux/spinlock.h>
26 #include <linux/workqueue.h>
27 #include <linux/extcon.h>
28 #include <linux/usb/class-dual-role.h>
29 #include <linux/usb/usbpd.h>
30 #include "usbpd.h"
31
32 enum usbpd_state {
33         PE_UNKNOWN,
34         PE_ERROR_RECOVERY,
35         PE_SRC_DISABLED,
36         PE_SRC_STARTUP,
37         PE_SRC_SEND_CAPABILITIES,
38         PE_SRC_SEND_CAPABILITIES_WAIT, /* substate to wait for Request */
39         PE_SRC_NEGOTIATE_CAPABILITY,
40         PE_SRC_TRANSITION_SUPPLY,
41         PE_SRC_READY,
42         PE_SRC_HARD_RESET,
43         PE_SRC_SOFT_RESET,
44         PE_SRC_SEND_SOFT_RESET,
45         PE_SRC_DISCOVERY,
46         PE_SRC_TRANSITION_TO_DEFAULT,
47         PE_SNK_STARTUP,
48         PE_SNK_DISCOVERY,
49         PE_SNK_WAIT_FOR_CAPABILITIES,
50         PE_SNK_EVALUATE_CAPABILITY,
51         PE_SNK_SELECT_CAPABILITY,
52         PE_SNK_TRANSITION_SINK,
53         PE_SNK_READY,
54         PE_SNK_HARD_RESET,
55         PE_SNK_SOFT_RESET,
56         PE_SNK_SEND_SOFT_RESET,
57         PE_SNK_TRANSITION_TO_DEFAULT,
58         PE_DRS_SEND_DR_SWAP,
59         PE_PRS_SNK_SRC_SEND_SWAP,
60         PE_PRS_SNK_SRC_TRANSITION_TO_OFF,
61         PE_PRS_SNK_SRC_SOURCE_ON,
62         PE_PRS_SRC_SNK_SEND_SWAP,
63         PE_PRS_SRC_SNK_TRANSITION_TO_OFF,
64         PE_PRS_SRC_SNK_WAIT_SOURCE_ON,
65         PE_VCS_WAIT_FOR_VCONN,
66 };
67
68 static const char * const usbpd_state_strings[] = {
69         "UNKNOWN",
70         "ERROR_RECOVERY",
71         "SRC_Disabled",
72         "SRC_Startup",
73         "SRC_Send_Capabilities",
74         "SRC_Send_Capabilities (Wait for Request)",
75         "SRC_Negotiate_Capability",
76         "SRC_Transition_Supply",
77         "SRC_Ready",
78         "SRC_Hard_Reset",
79         "SRC_Soft_Reset",
80         "SRC_Send_Soft_Reset",
81         "SRC_Discovery",
82         "SRC_Transition_to_default",
83         "SNK_Startup",
84         "SNK_Discovery",
85         "SNK_Wait_for_Capabilities",
86         "SNK_Evaluate_Capability",
87         "SNK_Select_Capability",
88         "SNK_Transition_Sink",
89         "SNK_Ready",
90         "SNK_Hard_Reset",
91         "SNK_Soft_Reset",
92         "SNK_Send_Soft_Reset",
93         "SNK_Transition_to_default",
94         "DRS_Send_DR_Swap",
95         "PRS_SNK_SRC_Send_Swap",
96         "PRS_SNK_SRC_Transition_to_off",
97         "PRS_SNK_SRC_Source_on",
98         "PRS_SRC_SNK_Send_Swap",
99         "PRS_SRC_SNK_Transition_to_off",
100         "PRS_SRC_SNK_Wait_Source_on",
101         "VCS_Wait_for_VCONN",
102 };
103
104 enum usbpd_control_msg_type {
105         MSG_RESERVED = 0,
106         MSG_GOODCRC,
107         MSG_GOTOMIN,
108         MSG_ACCEPT,
109         MSG_REJECT,
110         MSG_PING,
111         MSG_PS_RDY,
112         MSG_GET_SOURCE_CAP,
113         MSG_GET_SINK_CAP,
114         MSG_DR_SWAP,
115         MSG_PR_SWAP,
116         MSG_VCONN_SWAP,
117         MSG_WAIT,
118         MSG_SOFT_RESET,
119 };
120
121 enum usbpd_data_msg_type {
122         MSG_SOURCE_CAPABILITIES = 1,
123         MSG_REQUEST,
124         MSG_BIST,
125         MSG_SINK_CAPABILITIES,
126         MSG_VDM = 0xF,
127 };
128
129 enum vdm_state {
130         VDM_NONE,
131         DISCOVERED_ID,
132         DISCOVERED_SVIDS,
133         DISCOVERED_MODES,
134         MODE_ENTERED,
135         MODE_EXITED,
136 };
137
138 static void *usbpd_ipc_log;
139 #define usbpd_dbg(dev, fmt, ...) do { \
140         ipc_log_string(usbpd_ipc_log, "%s: %s: " fmt, dev_name(dev), __func__, \
141                         ##__VA_ARGS__); \
142         dev_dbg(dev, fmt, ##__VA_ARGS__); \
143         } while (0)
144
145 #define usbpd_info(dev, fmt, ...) do { \
146         ipc_log_string(usbpd_ipc_log, "%s: %s: " fmt, dev_name(dev), __func__, \
147                         ##__VA_ARGS__); \
148         dev_info(dev, fmt, ##__VA_ARGS__); \
149         } while (0)
150
151 #define usbpd_warn(dev, fmt, ...) do { \
152         ipc_log_string(usbpd_ipc_log, "%s: %s: " fmt, dev_name(dev), __func__, \
153                         ##__VA_ARGS__); \
154         dev_warn(dev, fmt, ##__VA_ARGS__); \
155         } while (0)
156
157 #define usbpd_err(dev, fmt, ...) do { \
158         ipc_log_string(usbpd_ipc_log, "%s: %s: " fmt, dev_name(dev), __func__, \
159                         ##__VA_ARGS__); \
160         dev_err(dev, fmt, ##__VA_ARGS__); \
161         } while (0)
162
163 #define NUM_LOG_PAGES           10
164
165 /* Timeouts (in ms) */
166 #define ERROR_RECOVERY_TIME     25
167 #define SENDER_RESPONSE_TIME    26
168 #define SINK_WAIT_CAP_TIME      500
169 #define PS_TRANSITION_TIME      450
170 #define SRC_CAP_TIME            120
171 #define SRC_TRANSITION_TIME     25
172 #define SRC_RECOVER_TIME        750
173 #define PS_HARD_RESET_TIME      25
174 #define PS_SOURCE_ON            400
175 #define PS_SOURCE_OFF           750
176 #define SWAP_SOURCE_START_TIME  20
177 #define VDM_BUSY_TIME           50
178 #define VCONN_ON_TIME           100
179
180 /* tPSHardReset + tSafe0V */
181 #define SNK_HARD_RESET_VBUS_OFF_TIME    (35 + 650)
182
183 /* tSrcRecover + tSrcTurnOn */
184 #define SNK_HARD_RESET_VBUS_ON_TIME     (1000 + 275)
185
186 #define PD_CAPS_COUNT           50
187
188 #define PD_MAX_MSG_ID           7
189
190 #define PD_MSG_HDR(type, dr, pr, id, cnt, rev) \
191         (((type) & 0xF) | ((dr) << 5) | (rev << 6) | \
192          ((pr) << 8) | ((id) << 9) | ((cnt) << 12))
193 #define PD_MSG_HDR_COUNT(hdr) (((hdr) >> 12) & 7)
194 #define PD_MSG_HDR_TYPE(hdr) ((hdr) & 0xF)
195 #define PD_MSG_HDR_ID(hdr) (((hdr) >> 9) & 7)
196 #define PD_MSG_HDR_REV(hdr) (((hdr) >> 6) & 3)
197
198 #define PD_RDO_FIXED(obj, gb, mismatch, usb_comm, no_usb_susp, curr1, curr2) \
199                 (((obj) << 28) | ((gb) << 27) | ((mismatch) << 26) | \
200                  ((usb_comm) << 25) | ((no_usb_susp) << 24) | \
201                  ((curr1) << 10) | (curr2))
202
203 #define PD_RDO_AUGMENTED(obj, mismatch, usb_comm, no_usb_susp, volt, curr) \
204                 (((obj) << 28) | ((mismatch) << 26) | ((usb_comm) << 25) | \
205                  ((no_usb_susp) << 24) | ((volt) << 9) | (curr))
206
207 #define PD_RDO_OBJ_POS(rdo)             ((rdo) >> 28 & 7)
208 #define PD_RDO_GIVEBACK(rdo)            ((rdo) >> 27 & 1)
209 #define PD_RDO_MISMATCH(rdo)            ((rdo) >> 26 & 1)
210 #define PD_RDO_USB_COMM(rdo)            ((rdo) >> 25 & 1)
211 #define PD_RDO_NO_USB_SUSP(rdo)         ((rdo) >> 24 & 1)
212 #define PD_RDO_FIXED_CURR(rdo)          ((rdo) >> 10 & 0x3FF)
213 #define PD_RDO_FIXED_CURR_MINMAX(rdo)   ((rdo) & 0x3FF)
214 #define PD_RDO_PROG_VOLTAGE(rdo)        ((rdo) >> 9 & 0x7FF)
215 #define PD_RDO_PROG_CURR(rdo)           ((rdo) & 0x7F)
216
217 #define PD_SRC_PDO_TYPE(pdo)            (((pdo) >> 30) & 3)
218 #define PD_SRC_PDO_TYPE_FIXED           0
219 #define PD_SRC_PDO_TYPE_BATTERY         1
220 #define PD_SRC_PDO_TYPE_VARIABLE        2
221 #define PD_SRC_PDO_TYPE_AUGMENTED       3
222
223 #define PD_SRC_PDO_FIXED_PR_SWAP(pdo)           (((pdo) >> 29) & 1)
224 #define PD_SRC_PDO_FIXED_USB_SUSP(pdo)          (((pdo) >> 28) & 1)
225 #define PD_SRC_PDO_FIXED_EXT_POWERED(pdo)       (((pdo) >> 27) & 1)
226 #define PD_SRC_PDO_FIXED_USB_COMM(pdo)          (((pdo) >> 26) & 1)
227 #define PD_SRC_PDO_FIXED_DR_SWAP(pdo)           (((pdo) >> 25) & 1)
228 #define PD_SRC_PDO_FIXED_PEAK_CURR(pdo)         (((pdo) >> 20) & 3)
229 #define PD_SRC_PDO_FIXED_VOLTAGE(pdo)           (((pdo) >> 10) & 0x3FF)
230 #define PD_SRC_PDO_FIXED_MAX_CURR(pdo)          ((pdo) & 0x3FF)
231
232 #define PD_SRC_PDO_VAR_BATT_MAX_VOLT(pdo)       (((pdo) >> 20) & 0x3FF)
233 #define PD_SRC_PDO_VAR_BATT_MIN_VOLT(pdo)       (((pdo) >> 10) & 0x3FF)
234 #define PD_SRC_PDO_VAR_BATT_MAX(pdo)            ((pdo) & 0x3FF)
235
236 #define PD_APDO_PPS(pdo)                        (((pdo) >> 28) & 3)
237 #define PD_APDO_MAX_VOLT(pdo)                   (((pdo) >> 17) & 0xFF)
238 #define PD_APDO_MIN_VOLT(pdo)                   (((pdo) >> 8) & 0xFF)
239 #define PD_APDO_MAX_CURR(pdo)                   ((pdo) & 0x7F)
240
241 /* Vendor Defined Messages */
242 #define MAX_CRC_RECEIVE_TIME    9 /* ~(2 * tReceive_max(1.1ms) * # retry 4) */
243 #define MAX_VDM_RESPONSE_TIME   60 /* 2 * tVDMSenderResponse_max(30ms) */
244 #define MAX_VDM_BUSY_TIME       100 /* 2 * tVDMBusy (50ms) */
245
246 #define PD_SNK_PDO_FIXED(prs, hc, uc, usb_comm, drs, volt, curr) \
247         (((prs) << 29) | ((hc) << 28) | ((uc) << 27) | ((usb_comm) << 26) | \
248          ((drs) << 25) | ((volt) << 10) | (curr))
249
250 /* VDM header is the first 32-bit object following the 16-bit PD header */
251 #define VDM_HDR_SVID(hdr)       ((hdr) >> 16)
252 #define VDM_IS_SVDM(hdr)        ((hdr) & 0x8000)
253 #define SVDM_HDR_OBJ_POS(hdr)   (((hdr) >> 8) & 0x7)
254 #define SVDM_HDR_CMD_TYPE(hdr)  (((hdr) >> 6) & 0x3)
255 #define SVDM_HDR_CMD(hdr)       ((hdr) & 0x1f)
256
257 #define SVDM_HDR(svid, ver, obj, cmd_type, cmd) \
258         (((svid) << 16) | (1 << 15) | ((ver) << 13) \
259         | ((obj) << 8) | ((cmd_type) << 6) | (cmd))
260
261 /* discover id response vdo bit fields */
262 #define ID_HDR_USB_HOST         BIT(31)
263 #define ID_HDR_USB_DEVICE       BIT(30)
264 #define ID_HDR_MODAL_OPR        BIT(26)
265 #define ID_HDR_PRODUCT_TYPE(n)  ((n) >> 27)
266 #define ID_HDR_PRODUCT_PER_MASK (2 << 27)
267 #define ID_HDR_PRODUCT_HUB      1
268 #define ID_HDR_PRODUCT_PER      2
269 #define ID_HDR_PRODUCT_AMA      5
270 #define ID_HDR_VID              0x05c6 /* qcom */
271 #define PROD_VDO_PID            0x0a00 /* TBD */
272
273 static bool check_vsafe0v = true;
274 module_param(check_vsafe0v, bool, S_IRUSR | S_IWUSR);
275
276 static int min_sink_current = 900;
277 module_param(min_sink_current, int, S_IRUSR | S_IWUSR);
278
279 static const u32 default_src_caps[] = { 0x36019096 };   /* VSafe5V @ 1.5A */
280 static const u32 default_snk_caps[] = { 0x2601912C };   /* VSafe5V @ 3A */
281
282 struct vdm_tx {
283         u32                     data[7];
284         int                     size;
285 };
286
287 struct rx_msg {
288         u8                      type;
289         u8                      len;
290         u32                     payload[7];
291         struct list_head        entry;
292 };
293
294 #define IS_DATA(m, t) ((m) && ((m)->len) && ((m)->type == (t)))
295 #define IS_CTRL(m, t) ((m) && !((m)->len) && ((m)->type == (t)))
296
297 struct usbpd {
298         struct device           dev;
299         struct workqueue_struct *wq;
300         struct work_struct      sm_work;
301         struct hrtimer          timer;
302         bool                    sm_queued;
303
304         struct extcon_dev       *extcon;
305
306         enum usbpd_state        current_state;
307         bool                    hard_reset_recvd;
308         struct list_head        rx_q;
309         spinlock_t              rx_lock;
310
311         u32                     received_pdos[7];
312         u16                     src_cap_id;
313         u8                      selected_pdo;
314         u8                      requested_pdo;
315         u32                     rdo;    /* can be either source or sink */
316         int                     current_voltage;        /* uV */
317         int                     requested_voltage;      /* uV */
318         int                     requested_current;      /* mA */
319         bool                    pd_connected;
320         bool                    in_explicit_contract;
321         bool                    peer_usb_comm;
322         bool                    peer_pr_swap;
323         bool                    peer_dr_swap;
324
325         u32                     sink_caps[7];
326         int                     num_sink_caps;
327
328         struct power_supply     *usb_psy;
329         struct notifier_block   psy_nb;
330
331         enum power_supply_typec_mode typec_mode;
332         enum power_supply_type  psy_type;
333         enum power_supply_typec_power_role forced_pr;
334         bool                    vbus_present;
335
336         enum pd_spec_rev        spec_rev;
337         enum data_role          current_dr;
338         enum power_role         current_pr;
339         bool                    in_pr_swap;
340         bool                    pd_phy_opened;
341         bool                    send_request;
342         struct completion       is_ready;
343
344         struct mutex            swap_lock;
345         struct dual_role_phy_instance   *dual_role;
346         struct dual_role_phy_desc       dr_desc;
347         bool                    send_pr_swap;
348         bool                    send_dr_swap;
349
350         struct regulator        *vbus;
351         struct regulator        *vconn;
352         bool                    vbus_enabled;
353         bool                    vconn_enabled;
354         bool                    vconn_is_external;
355
356         u8                      tx_msgid;
357         u8                      rx_msgid;
358         int                     caps_count;
359         int                     hard_reset_count;
360
361         enum vdm_state          vdm_state;
362         u16                     *discovered_svids;
363         int                     num_svids;
364         struct vdm_tx           *vdm_tx;
365         struct vdm_tx           *vdm_tx_retry;
366         struct list_head        svid_handlers;
367
368         struct list_head        instance;
369 };
370
371 static LIST_HEAD(_usbpd);       /* useful for debugging */
372
373 static const unsigned int usbpd_extcon_cable[] = {
374         EXTCON_USB,
375         EXTCON_USB_HOST,
376         EXTCON_USB_CC,
377         EXTCON_USB_SPEED,
378         EXTCON_USB_TYPEC_MED_HIGH_CURRENT,
379         EXTCON_NONE,
380 };
381
382 /* EXTCON_USB and EXTCON_USB_HOST are mutually exclusive */
383 static const u32 usbpd_extcon_exclusive[] = {0x3, 0};
384
385 enum plug_orientation usbpd_get_plug_orientation(struct usbpd *pd)
386 {
387         int ret;
388         union power_supply_propval val;
389
390         ret = power_supply_get_property(pd->usb_psy,
391                 POWER_SUPPLY_PROP_TYPEC_CC_ORIENTATION, &val);
392         if (ret)
393                 return ORIENTATION_NONE;
394
395         return val.intval;
396 }
397 EXPORT_SYMBOL(usbpd_get_plug_orientation);
398
399 static inline void stop_usb_host(struct usbpd *pd)
400 {
401         extcon_set_cable_state_(pd->extcon, EXTCON_USB_HOST, 0);
402 }
403
404 static inline void start_usb_host(struct usbpd *pd, bool ss)
405 {
406         enum plug_orientation cc = usbpd_get_plug_orientation(pd);
407
408         extcon_set_cable_state_(pd->extcon, EXTCON_USB_CC,
409                         cc == ORIENTATION_CC2);
410         extcon_set_cable_state_(pd->extcon, EXTCON_USB_SPEED, ss);
411         extcon_set_cable_state_(pd->extcon, EXTCON_USB_HOST, 1);
412 }
413
414 static inline void stop_usb_peripheral(struct usbpd *pd)
415 {
416         extcon_set_cable_state_(pd->extcon, EXTCON_USB, 0);
417 }
418
419 static inline void start_usb_peripheral(struct usbpd *pd)
420 {
421         enum plug_orientation cc = usbpd_get_plug_orientation(pd);
422
423         extcon_set_cable_state_(pd->extcon, EXTCON_USB_CC,
424                         cc == ORIENTATION_CC2);
425         extcon_set_cable_state_(pd->extcon, EXTCON_USB_SPEED, 1);
426         extcon_set_cable_state_(pd->extcon, EXTCON_USB_TYPEC_MED_HIGH_CURRENT,
427                 pd->typec_mode > POWER_SUPPLY_TYPEC_SOURCE_DEFAULT ? 1 : 0);
428         extcon_set_cable_state_(pd->extcon, EXTCON_USB, 1);
429 }
430
431 static int set_power_role(struct usbpd *pd, enum power_role pr)
432 {
433         union power_supply_propval val = {0};
434
435         switch (pr) {
436         case PR_NONE:
437                 val.intval = POWER_SUPPLY_TYPEC_PR_NONE;
438                 break;
439         case PR_SINK:
440                 val.intval = POWER_SUPPLY_TYPEC_PR_SINK;
441                 break;
442         case PR_SRC:
443                 val.intval = POWER_SUPPLY_TYPEC_PR_SOURCE;
444                 break;
445         }
446
447         return power_supply_set_property(pd->usb_psy,
448                         POWER_SUPPLY_PROP_TYPEC_POWER_ROLE, &val);
449 }
450
451 static struct usbpd_svid_handler *find_svid_handler(struct usbpd *pd, u16 svid)
452 {
453         struct usbpd_svid_handler *handler;
454
455         list_for_each_entry(handler, &pd->svid_handlers, entry)
456                 if (svid == handler->svid)
457                         return handler;
458
459         return NULL;
460 }
461
462 /* Reset protocol layer */
463 static inline void pd_reset_protocol(struct usbpd *pd)
464 {
465         /*
466          * first Rx ID should be 0; set this to a sentinel of -1 so that in
467          * phy_msg_received() we can check if we had seen it before.
468          */
469         pd->rx_msgid = -1;
470         pd->tx_msgid = 0;
471         pd->send_request = false;
472         pd->send_pr_swap = false;
473         pd->send_dr_swap = false;
474 }
475
476 static int pd_send_msg(struct usbpd *pd, u8 hdr_type, const u32 *data,
477                 size_t num_data, enum pd_msg_type type)
478 {
479         int ret;
480         u16 hdr;
481
482         hdr = PD_MSG_HDR(hdr_type, pd->current_dr, pd->current_pr,
483                         pd->tx_msgid, num_data, pd->spec_rev);
484         ret = pd_phy_write(hdr, (u8 *)data, num_data * sizeof(u32), type, 15);
485         /* TODO figure out timeout. based on tReceive=1.1ms x nRetryCount? */
486
487         /* MessageID incremented regardless of Tx error */
488         pd->tx_msgid = (pd->tx_msgid + 1) & PD_MAX_MSG_ID;
489
490         if (ret < 0)
491                 return ret;
492         else if (ret != num_data * sizeof(u32))
493                 return -EIO;
494         return 0;
495 }
496
497 static int pd_select_pdo(struct usbpd *pd, int pdo_pos, int uv, int ua)
498 {
499         int curr;
500         int max_current;
501         bool mismatch = false;
502         u8 type;
503         u32 pdo = pd->received_pdos[pdo_pos - 1];
504
505         type = PD_SRC_PDO_TYPE(pdo);
506         if (type == PD_SRC_PDO_TYPE_FIXED) {
507                 curr = max_current = PD_SRC_PDO_FIXED_MAX_CURR(pdo) * 10;
508
509                 /*
510                  * Check if the PDO has enough current, otherwise set the
511                  * Capability Mismatch flag
512                  */
513                 if (curr < min_sink_current) {
514                         mismatch = true;
515                         max_current = min_sink_current;
516                 }
517
518                 pd->requested_voltage =
519                         PD_SRC_PDO_FIXED_VOLTAGE(pdo) * 50 * 1000;
520                 pd->rdo = PD_RDO_FIXED(pdo_pos, 0, mismatch, 1, 1, curr / 10,
521                                 max_current / 10);
522         } else if (type == PD_SRC_PDO_TYPE_AUGMENTED) {
523                 if ((uv / 100000) > PD_APDO_MAX_VOLT(pdo) ||
524                         (uv / 100000) < PD_APDO_MIN_VOLT(pdo) ||
525                         (ua / 50000) > PD_APDO_MAX_CURR(pdo) || (ua < 0)) {
526                         usbpd_err(&pd->dev, "uv (%d) and ua (%d) out of range of APDO\n",
527                                         uv, ua);
528                         return -EINVAL;
529                 }
530
531                 curr = ua / 1000;
532                 pd->requested_voltage = uv;
533                 pd->rdo = PD_RDO_AUGMENTED(pdo_pos, mismatch, 1, 1,
534                                 uv / 20000, ua / 50000);
535         } else {
536                 usbpd_err(&pd->dev, "Only Fixed or Programmable PDOs supported\n");
537                 return -ENOTSUPP;
538         }
539
540         /* Can't sink more than 5V if VCONN is sourced from the VBUS input */
541         if (pd->vconn_enabled && !pd->vconn_is_external &&
542                         pd->requested_voltage > 5000000)
543                 return -ENOTSUPP;
544
545         pd->requested_current = curr;
546         pd->requested_pdo = pdo_pos;
547
548         return 0;
549 }
550
551 static int pd_eval_src_caps(struct usbpd *pd)
552 {
553         union power_supply_propval val;
554         u32 first_pdo = pd->received_pdos[0];
555
556         if (PD_SRC_PDO_TYPE(first_pdo) != PD_SRC_PDO_TYPE_FIXED) {
557                 usbpd_err(&pd->dev, "First src_cap invalid! %08x\n", first_pdo);
558                 return -EINVAL;
559         }
560
561         pd->peer_usb_comm = PD_SRC_PDO_FIXED_USB_COMM(first_pdo);
562         pd->peer_pr_swap = PD_SRC_PDO_FIXED_PR_SWAP(first_pdo);
563         pd->peer_dr_swap = PD_SRC_PDO_FIXED_DR_SWAP(first_pdo);
564
565         val.intval = PD_SRC_PDO_FIXED_USB_SUSP(first_pdo);
566         power_supply_set_property(pd->usb_psy,
567                         POWER_SUPPLY_PROP_PD_USB_SUSPEND_SUPPORTED, &val);
568
569         /* Select the first PDO (vSafe5V) immediately. */
570         pd_select_pdo(pd, 1, 0, 0);
571
572         return 0;
573 }
574
575 static void pd_send_hard_reset(struct usbpd *pd)
576 {
577         usbpd_dbg(&pd->dev, "send hard reset");
578
579         /* Force CC logic to source/sink to keep Rp/Rd unchanged */
580         set_power_role(pd, pd->current_pr);
581         pd->hard_reset_count++;
582         pd_phy_signal(HARD_RESET_SIG, 5); /* tHardResetComplete */
583         pd->in_pr_swap = false;
584 }
585
586 static void kick_sm(struct usbpd *pd, int ms)
587 {
588         pm_stay_awake(&pd->dev);
589         pd->sm_queued = true;
590
591         if (ms)
592                 hrtimer_start(&pd->timer, ms_to_ktime(ms), HRTIMER_MODE_REL);
593         else
594                 queue_work(pd->wq, &pd->sm_work);
595 }
596
597 static void phy_sig_received(struct usbpd *pd, enum pd_sig_type type)
598 {
599         if (type != HARD_RESET_SIG) {
600                 usbpd_err(&pd->dev, "invalid signal (%d) received\n", type);
601                 return;
602         }
603
604         usbpd_dbg(&pd->dev, "hard reset received\n");
605
606         /* Force CC logic to source/sink to keep Rp/Rd unchanged */
607         set_power_role(pd, pd->current_pr);
608         pd->hard_reset_recvd = true;
609         kick_sm(pd, 0);
610 }
611
612 static void phy_msg_received(struct usbpd *pd, enum pd_msg_type type,
613                 u8 *buf, size_t len)
614 {
615         struct rx_msg *rx_msg;
616         unsigned long flags;
617         u16 header;
618
619         if (type != SOP_MSG) {
620                 usbpd_err(&pd->dev, "invalid msg type (%d) received; only SOP supported\n",
621                                 type);
622                 return;
623         }
624
625         if (len < 2) {
626                 usbpd_err(&pd->dev, "invalid message received, len=%zd\n", len);
627                 return;
628         }
629
630         header = *((u16 *)buf);
631         buf += sizeof(u16);
632         len -= sizeof(u16);
633
634         if (len % 4 != 0) {
635                 usbpd_err(&pd->dev, "len=%zd not multiple of 4\n", len);
636                 return;
637         }
638
639         /* if MSGID already seen, discard */
640         if (PD_MSG_HDR_ID(header) == pd->rx_msgid &&
641                         PD_MSG_HDR_TYPE(header) != MSG_SOFT_RESET) {
642                 usbpd_dbg(&pd->dev, "MessageID already seen, discarding\n");
643                 return;
644         }
645
646         pd->rx_msgid = PD_MSG_HDR_ID(header);
647
648         /* discard Pings */
649         if (PD_MSG_HDR_TYPE(header) == MSG_PING && !len)
650                 return;
651
652         /* check header's count field to see if it matches len */
653         if (PD_MSG_HDR_COUNT(header) != (len / 4)) {
654                 usbpd_err(&pd->dev, "header count (%d) mismatch, len=%zd\n",
655                                 PD_MSG_HDR_COUNT(header), len);
656                 return;
657         }
658
659         /* if spec rev differs (i.e. is older), update PHY */
660         if (PD_MSG_HDR_REV(header) < pd->spec_rev) {
661                 pd->spec_rev = PD_MSG_HDR_REV(header);
662                 pd_phy_update_spec_rev(pd->spec_rev);
663         }
664
665         rx_msg = kzalloc(sizeof(*rx_msg), GFP_KERNEL);
666         if (!rx_msg)
667                 return;
668
669         rx_msg->type = PD_MSG_HDR_TYPE(header);
670         rx_msg->len = PD_MSG_HDR_COUNT(header);
671         memcpy(&rx_msg->payload, buf, min(len, sizeof(rx_msg->payload)));
672
673         spin_lock_irqsave(&pd->rx_lock, flags);
674         list_add_tail(&rx_msg->entry, &pd->rx_q);
675         spin_unlock_irqrestore(&pd->rx_lock, flags);
676
677         usbpd_dbg(&pd->dev, "received message: type(%d) len(%d)\n",
678                         rx_msg->type, rx_msg->len);
679
680         kick_sm(pd, 0);
681 }
682
683 static void phy_shutdown(struct usbpd *pd)
684 {
685         usbpd_dbg(&pd->dev, "shutdown");
686 }
687
688 static enum hrtimer_restart pd_timeout(struct hrtimer *timer)
689 {
690         struct usbpd *pd = container_of(timer, struct usbpd, timer);
691
692         usbpd_dbg(&pd->dev, "timeout");
693         queue_work(pd->wq, &pd->sm_work);
694
695         return HRTIMER_NORESTART;
696 }
697
698 /* Enters new state and executes actions on entry */
699 static void usbpd_set_state(struct usbpd *pd, enum usbpd_state next_state)
700 {
701         struct pd_phy_params phy_params = {
702                 .signal_cb              = phy_sig_received,
703                 .msg_rx_cb              = phy_msg_received,
704                 .shutdown_cb            = phy_shutdown,
705                 .frame_filter_val       = FRAME_FILTER_EN_SOP |
706                                           FRAME_FILTER_EN_HARD_RESET,
707                 .spec_rev               = USBPD_REV_20,
708         };
709         union power_supply_propval val = {0};
710         unsigned long flags;
711         int ret;
712
713         usbpd_dbg(&pd->dev, "%s -> %s\n",
714                         usbpd_state_strings[pd->current_state],
715                         usbpd_state_strings[next_state]);
716
717         pd->current_state = next_state;
718
719         switch (next_state) {
720         case PE_ERROR_RECOVERY: /* perform hard disconnect/reconnect */
721                 pd->in_pr_swap = false;
722                 pd->current_pr = PR_NONE;
723                 set_power_role(pd, PR_NONE);
724                 pd->typec_mode = POWER_SUPPLY_TYPEC_NONE;
725                 kick_sm(pd, 0);
726                 break;
727
728         /* Source states */
729         case PE_SRC_STARTUP:
730                 if (pd->current_dr == DR_NONE) {
731                         pd->current_dr = DR_DFP;
732                         /*
733                          * Defer starting USB host mode until PE_SRC_READY or
734                          * when PE_SRC_SEND_CAPABILITIES fails
735                          */
736                 }
737
738                 dual_role_instance_changed(pd->dual_role);
739
740                 /* Set CC back to DRP toggle for the next disconnect */
741                 val.intval = POWER_SUPPLY_TYPEC_PR_DUAL;
742                 power_supply_set_property(pd->usb_psy,
743                                 POWER_SUPPLY_PROP_TYPEC_POWER_ROLE, &val);
744
745                 /* support only PD 2.0 as a source */
746                 pd->spec_rev = USBPD_REV_20;
747                 pd_reset_protocol(pd);
748
749                 if (!pd->in_pr_swap) {
750                         if (pd->pd_phy_opened) {
751                                 pd_phy_close();
752                                 pd->pd_phy_opened = false;
753                         }
754
755                         phy_params.data_role = pd->current_dr;
756                         phy_params.power_role = pd->current_pr;
757                         phy_params.spec_rev = pd->spec_rev;
758
759                         ret = pd_phy_open(&phy_params);
760                         if (ret) {
761                                 WARN_ON_ONCE(1);
762                                 usbpd_err(&pd->dev, "error opening PD PHY %d\n",
763                                                 ret);
764                                 pd->current_state = PE_UNKNOWN;
765                                 return;
766                         }
767
768                         pd->pd_phy_opened = true;
769                 } else {
770                         pd_phy_update_spec_rev(pd->spec_rev);
771                 }
772
773                 pd->current_state = PE_SRC_SEND_CAPABILITIES;
774                 if (pd->in_pr_swap) {
775                         kick_sm(pd, SWAP_SOURCE_START_TIME);
776                         pd->in_pr_swap = false;
777                         break;
778                 }
779
780                 /* fall-through */
781
782         case PE_SRC_SEND_CAPABILITIES:
783                 kick_sm(pd, 0);
784                 break;
785
786         case PE_SRC_NEGOTIATE_CAPABILITY:
787                 if (PD_RDO_OBJ_POS(pd->rdo) != 1 ||
788                         PD_RDO_FIXED_CURR(pd->rdo) >
789                                 PD_SRC_PDO_FIXED_MAX_CURR(*default_src_caps) ||
790                         PD_RDO_FIXED_CURR_MINMAX(pd->rdo) >
791                                 PD_SRC_PDO_FIXED_MAX_CURR(*default_src_caps)) {
792                         /* send Reject */
793                         ret = pd_send_msg(pd, MSG_REJECT, NULL, 0, SOP_MSG);
794                         if (ret) {
795                                 usbpd_err(&pd->dev, "Error sending Reject\n");
796                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
797                                 break;
798                         }
799
800                         usbpd_err(&pd->dev, "Invalid request: %08x\n", pd->rdo);
801
802                         if (pd->in_explicit_contract)
803                                 usbpd_set_state(pd, PE_SRC_READY);
804                         else
805                                 /*
806                                  * bypass PE_SRC_Capability_Response and
807                                  * PE_SRC_Wait_New_Capabilities in this
808                                  * implementation for simplicity.
809                                  */
810                                 usbpd_set_state(pd, PE_SRC_SEND_CAPABILITIES);
811                         break;
812                 }
813
814                 /* PE_SRC_TRANSITION_SUPPLY pseudo-state */
815                 ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
816                 if (ret) {
817                         usbpd_err(&pd->dev, "Error sending Accept\n");
818                         usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
819                         break;
820                 }
821
822                 /* tSrcTransition required after ACCEPT */
823                 usleep_range(SRC_TRANSITION_TIME * USEC_PER_MSEC,
824                                 (SRC_TRANSITION_TIME + 5) * USEC_PER_MSEC);
825
826                 /*
827                  * Normally a voltage change should occur within tSrcReady
828                  * but since we only support VSafe5V there is nothing more to
829                  * prepare from the power supply so send PS_RDY right away.
830                  */
831                 ret = pd_send_msg(pd, MSG_PS_RDY, NULL, 0, SOP_MSG);
832                 if (ret) {
833                         usbpd_err(&pd->dev, "Error sending PS_RDY\n");
834                         usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
835                         break;
836                 }
837
838                 usbpd_set_state(pd, PE_SRC_READY);
839                 break;
840
841         case PE_SRC_READY:
842                 pd->in_explicit_contract = true;
843                 if (pd->current_dr == DR_DFP) {
844                         /* don't start USB host until after SVDM discovery */
845                         if (pd->vdm_state == VDM_NONE)
846                                 usbpd_send_svdm(pd, USBPD_SID,
847                                                 USBPD_SVDM_DISCOVER_IDENTITY,
848                                                 SVDM_CMD_TYPE_INITIATOR, 0,
849                                                 NULL, 0);
850                 }
851
852                 kobject_uevent(&pd->dev.kobj, KOBJ_CHANGE);
853                 complete(&pd->is_ready);
854                 dual_role_instance_changed(pd->dual_role);
855                 break;
856
857         case PE_SRC_HARD_RESET:
858         case PE_SNK_HARD_RESET:
859                 /* hard reset may sleep; handle it in the workqueue */
860                 kick_sm(pd, 0);
861                 break;
862
863         case PE_SRC_SEND_SOFT_RESET:
864         case PE_SNK_SEND_SOFT_RESET:
865                 pd_reset_protocol(pd);
866
867                 ret = pd_send_msg(pd, MSG_SOFT_RESET, NULL, 0, SOP_MSG);
868                 if (ret) {
869                         usbpd_err(&pd->dev, "Error sending Soft Reset, do Hard Reset\n");
870                         usbpd_set_state(pd, pd->current_pr == PR_SRC ?
871                                         PE_SRC_HARD_RESET : PE_SNK_HARD_RESET);
872                         break;
873                 }
874
875                 /* wait for ACCEPT */
876                 kick_sm(pd, SENDER_RESPONSE_TIME);
877                 break;
878
879         /* Sink states */
880         case PE_SNK_STARTUP:
881                 if (pd->current_dr == DR_NONE || pd->current_dr == DR_UFP) {
882                         pd->current_dr = DR_UFP;
883
884                         if (pd->psy_type == POWER_SUPPLY_TYPE_USB ||
885                                 pd->psy_type == POWER_SUPPLY_TYPE_USB_CDP)
886                                 start_usb_peripheral(pd);
887                 }
888
889                 dual_role_instance_changed(pd->dual_role);
890
891                 ret = power_supply_get_property(pd->usb_psy,
892                                 POWER_SUPPLY_PROP_PD_ALLOWED, &val);
893                 if (ret) {
894                         usbpd_err(&pd->dev, "Unable to read USB PROP_PD_ALLOWED: %d\n",
895                                         ret);
896                         break;
897                 }
898
899                 if (!val.intval)
900                         break;
901
902                 /*
903                  * support up to PD 3.0 as a sink; if source is 2.0,
904                  * phy_msg_received() will handle the downgrade.
905                  */
906                 pd->spec_rev = USBPD_REV_30;
907                 pd_reset_protocol(pd);
908
909                 if (!pd->in_pr_swap) {
910                         if (pd->pd_phy_opened) {
911                                 pd_phy_close();
912                                 pd->pd_phy_opened = false;
913                         }
914
915                         phy_params.data_role = pd->current_dr;
916                         phy_params.power_role = pd->current_pr;
917                         phy_params.spec_rev = pd->spec_rev;
918
919                         ret = pd_phy_open(&phy_params);
920                         if (ret) {
921                                 WARN_ON_ONCE(1);
922                                 usbpd_err(&pd->dev, "error opening PD PHY %d\n",
923                                                 ret);
924                                 pd->current_state = PE_UNKNOWN;
925                                 return;
926                         }
927
928                         pd->pd_phy_opened = true;
929                 } else {
930                         pd_phy_update_spec_rev(pd->spec_rev);
931                 }
932
933                 pd->current_voltage = pd->requested_voltage = 5000000;
934                 val.intval = pd->requested_voltage; /* set max range to 5V */
935                 power_supply_set_property(pd->usb_psy,
936                                 POWER_SUPPLY_PROP_VOLTAGE_MAX, &val);
937
938                 if (!pd->vbus_present) {
939                         pd->current_state = PE_SNK_DISCOVERY;
940                         /* max time for hard reset to turn vbus back on */
941                         kick_sm(pd, SNK_HARD_RESET_VBUS_ON_TIME);
942                         break;
943                 }
944
945                 pd->current_state = PE_SNK_WAIT_FOR_CAPABILITIES;
946                 /* fall-through */
947
948         case PE_SNK_WAIT_FOR_CAPABILITIES:
949                 spin_lock_irqsave(&pd->rx_lock, flags);
950                 if (list_empty(&pd->rx_q))
951                         kick_sm(pd, SINK_WAIT_CAP_TIME);
952                 spin_unlock_irqrestore(&pd->rx_lock, flags);
953                 break;
954
955         case PE_SNK_EVALUATE_CAPABILITY:
956                 pd->pd_connected = true; /* we know peer is PD capable */
957                 pd->hard_reset_count = 0;
958
959                 /* evaluate PDOs and select one */
960                 ret = pd_eval_src_caps(pd);
961                 if (ret < 0) {
962                         usbpd_err(&pd->dev, "Invalid src_caps received. Skipping request\n");
963                         break;
964                 }
965                 pd->current_state = PE_SNK_SELECT_CAPABILITY;
966                 /* fall-through */
967
968         case PE_SNK_SELECT_CAPABILITY:
969                 ret = pd_send_msg(pd, MSG_REQUEST, &pd->rdo, 1, SOP_MSG);
970                 if (ret) {
971                         usbpd_err(&pd->dev, "Error sending Request\n");
972                         usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
973                         break;
974                 }
975
976                 /* wait for ACCEPT */
977                 kick_sm(pd, SENDER_RESPONSE_TIME);
978                 break;
979
980         case PE_SNK_TRANSITION_SINK:
981                 /* wait for PS_RDY */
982                 kick_sm(pd, PS_TRANSITION_TIME);
983                 break;
984
985         case PE_SNK_READY:
986                 pd->in_explicit_contract = true;
987                 kobject_uevent(&pd->dev.kobj, KOBJ_CHANGE);
988                 complete(&pd->is_ready);
989                 dual_role_instance_changed(pd->dual_role);
990                 break;
991
992         case PE_SNK_TRANSITION_TO_DEFAULT:
993                 if (pd->current_dr != DR_UFP) {
994                         stop_usb_host(pd);
995                         start_usb_peripheral(pd);
996                         pd->current_dr = DR_UFP;
997                         pd_phy_update_roles(pd->current_dr, pd->current_pr);
998                 }
999                 if (pd->vconn_enabled) {
1000                         regulator_disable(pd->vconn);
1001                         pd->vconn_enabled = false;
1002                 }
1003
1004                 /* max time for hard reset to turn vbus off */
1005                 kick_sm(pd, SNK_HARD_RESET_VBUS_OFF_TIME);
1006                 break;
1007
1008         case PE_PRS_SNK_SRC_TRANSITION_TO_OFF:
1009                 val.intval = pd->requested_current = 0; /* suspend charging */
1010                 power_supply_set_property(pd->usb_psy,
1011                                 POWER_SUPPLY_PROP_PD_CURRENT_MAX, &val);
1012
1013                 pd->in_explicit_contract = false;
1014
1015                 /*
1016                  * need to update PR bit in message header so that
1017                  * proper GoodCRC is sent when receiving next PS_RDY
1018                  */
1019                 pd_phy_update_roles(pd->current_dr, PR_SRC);
1020
1021                 /* wait for PS_RDY */
1022                 kick_sm(pd, PS_SOURCE_OFF);
1023                 break;
1024
1025         default:
1026                 usbpd_dbg(&pd->dev, "No action for state %s\n",
1027                                 usbpd_state_strings[pd->current_state]);
1028                 break;
1029         }
1030 }
1031
1032 int usbpd_register_svid(struct usbpd *pd, struct usbpd_svid_handler *hdlr)
1033 {
1034         if (find_svid_handler(pd, hdlr->svid)) {
1035                 usbpd_err(&pd->dev, "SVID 0x%04x already registered\n",
1036                                 hdlr->svid);
1037                 return -EINVAL;
1038         }
1039
1040         /* require connect/disconnect callbacks be implemented */
1041         if (!hdlr->connect || !hdlr->disconnect) {
1042                 usbpd_err(&pd->dev, "SVID 0x%04x connect/disconnect must be non-NULL\n",
1043                                 hdlr->svid);
1044                 return -EINVAL;
1045         }
1046
1047         usbpd_dbg(&pd->dev, "registered handler for SVID 0x%04x\n", hdlr->svid);
1048
1049         list_add_tail(&hdlr->entry, &pd->svid_handlers);
1050
1051         /* already connected with this SVID discovered? */
1052         if (pd->vdm_state >= DISCOVERED_SVIDS) {
1053                 int i;
1054
1055                 for (i = 0; i < pd->num_svids; i++) {
1056                         if (pd->discovered_svids[i] == hdlr->svid) {
1057                                 hdlr->connect(hdlr);
1058                                 hdlr->discovered = true;
1059                                 break;
1060                         }
1061                 }
1062         }
1063
1064         return 0;
1065 }
1066 EXPORT_SYMBOL(usbpd_register_svid);
1067
1068 void usbpd_unregister_svid(struct usbpd *pd, struct usbpd_svid_handler *hdlr)
1069 {
1070         list_del_init(&hdlr->entry);
1071 }
1072 EXPORT_SYMBOL(usbpd_unregister_svid);
1073
1074 int usbpd_send_vdm(struct usbpd *pd, u32 vdm_hdr, const u32 *vdos, int num_vdos)
1075 {
1076         struct vdm_tx *vdm_tx;
1077
1078         if (!pd->in_explicit_contract || pd->vdm_tx)
1079                 return -EBUSY;
1080
1081         vdm_tx = kzalloc(sizeof(*vdm_tx), GFP_KERNEL);
1082         if (!vdm_tx)
1083                 return -ENOMEM;
1084
1085         vdm_tx->data[0] = vdm_hdr;
1086         if (vdos && num_vdos)
1087                 memcpy(&vdm_tx->data[1], vdos, num_vdos * sizeof(u32));
1088         vdm_tx->size = num_vdos + 1; /* include the header */
1089
1090         /* VDM will get sent in PE_SRC/SNK_READY state handling */
1091         pd->vdm_tx = vdm_tx;
1092
1093         /* slight delay before queuing to prioritize handling of incoming VDM */
1094         kick_sm(pd, 2);
1095
1096         return 0;
1097 }
1098 EXPORT_SYMBOL(usbpd_send_vdm);
1099
1100 int usbpd_send_svdm(struct usbpd *pd, u16 svid, u8 cmd,
1101                 enum usbpd_svdm_cmd_type cmd_type, int obj_pos,
1102                 const u32 *vdos, int num_vdos)
1103 {
1104         u32 svdm_hdr = SVDM_HDR(svid, 0, obj_pos, cmd_type, cmd);
1105
1106         usbpd_dbg(&pd->dev, "VDM tx: svid:%x cmd:%x cmd_type:%x svdm_hdr:%x\n",
1107                         svid, cmd, cmd_type, svdm_hdr);
1108
1109         return usbpd_send_vdm(pd, svdm_hdr, vdos, num_vdos);
1110 }
1111 EXPORT_SYMBOL(usbpd_send_svdm);
1112
1113 static void handle_vdm_rx(struct usbpd *pd, struct rx_msg *rx_msg)
1114 {
1115         u32 vdm_hdr = rx_msg->payload[0];
1116         u32 *vdos = &rx_msg->payload[1];
1117         u16 svid = VDM_HDR_SVID(vdm_hdr);
1118         u16 *psvid;
1119         u8 i, num_vdos = rx_msg->len - 1;       /* num objects minus header */
1120         u8 cmd = SVDM_HDR_CMD(vdm_hdr);
1121         u8 cmd_type = SVDM_HDR_CMD_TYPE(vdm_hdr);
1122         bool has_dp = false;
1123         struct usbpd_svid_handler *handler;
1124
1125         usbpd_dbg(&pd->dev, "VDM rx: svid:%x cmd:%x cmd_type:%x vdm_hdr:%x\n",
1126                         svid, cmd, cmd_type, vdm_hdr);
1127
1128         /* if it's a supported SVID, pass the message to the handler */
1129         handler = find_svid_handler(pd, svid);
1130
1131         /* Unstructured VDM */
1132         if (!VDM_IS_SVDM(vdm_hdr)) {
1133                 if (handler && handler->vdm_received)
1134                         handler->vdm_received(handler, vdm_hdr, vdos, num_vdos);
1135                 return;
1136         }
1137
1138         /* if this interrupts a previous exchange, abort queued response */
1139         if (cmd_type == SVDM_CMD_TYPE_INITIATOR && pd->vdm_tx) {
1140                 usbpd_dbg(&pd->dev, "Discarding previously queued SVDM tx (SVID:0x%04x)\n",
1141                                 VDM_HDR_SVID(pd->vdm_tx->data[0]));
1142
1143                 kfree(pd->vdm_tx);
1144                 pd->vdm_tx = NULL;
1145         }
1146
1147         if (handler && handler->svdm_received) {
1148                 handler->svdm_received(handler, cmd, cmd_type, vdos, num_vdos);
1149                 return;
1150         }
1151
1152         /* Standard Discovery or unhandled messages go here */
1153         switch (cmd_type) {
1154         case SVDM_CMD_TYPE_INITIATOR:
1155                 if (svid == USBPD_SID && cmd == USBPD_SVDM_DISCOVER_IDENTITY) {
1156                         u32 tx_vdos[3] = {
1157                                 ID_HDR_USB_HOST | ID_HDR_USB_DEVICE |
1158                                         ID_HDR_PRODUCT_PER_MASK | ID_HDR_VID,
1159                                 0x0, /* TBD: Cert Stat VDO */
1160                                 (PROD_VDO_PID << 16),
1161                                 /* TBD: Get these from gadget */
1162                         };
1163
1164                         usbpd_send_svdm(pd, USBPD_SID, cmd,
1165                                         SVDM_CMD_TYPE_RESP_ACK, 0, tx_vdos, 3);
1166                 } else if (cmd != USBPD_SVDM_ATTENTION) {
1167                         usbpd_send_svdm(pd, svid, cmd, SVDM_CMD_TYPE_RESP_NAK,
1168                                         SVDM_HDR_OBJ_POS(vdm_hdr), NULL, 0);
1169                 }
1170                 break;
1171
1172         case SVDM_CMD_TYPE_RESP_ACK:
1173                 if (svid != USBPD_SID) {
1174                         usbpd_err(&pd->dev, "unhandled ACK for SVID:0x%x\n",
1175                                         svid);
1176                         break;
1177                 }
1178
1179                 switch (cmd) {
1180                 case USBPD_SVDM_DISCOVER_IDENTITY:
1181                         kfree(pd->vdm_tx_retry);
1182                         pd->vdm_tx_retry = NULL;
1183
1184                         pd->vdm_state = DISCOVERED_ID;
1185                         usbpd_send_svdm(pd, USBPD_SID,
1186                                         USBPD_SVDM_DISCOVER_SVIDS,
1187                                         SVDM_CMD_TYPE_INITIATOR, 0, NULL, 0);
1188                         break;
1189
1190                 case USBPD_SVDM_DISCOVER_SVIDS:
1191                         pd->vdm_state = DISCOVERED_SVIDS;
1192
1193                         kfree(pd->vdm_tx_retry);
1194                         pd->vdm_tx_retry = NULL;
1195
1196                         if (!pd->discovered_svids) {
1197                                 pd->num_svids = 2 * num_vdos;
1198                                 pd->discovered_svids = kcalloc(pd->num_svids,
1199                                                                 sizeof(u16),
1200                                                                 GFP_KERNEL);
1201                                 if (!pd->discovered_svids) {
1202                                         usbpd_err(&pd->dev, "unable to allocate SVIDs\n");
1203                                         break;
1204                                 }
1205
1206                                 psvid = pd->discovered_svids;
1207                         } else { /* handle > 12 SVIDs */
1208                                 void *ptr;
1209                                 size_t oldsize = pd->num_svids * sizeof(u16);
1210                                 size_t newsize = oldsize +
1211                                                 (2 * num_vdos * sizeof(u16));
1212
1213                                 ptr = krealloc(pd->discovered_svids, newsize,
1214                                                 GFP_KERNEL);
1215                                 if (!ptr) {
1216                                         usbpd_err(&pd->dev, "unable to realloc SVIDs\n");
1217                                         break;
1218                                 }
1219
1220                                 pd->discovered_svids = ptr;
1221                                 psvid = pd->discovered_svids + pd->num_svids;
1222                                 memset(psvid, 0, (2 * num_vdos));
1223                                 pd->num_svids += 2 * num_vdos;
1224                         }
1225
1226                         /* convert 32-bit VDOs to list of 16-bit SVIDs */
1227                         for (i = 0; i < num_vdos * 2; i++) {
1228                                 /*
1229                                  * Within each 32-bit VDO,
1230                                  *    SVID[i]: upper 16-bits
1231                                  *    SVID[i+1]: lower 16-bits
1232                                  * where i is even.
1233                                  */
1234                                 if (!(i & 1))
1235                                         svid = vdos[i >> 1] >> 16;
1236                                 else
1237                                         svid = vdos[i >> 1] & 0xFFFF;
1238
1239                                 /*
1240                                  * There are some devices that incorrectly
1241                                  * swap the order of SVIDs within a VDO. So in
1242                                  * case of an odd-number of SVIDs it could end
1243                                  * up with SVID[i] as 0 while SVID[i+1] is
1244                                  * non-zero. Just skip over the zero ones.
1245                                  */
1246                                 if (svid) {
1247                                         usbpd_dbg(&pd->dev, "Discovered SVID: 0x%04x\n",
1248                                                         svid);
1249                                         *psvid++ = svid;
1250                                 }
1251                         }
1252
1253                         /* if more than 12 SVIDs, resend the request */
1254                         if (num_vdos == 6 && vdos[5] != 0) {
1255                                 usbpd_send_svdm(pd, USBPD_SID,
1256                                                 USBPD_SVDM_DISCOVER_SVIDS,
1257                                                 SVDM_CMD_TYPE_INITIATOR, 0,
1258                                                 NULL, 0);
1259                                 break;
1260                         }
1261
1262                         /* now that all SVIDs are discovered, notify handlers */
1263                         for (i = 0; i < pd->num_svids; i++) {
1264                                 svid = pd->discovered_svids[i];
1265                                 if (svid) {
1266                                         handler = find_svid_handler(pd, svid);
1267                                         if (handler) {
1268                                                 handler->connect(handler);
1269                                                 handler->discovered = true;
1270                                         }
1271                                 }
1272
1273                                 if (svid == 0xFF01)
1274                                         has_dp = true;
1275                         }
1276
1277                         /*
1278                          * Finally start USB host now that we have determined
1279                          * if DisplayPort mode is present or not and limit USB
1280                          * to HS-only mode if so.
1281                          */
1282                         start_usb_host(pd, !has_dp);
1283
1284                         break;
1285
1286                 default:
1287                         usbpd_dbg(&pd->dev, "unhandled ACK for command:0x%x\n",
1288                                         cmd);
1289                         break;
1290                 }
1291                 break;
1292
1293         case SVDM_CMD_TYPE_RESP_NAK:
1294                 usbpd_info(&pd->dev, "VDM NAK received for SVID:0x%04x command:0x%x\n",
1295                                 svid, cmd);
1296
1297                 switch (cmd) {
1298                 case USBPD_SVDM_DISCOVER_IDENTITY:
1299                 case USBPD_SVDM_DISCOVER_SVIDS:
1300                         start_usb_host(pd, true);
1301                         break;
1302                 default:
1303                         break;
1304                 }
1305
1306                 break;
1307
1308         case SVDM_CMD_TYPE_RESP_BUSY:
1309                 switch (cmd) {
1310                 case USBPD_SVDM_DISCOVER_IDENTITY:
1311                 case USBPD_SVDM_DISCOVER_SVIDS:
1312                         if (!pd->vdm_tx_retry) {
1313                                 usbpd_err(&pd->dev, "Discover command %d VDM was unexpectedly freed\n",
1314                                                 cmd);
1315                                 break;
1316                         }
1317
1318                         /* wait tVDMBusy, then retry */
1319                         pd->vdm_tx = pd->vdm_tx_retry;
1320                         pd->vdm_tx_retry = NULL;
1321                         kick_sm(pd, VDM_BUSY_TIME);
1322                         break;
1323                 default:
1324                         break;
1325                 }
1326                 break;
1327         }
1328 }
1329
1330 static void handle_vdm_tx(struct usbpd *pd)
1331 {
1332         int ret;
1333         unsigned long flags;
1334
1335         /* only send one VDM at a time */
1336         if (pd->vdm_tx) {
1337                 u32 vdm_hdr = pd->vdm_tx->data[0];
1338
1339                 /* bail out and try again later if a message just arrived */
1340                 spin_lock_irqsave(&pd->rx_lock, flags);
1341                 if (!list_empty(&pd->rx_q)) {
1342                         spin_unlock_irqrestore(&pd->rx_lock, flags);
1343                         return;
1344                 }
1345                 spin_unlock_irqrestore(&pd->rx_lock, flags);
1346
1347                 ret = pd_send_msg(pd, MSG_VDM, pd->vdm_tx->data,
1348                                 pd->vdm_tx->size, SOP_MSG);
1349                 if (ret) {
1350                         usbpd_err(&pd->dev, "Error (%d) sending VDM command %d\n",
1351                                         ret, SVDM_HDR_CMD(pd->vdm_tx->data[0]));
1352
1353                         /* retry when hitting PE_SRC/SNK_Ready again */
1354                         if (ret != -EBUSY)
1355                                 usbpd_set_state(pd, pd->current_pr == PR_SRC ?
1356                                         PE_SRC_SEND_SOFT_RESET :
1357                                         PE_SNK_SEND_SOFT_RESET);
1358
1359                         return;
1360                 }
1361
1362                 /*
1363                  * special case: keep initiated Discover ID/SVIDs
1364                  * around in case we need to re-try when receiving BUSY
1365                  */
1366                 if (VDM_IS_SVDM(vdm_hdr) &&
1367                         SVDM_HDR_CMD_TYPE(vdm_hdr) == SVDM_CMD_TYPE_INITIATOR &&
1368                         SVDM_HDR_CMD(vdm_hdr) <= USBPD_SVDM_DISCOVER_SVIDS) {
1369                         if (pd->vdm_tx_retry) {
1370                                 usbpd_dbg(&pd->dev, "Previous Discover VDM command %d not ACKed/NAKed\n",
1371                                         SVDM_HDR_CMD(
1372                                                 pd->vdm_tx_retry->data[0]));
1373                                 kfree(pd->vdm_tx_retry);
1374                         }
1375                         pd->vdm_tx_retry = pd->vdm_tx;
1376                 } else {
1377                         kfree(pd->vdm_tx);
1378                 }
1379
1380                 pd->vdm_tx = NULL;
1381         }
1382 }
1383
1384 static void reset_vdm_state(struct usbpd *pd)
1385 {
1386         struct usbpd_svid_handler *handler;
1387
1388         list_for_each_entry(handler, &pd->svid_handlers, entry) {
1389                 if (handler->discovered) {
1390                         handler->disconnect(handler);
1391                         handler->discovered = false;
1392                 }
1393         }
1394
1395         pd->vdm_state = VDM_NONE;
1396         kfree(pd->vdm_tx_retry);
1397         pd->vdm_tx_retry = NULL;
1398         kfree(pd->discovered_svids);
1399         pd->discovered_svids = NULL;
1400         pd->num_svids = 0;
1401         kfree(pd->vdm_tx);
1402         pd->vdm_tx = NULL;
1403 }
1404
1405 static void dr_swap(struct usbpd *pd)
1406 {
1407         reset_vdm_state(pd);
1408
1409         if (pd->current_dr == DR_DFP) {
1410                 stop_usb_host(pd);
1411                 start_usb_peripheral(pd);
1412                 pd->current_dr = DR_UFP;
1413         } else if (pd->current_dr == DR_UFP) {
1414                 stop_usb_peripheral(pd);
1415                 pd->current_dr = DR_DFP;
1416
1417                 /* don't start USB host until after SVDM discovery */
1418                 usbpd_send_svdm(pd, USBPD_SID, USBPD_SVDM_DISCOVER_IDENTITY,
1419                                 SVDM_CMD_TYPE_INITIATOR, 0, NULL, 0);
1420         }
1421
1422         pd_phy_update_roles(pd->current_dr, pd->current_pr);
1423 }
1424
1425
1426 static void vconn_swap(struct usbpd *pd)
1427 {
1428         int ret;
1429
1430         if (pd->vconn_enabled) {
1431                 pd->current_state = PE_VCS_WAIT_FOR_VCONN;
1432                 kick_sm(pd, VCONN_ON_TIME);
1433         } else {
1434                 ret = regulator_enable(pd->vconn);
1435                 if (ret) {
1436                         usbpd_err(&pd->dev, "Unable to enable vconn\n");
1437                         return;
1438                 }
1439
1440                 pd->vconn_enabled = true;
1441
1442                 /*
1443                  * Small delay to ensure Vconn has ramped up. This is well
1444                  * below tVCONNSourceOn (100ms) so we still send PS_RDY within
1445                  * the allowed time.
1446                  */
1447                 usleep_range(5000, 10000);
1448
1449                 ret = pd_send_msg(pd, MSG_PS_RDY, NULL, 0, SOP_MSG);
1450                 if (ret) {
1451                         usbpd_err(&pd->dev, "Error sending PS_RDY\n");
1452                         usbpd_set_state(pd, pd->current_pr == PR_SRC ?
1453                                         PE_SRC_SEND_SOFT_RESET :
1454                                         PE_SNK_SEND_SOFT_RESET);
1455                         return;
1456                 }
1457         }
1458 }
1459
1460 static int enable_vbus(struct usbpd *pd)
1461 {
1462         union power_supply_propval val = {0};
1463         int count = 100;
1464         int ret;
1465
1466         if (!check_vsafe0v)
1467                 goto enable_reg;
1468
1469         /*
1470          * Check to make sure there's no lingering charge on
1471          * VBUS before enabling it as a source. If so poll here
1472          * until it goes below VSafe0V (0.8V) before proceeding.
1473          */
1474         while (count--) {
1475                 ret = power_supply_get_property(pd->usb_psy,
1476                                 POWER_SUPPLY_PROP_VOLTAGE_NOW, &val);
1477                 if (ret || val.intval <= 800000)
1478                         break;
1479                 usleep_range(20000, 30000);
1480         }
1481
1482         if (count < 99)
1483                 msleep(100);    /* need to wait an additional tCCDebounce */
1484
1485 enable_reg:
1486         ret = regulator_enable(pd->vbus);
1487         if (ret)
1488                 usbpd_err(&pd->dev, "Unable to enable vbus (%d)\n", ret);
1489         else
1490                 pd->vbus_enabled = true;
1491
1492         return ret;
1493 }
1494
1495 static inline void rx_msg_cleanup(struct usbpd *pd)
1496 {
1497         struct rx_msg *msg, *tmp;
1498         unsigned long flags;
1499
1500         spin_lock_irqsave(&pd->rx_lock, flags);
1501         list_for_each_entry_safe(msg, tmp, &pd->rx_q, entry) {
1502                 list_del(&msg->entry);
1503                 kfree(msg);
1504         }
1505         spin_unlock_irqrestore(&pd->rx_lock, flags);
1506 }
1507
1508 /* For PD 3.0, check SinkTxOk before allowing initiating AMS */
1509 static inline bool is_sink_tx_ok(struct usbpd *pd)
1510 {
1511         if (pd->spec_rev == USBPD_REV_30)
1512                 return pd->typec_mode == POWER_SUPPLY_TYPEC_SOURCE_HIGH;
1513
1514         return true;
1515 }
1516
1517 /* Handles current state and determines transitions */
1518 static void usbpd_sm(struct work_struct *w)
1519 {
1520         struct usbpd *pd = container_of(w, struct usbpd, sm_work);
1521         union power_supply_propval val = {0};
1522         int ret;
1523         struct rx_msg *rx_msg = NULL;
1524         unsigned long flags;
1525
1526         usbpd_dbg(&pd->dev, "handle state %s\n",
1527                         usbpd_state_strings[pd->current_state]);
1528
1529         hrtimer_cancel(&pd->timer);
1530         pd->sm_queued = false;
1531
1532         spin_lock_irqsave(&pd->rx_lock, flags);
1533         if (!list_empty(&pd->rx_q)) {
1534                 rx_msg = list_first_entry(&pd->rx_q, struct rx_msg, entry);
1535                 list_del(&rx_msg->entry);
1536         }
1537         spin_unlock_irqrestore(&pd->rx_lock, flags);
1538
1539         /* Disconnect? */
1540         if (pd->current_pr == PR_NONE) {
1541                 if (pd->current_state == PE_UNKNOWN)
1542                         goto sm_done;
1543
1544                 usbpd_info(&pd->dev, "USB Type-C disconnect\n");
1545
1546                 if (pd->pd_phy_opened) {
1547                         pd_phy_close();
1548                         pd->pd_phy_opened = false;
1549                 }
1550
1551                 pd->in_pr_swap = false;
1552                 pd->pd_connected = false;
1553                 pd->in_explicit_contract = false;
1554                 pd->hard_reset_recvd = false;
1555                 pd->caps_count = 0;
1556                 pd->hard_reset_count = 0;
1557                 pd->requested_voltage = 0;
1558                 pd->requested_current = 0;
1559                 pd->selected_pdo = pd->requested_pdo = 0;
1560                 memset(&pd->received_pdos, 0, sizeof(pd->received_pdos));
1561                 rx_msg_cleanup(pd);
1562
1563                 val.intval = 0;
1564                 power_supply_set_property(pd->usb_psy,
1565                                 POWER_SUPPLY_PROP_PD_IN_HARD_RESET, &val);
1566
1567                 power_supply_set_property(pd->usb_psy,
1568                                 POWER_SUPPLY_PROP_PD_USB_SUSPEND_SUPPORTED,
1569                                 &val);
1570
1571                 power_supply_set_property(pd->usb_psy,
1572                                 POWER_SUPPLY_PROP_PD_ACTIVE, &val);
1573
1574                 if (pd->vbus_enabled) {
1575                         regulator_disable(pd->vbus);
1576                         pd->vbus_enabled = false;
1577                 }
1578
1579                 if (pd->vconn_enabled) {
1580                         regulator_disable(pd->vconn);
1581                         pd->vconn_enabled = false;
1582                 }
1583
1584                 if (pd->current_dr == DR_UFP)
1585                         stop_usb_peripheral(pd);
1586                 else if (pd->current_dr == DR_DFP)
1587                         stop_usb_host(pd);
1588
1589                 pd->current_pr = PR_NONE;
1590                 pd->current_dr = DR_NONE;
1591
1592                 reset_vdm_state(pd);
1593
1594                 if (pd->current_state == PE_ERROR_RECOVERY)
1595                         /* forced disconnect, wait before resetting to DRP */
1596                         usleep_range(ERROR_RECOVERY_TIME * USEC_PER_MSEC,
1597                                 (ERROR_RECOVERY_TIME + 5) * USEC_PER_MSEC);
1598
1599                 /* set due to dual_role class "mode" change */
1600                 if (pd->forced_pr != POWER_SUPPLY_TYPEC_PR_NONE)
1601                         val.intval = pd->forced_pr;
1602                 else
1603                         /* Set CC back to DRP toggle */
1604                         val.intval = POWER_SUPPLY_TYPEC_PR_DUAL;
1605
1606                 power_supply_set_property(pd->usb_psy,
1607                                 POWER_SUPPLY_PROP_TYPEC_POWER_ROLE, &val);
1608                 pd->forced_pr = POWER_SUPPLY_TYPEC_PR_NONE;
1609
1610                 pd->current_state = PE_UNKNOWN;
1611
1612                 kobject_uevent(&pd->dev.kobj, KOBJ_CHANGE);
1613                 dual_role_instance_changed(pd->dual_role);
1614
1615                 goto sm_done;
1616         }
1617
1618         /* Hard reset? */
1619         if (pd->hard_reset_recvd) {
1620                 pd->hard_reset_recvd = false;
1621
1622                 val.intval = 1;
1623                 power_supply_set_property(pd->usb_psy,
1624                                 POWER_SUPPLY_PROP_PD_IN_HARD_RESET, &val);
1625
1626                 pd->in_pr_swap = false;
1627                 pd->in_explicit_contract = false;
1628                 pd->selected_pdo = pd->requested_pdo = 0;
1629                 pd->rdo = 0;
1630                 rx_msg_cleanup(pd);
1631                 reset_vdm_state(pd);
1632                 kobject_uevent(&pd->dev.kobj, KOBJ_CHANGE);
1633
1634                 if (pd->current_pr == PR_SINK) {
1635                         usbpd_set_state(pd, PE_SNK_TRANSITION_TO_DEFAULT);
1636                 } else {
1637                         pd->current_state = PE_SRC_TRANSITION_TO_DEFAULT;
1638                         kick_sm(pd, PS_HARD_RESET_TIME);
1639                 }
1640
1641                 goto sm_done;
1642         }
1643
1644         /* Soft reset? */
1645         if (IS_CTRL(rx_msg, MSG_SOFT_RESET)) {
1646                 usbpd_dbg(&pd->dev, "Handle soft reset\n");
1647
1648                 if (pd->current_pr == PR_SRC)
1649                         pd->current_state = PE_SRC_SOFT_RESET;
1650                 else if (pd->current_pr == PR_SINK)
1651                         pd->current_state = PE_SNK_SOFT_RESET;
1652         }
1653
1654         switch (pd->current_state) {
1655         case PE_UNKNOWN:
1656                 if (pd->current_pr == PR_SINK) {
1657                         usbpd_set_state(pd, PE_SNK_STARTUP);
1658                 } else if (pd->current_pr == PR_SRC) {
1659                         enable_vbus(pd);
1660                         if (!pd->vconn_enabled &&
1661                                         pd->typec_mode ==
1662                                         POWER_SUPPLY_TYPEC_SINK_POWERED_CABLE) {
1663                                 ret = regulator_enable(pd->vconn);
1664                                 if (ret)
1665                                         usbpd_err(&pd->dev, "Unable to enable vconn\n");
1666                                 else
1667                                         pd->vconn_enabled = true;
1668                         }
1669
1670                         usbpd_set_state(pd, PE_SRC_STARTUP);
1671                 }
1672                 break;
1673
1674         case PE_SRC_STARTUP:
1675                 usbpd_set_state(pd, PE_SRC_STARTUP);
1676                 break;
1677
1678         case PE_SRC_SEND_CAPABILITIES:
1679                 ret = pd_send_msg(pd, MSG_SOURCE_CAPABILITIES, default_src_caps,
1680                                 ARRAY_SIZE(default_src_caps), SOP_MSG);
1681                 if (ret) {
1682                         pd->caps_count++;
1683
1684                         if (pd->caps_count == 10 && pd->current_dr == DR_DFP) {
1685                                 /* Likely not PD-capable, start host now */
1686                                 start_usb_host(pd, true);
1687                         } else if (pd->caps_count >= PD_CAPS_COUNT) {
1688                                 usbpd_dbg(&pd->dev, "Src CapsCounter exceeded, disabling PD\n");
1689                                 usbpd_set_state(pd, PE_SRC_DISABLED);
1690
1691                                 val.intval = 0;
1692                                 power_supply_set_property(pd->usb_psy,
1693                                                 POWER_SUPPLY_PROP_PD_ACTIVE,
1694                                                 &val);
1695                                 break;
1696                         }
1697
1698                         kick_sm(pd, SRC_CAP_TIME);
1699                         break;
1700                 }
1701
1702                 /* transmit was successful if GoodCRC was received */
1703                 pd->caps_count = 0;
1704                 pd->hard_reset_count = 0;
1705                 pd->pd_connected = true; /* we know peer is PD capable */
1706
1707                 /* wait for REQUEST */
1708                 pd->current_state = PE_SRC_SEND_CAPABILITIES_WAIT;
1709                 kick_sm(pd, SENDER_RESPONSE_TIME);
1710
1711                 val.intval = 1;
1712                 power_supply_set_property(pd->usb_psy,
1713                                 POWER_SUPPLY_PROP_PD_ACTIVE, &val);
1714                 break;
1715
1716         case PE_SRC_SEND_CAPABILITIES_WAIT:
1717                 if (IS_DATA(rx_msg, MSG_REQUEST)) {
1718                         pd->rdo = rx_msg->payload[0];
1719                         usbpd_set_state(pd, PE_SRC_NEGOTIATE_CAPABILITY);
1720                 } else if (rx_msg) {
1721                         usbpd_err(&pd->dev, "Unexpected message received\n");
1722                         usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1723                 } else {
1724                         usbpd_set_state(pd, PE_SRC_HARD_RESET);
1725                 }
1726                 break;
1727
1728         case PE_SRC_READY:
1729                 if (IS_CTRL(rx_msg, MSG_GET_SOURCE_CAP)) {
1730                         ret = pd_send_msg(pd, MSG_SOURCE_CAPABILITIES,
1731                                         default_src_caps,
1732                                         ARRAY_SIZE(default_src_caps), SOP_MSG);
1733                         if (ret) {
1734                                 usbpd_err(&pd->dev, "Error sending SRC CAPs\n");
1735                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1736                                 break;
1737                         }
1738                 } else if (IS_CTRL(rx_msg, MSG_GET_SINK_CAP)) {
1739                         ret = pd_send_msg(pd, MSG_SINK_CAPABILITIES,
1740                                         pd->sink_caps, pd->num_sink_caps,
1741                                         SOP_MSG);
1742                         if (ret) {
1743                                 usbpd_err(&pd->dev, "Error sending Sink Caps\n");
1744                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1745                         }
1746                 } else if (IS_DATA(rx_msg, MSG_REQUEST)) {
1747                         pd->rdo = rx_msg->payload[0];
1748                         usbpd_set_state(pd, PE_SRC_NEGOTIATE_CAPABILITY);
1749                 } else if (IS_CTRL(rx_msg, MSG_DR_SWAP)) {
1750                         if (pd->vdm_state == MODE_ENTERED) {
1751                                 usbpd_set_state(pd, PE_SRC_HARD_RESET);
1752                                 break;
1753                         }
1754
1755                         ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
1756                         if (ret) {
1757                                 usbpd_err(&pd->dev, "Error sending Accept\n");
1758                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1759                                 break;
1760                         }
1761
1762                         dr_swap(pd);
1763                 } else if (IS_CTRL(rx_msg, MSG_PR_SWAP)) {
1764                         /* lock in current mode */
1765                         set_power_role(pd, pd->current_pr);
1766
1767                         /* we'll happily accept Src->Sink requests anytime */
1768                         ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
1769                         if (ret) {
1770                                 usbpd_err(&pd->dev, "Error sending Accept\n");
1771                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1772                                 break;
1773                         }
1774
1775                         pd->current_state = PE_PRS_SRC_SNK_TRANSITION_TO_OFF;
1776                         kick_sm(pd, SRC_TRANSITION_TIME);
1777                         break;
1778                 } else if (IS_CTRL(rx_msg, MSG_VCONN_SWAP)) {
1779                         ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
1780                         if (ret) {
1781                                 usbpd_err(&pd->dev, "Error sending Accept\n");
1782                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1783                                 break;
1784                         }
1785
1786                         vconn_swap(pd);
1787                 } else if (IS_DATA(rx_msg, MSG_VDM)) {
1788                         handle_vdm_rx(pd, rx_msg);
1789                 } else if (pd->send_pr_swap) {
1790                         pd->send_pr_swap = false;
1791                         ret = pd_send_msg(pd, MSG_PR_SWAP, NULL, 0, SOP_MSG);
1792                         if (ret) {
1793                                 dev_err(&pd->dev, "Error sending PR Swap\n");
1794                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1795                                 break;
1796                         }
1797
1798                         pd->current_state = PE_PRS_SRC_SNK_SEND_SWAP;
1799                         kick_sm(pd, SENDER_RESPONSE_TIME);
1800                 } else if (pd->send_dr_swap) {
1801                         pd->send_dr_swap = false;
1802                         ret = pd_send_msg(pd, MSG_DR_SWAP, NULL, 0, SOP_MSG);
1803                         if (ret) {
1804                                 dev_err(&pd->dev, "Error sending DR Swap\n");
1805                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
1806                                 break;
1807                         }
1808
1809                         pd->current_state = PE_DRS_SEND_DR_SWAP;
1810                         kick_sm(pd, SENDER_RESPONSE_TIME);
1811                 } else {
1812                         handle_vdm_tx(pd);
1813                 }
1814                 break;
1815
1816         case PE_SRC_TRANSITION_TO_DEFAULT:
1817                 if (pd->vconn_enabled)
1818                         regulator_disable(pd->vconn);
1819                 if (pd->vbus_enabled)
1820                         regulator_disable(pd->vbus);
1821
1822                 if (pd->current_dr != DR_DFP) {
1823                         extcon_set_cable_state_(pd->extcon, EXTCON_USB, 0);
1824                         pd->current_dr = DR_DFP;
1825                         pd_phy_update_roles(pd->current_dr, pd->current_pr);
1826                 }
1827
1828                 msleep(SRC_RECOVER_TIME);
1829
1830                 pd->vbus_enabled = false;
1831                 enable_vbus(pd);
1832
1833                 if (pd->vconn_enabled) {
1834                         ret = regulator_enable(pd->vconn);
1835                         if (ret) {
1836                                 usbpd_err(&pd->dev, "Unable to enable vconn\n");
1837                                 pd->vconn_enabled = false;
1838                         }
1839                 }
1840
1841                 val.intval = 0;
1842                 power_supply_set_property(pd->usb_psy,
1843                                 POWER_SUPPLY_PROP_PD_IN_HARD_RESET, &val);
1844
1845                 usbpd_set_state(pd, PE_SRC_STARTUP);
1846                 break;
1847
1848         case PE_SRC_HARD_RESET:
1849                 val.intval = 1;
1850                 power_supply_set_property(pd->usb_psy,
1851                                 POWER_SUPPLY_PROP_PD_IN_HARD_RESET, &val);
1852
1853                 pd_send_hard_reset(pd);
1854                 pd->in_explicit_contract = false;
1855                 pd->rdo = 0;
1856                 rx_msg_cleanup(pd);
1857                 reset_vdm_state(pd);
1858                 kobject_uevent(&pd->dev.kobj, KOBJ_CHANGE);
1859
1860                 pd->current_state = PE_SRC_TRANSITION_TO_DEFAULT;
1861                 kick_sm(pd, PS_HARD_RESET_TIME);
1862                 break;
1863
1864         case PE_SNK_STARTUP:
1865                 usbpd_set_state(pd, PE_SNK_STARTUP);
1866                 break;
1867
1868         case PE_SNK_DISCOVERY:
1869                 if (!rx_msg) {
1870                         if (pd->vbus_present)
1871                                 usbpd_set_state(pd,
1872                                                 PE_SNK_WAIT_FOR_CAPABILITIES);
1873
1874                         /*
1875                          * Handle disconnection in the middle of PR_Swap.
1876                          * Since in psy_changed() if pd->in_pr_swap is true
1877                          * we ignore the typec_mode==NONE change since that is
1878                          * expected to happen. However if the cable really did
1879                          * get disconnected we need to check for it here after
1880                          * waiting for VBUS presence times out.
1881                          */
1882                         if (!pd->typec_mode) {
1883                                 pd->current_pr = PR_NONE;
1884                                 kick_sm(pd, 0);
1885                         }
1886
1887                         break;
1888                 }
1889                 /* else fall-through */
1890
1891         case PE_SNK_WAIT_FOR_CAPABILITIES:
1892                 pd->in_pr_swap = false;
1893
1894                 if (IS_DATA(rx_msg, MSG_SOURCE_CAPABILITIES)) {
1895                         val.intval = 0;
1896                         power_supply_set_property(pd->usb_psy,
1897                                         POWER_SUPPLY_PROP_PD_IN_HARD_RESET,
1898                                         &val);
1899
1900                         /* save the PDOs so userspace can further evaluate */
1901                         memcpy(&pd->received_pdos, rx_msg->payload,
1902                                         sizeof(pd->received_pdos));
1903                         pd->src_cap_id++;
1904
1905                         usbpd_set_state(pd, PE_SNK_EVALUATE_CAPABILITY);
1906
1907                         val.intval = 1;
1908                         power_supply_set_property(pd->usb_psy,
1909                                         POWER_SUPPLY_PROP_PD_ACTIVE, &val);
1910                 } else if (pd->hard_reset_count < 3) {
1911                         usbpd_set_state(pd, PE_SNK_HARD_RESET);
1912                 } else if (pd->pd_connected) {
1913                         usbpd_info(&pd->dev, "Sink hard reset count exceeded, forcing reconnect\n");
1914
1915                         val.intval = 0;
1916                         power_supply_set_property(pd->usb_psy,
1917                                         POWER_SUPPLY_PROP_PD_IN_HARD_RESET,
1918                                         &val);
1919
1920                         usbpd_set_state(pd, PE_ERROR_RECOVERY);
1921                 } else {
1922                         usbpd_dbg(&pd->dev, "Sink hard reset count exceeded, disabling PD\n");
1923
1924                         val.intval = 0;
1925                         power_supply_set_property(pd->usb_psy,
1926                                         POWER_SUPPLY_PROP_PD_IN_HARD_RESET,
1927                                         &val);
1928
1929                         val.intval = 0;
1930                         power_supply_set_property(pd->usb_psy,
1931                                         POWER_SUPPLY_PROP_PD_ACTIVE, &val);
1932                 }
1933                 break;
1934
1935         case PE_SNK_SELECT_CAPABILITY:
1936                 if (IS_CTRL(rx_msg, MSG_ACCEPT)) {
1937                         u32 pdo = pd->received_pdos[pd->requested_pdo - 1];
1938                         bool same_pps = (pd->selected_pdo == pd->requested_pdo)
1939                                 && (PD_SRC_PDO_TYPE(pdo) ==
1940                                                 PD_SRC_PDO_TYPE_AUGMENTED);
1941
1942                         usbpd_set_state(pd, PE_SNK_TRANSITION_SINK);
1943
1944                         /* prepare for voltage increase/decrease */
1945                         val.intval = pd->requested_voltage;
1946                         power_supply_set_property(pd->usb_psy,
1947                                 pd->requested_voltage >= pd->current_voltage ?
1948                                         POWER_SUPPLY_PROP_VOLTAGE_MAX :
1949                                         POWER_SUPPLY_PROP_VOLTAGE_MIN,
1950                                         &val);
1951
1952                         /*
1953                          * if changing voltages (not within the same PPS PDO),
1954                          * we must lower input current to pSnkStdby (2.5W).
1955                          * Calculate it and set PD_CURRENT_MAX accordingly.
1956                          */
1957                         if (!same_pps &&
1958                                 pd->requested_voltage != pd->current_voltage) {
1959                                 int mv = max(pd->requested_voltage,
1960                                                 pd->current_voltage) / 1000;
1961                                 val.intval = (2500000 / mv) * 1000;
1962                                 power_supply_set_property(pd->usb_psy,
1963                                         POWER_SUPPLY_PROP_PD_CURRENT_MAX, &val);
1964                         } else {
1965                                 /* decreasing current? */
1966                                 ret = power_supply_get_property(pd->usb_psy,
1967                                         POWER_SUPPLY_PROP_PD_CURRENT_MAX, &val);
1968                                 if (!ret &&
1969                                         pd->requested_current < val.intval) {
1970                                         val.intval =
1971                                                 pd->requested_current * 1000;
1972                                         power_supply_set_property(pd->usb_psy,
1973                                              POWER_SUPPLY_PROP_PD_CURRENT_MAX,
1974                                              &val);
1975                                 }
1976                         }
1977
1978                         pd->selected_pdo = pd->requested_pdo;
1979                 } else if (IS_CTRL(rx_msg, MSG_REJECT) ||
1980                                 IS_CTRL(rx_msg, MSG_WAIT)) {
1981                         if (pd->in_explicit_contract)
1982                                 usbpd_set_state(pd, PE_SNK_READY);
1983                         else
1984                                 usbpd_set_state(pd,
1985                                                 PE_SNK_WAIT_FOR_CAPABILITIES);
1986                 } else if (rx_msg) {
1987                         usbpd_err(&pd->dev, "Invalid response to sink request\n");
1988                         usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
1989                 } else {
1990                         /* timed out; go to hard reset */
1991                         usbpd_set_state(pd, PE_SNK_HARD_RESET);
1992                 }
1993                 break;
1994
1995         case PE_SNK_TRANSITION_SINK:
1996                 if (IS_CTRL(rx_msg, MSG_PS_RDY)) {
1997                         val.intval = pd->requested_voltage;
1998                         power_supply_set_property(pd->usb_psy,
1999                                 pd->requested_voltage >= pd->current_voltage ?
2000                                         POWER_SUPPLY_PROP_VOLTAGE_MIN :
2001                                         POWER_SUPPLY_PROP_VOLTAGE_MAX, &val);
2002                         pd->current_voltage = pd->requested_voltage;
2003
2004                         /* resume charging */
2005                         val.intval = pd->requested_current * 1000; /* mA->uA */
2006                         power_supply_set_property(pd->usb_psy,
2007                                         POWER_SUPPLY_PROP_PD_CURRENT_MAX, &val);
2008
2009                         usbpd_set_state(pd, PE_SNK_READY);
2010                 } else {
2011                         /* timed out; go to hard reset */
2012                         usbpd_set_state(pd, PE_SNK_HARD_RESET);
2013                 }
2014                 break;
2015
2016         case PE_SNK_READY:
2017                 if (IS_DATA(rx_msg, MSG_SOURCE_CAPABILITIES)) {
2018                         /* save the PDOs so userspace can further evaluate */
2019                         memcpy(&pd->received_pdos, rx_msg->payload,
2020                                         sizeof(pd->received_pdos));
2021                         pd->src_cap_id++;
2022
2023                         usbpd_set_state(pd, PE_SNK_EVALUATE_CAPABILITY);
2024                 } else if (IS_CTRL(rx_msg, MSG_GET_SINK_CAP)) {
2025                         ret = pd_send_msg(pd, MSG_SINK_CAPABILITIES,
2026                                         pd->sink_caps, pd->num_sink_caps,
2027                                         SOP_MSG);
2028                         if (ret) {
2029                                 usbpd_err(&pd->dev, "Error sending Sink Caps\n");
2030                                 usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
2031                         }
2032                 } else if (IS_CTRL(rx_msg, MSG_GET_SOURCE_CAP)) {
2033                         ret = pd_send_msg(pd, MSG_SOURCE_CAPABILITIES,
2034                                         default_src_caps,
2035                                         ARRAY_SIZE(default_src_caps), SOP_MSG);
2036                         if (ret) {
2037                                 usbpd_err(&pd->dev, "Error sending SRC CAPs\n");
2038                                 usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
2039                                 break;
2040                         }
2041                 } else if (IS_CTRL(rx_msg, MSG_DR_SWAP)) {
2042                         if (pd->vdm_state == MODE_ENTERED) {
2043                                 usbpd_set_state(pd, PE_SNK_HARD_RESET);
2044                                 break;
2045                         }
2046
2047                         ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
2048                         if (ret) {
2049                                 usbpd_err(&pd->dev, "Error sending Accept\n");
2050                                 usbpd_set_state(pd, PE_SRC_SEND_SOFT_RESET);
2051                                 break;
2052                         }
2053
2054                         dr_swap(pd);
2055                 } else if (IS_CTRL(rx_msg, MSG_PR_SWAP)) {
2056                         /* lock in current mode */
2057                         set_power_role(pd, pd->current_pr);
2058
2059                         /* TODO: should we Reject in certain circumstances? */
2060                         ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
2061                         if (ret) {
2062                                 usbpd_err(&pd->dev, "Error sending Accept\n");
2063                                 usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
2064                                 break;
2065                         }
2066
2067                         pd->in_pr_swap = true;
2068                         usbpd_set_state(pd, PE_PRS_SNK_SRC_TRANSITION_TO_OFF);
2069                         break;
2070                 } else if (IS_CTRL(rx_msg, MSG_VCONN_SWAP)) {
2071                         /*
2072                          * if VCONN is connected to VBUS, make sure we are
2073                          * not in high voltage contract, otherwise reject.
2074                          */
2075                         if (!pd->vconn_is_external &&
2076                                         (pd->requested_voltage > 5000000)) {
2077                                 ret = pd_send_msg(pd, MSG_REJECT, NULL, 0,
2078                                                 SOP_MSG);
2079                                 if (ret) {
2080                                         usbpd_err(&pd->dev, "Error sending Reject\n");
2081                                         usbpd_set_state(pd,
2082                                                         PE_SNK_SEND_SOFT_RESET);
2083                                 }
2084
2085                                 break;
2086                         }
2087
2088                         ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
2089                         if (ret) {
2090                                 usbpd_err(&pd->dev, "Error sending Accept\n");
2091                                 usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
2092                                 break;
2093                         }
2094
2095                         vconn_swap(pd);
2096                 } else if (IS_DATA(rx_msg, MSG_VDM)) {
2097                         handle_vdm_rx(pd, rx_msg);
2098                 } else if (pd->send_request) {
2099                         pd->send_request = false;
2100                         usbpd_set_state(pd, PE_SNK_SELECT_CAPABILITY);
2101                 } else if (pd->send_pr_swap && is_sink_tx_ok(pd)) {
2102                         pd->send_pr_swap = false;
2103                         ret = pd_send_msg(pd, MSG_PR_SWAP, NULL, 0, SOP_MSG);
2104                         if (ret) {
2105                                 dev_err(&pd->dev, "Error sending PR Swap\n");
2106                                 usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
2107                                 break;
2108                         }
2109
2110                         pd->current_state = PE_PRS_SNK_SRC_SEND_SWAP;
2111                         kick_sm(pd, SENDER_RESPONSE_TIME);
2112                 } else if (pd->send_dr_swap && is_sink_tx_ok(pd)) {
2113                         pd->send_dr_swap = false;
2114                         ret = pd_send_msg(pd, MSG_DR_SWAP, NULL, 0, SOP_MSG);
2115                         if (ret) {
2116                                 dev_err(&pd->dev, "Error sending DR Swap\n");
2117                                 usbpd_set_state(pd, PE_SNK_SEND_SOFT_RESET);
2118                                 break;
2119                         }
2120
2121                         pd->current_state = PE_DRS_SEND_DR_SWAP;
2122                         kick_sm(pd, SENDER_RESPONSE_TIME);
2123                 } else if (is_sink_tx_ok(pd)) {
2124                         handle_vdm_tx(pd);
2125                 }
2126                 break;
2127
2128         case PE_SNK_TRANSITION_TO_DEFAULT:
2129                 usbpd_set_state(pd, PE_SNK_STARTUP);
2130                 break;
2131
2132         case PE_SRC_SOFT_RESET:
2133         case PE_SNK_SOFT_RESET:
2134                 pd_reset_protocol(pd);
2135
2136                 ret = pd_send_msg(pd, MSG_ACCEPT, NULL, 0, SOP_MSG);
2137                 if (ret) {
2138                         usbpd_err(&pd->dev, "%s: Error sending Accept, do Hard Reset\n",
2139                                         usbpd_state_strings[pd->current_state]);
2140                         usbpd_set_state(pd, pd->current_pr == PR_SRC ?
2141                                         PE_SRC_HARD_RESET : PE_SNK_HARD_RESET);
2142                         break;
2143                 }
2144
2145                 usbpd_set_state(pd, pd->current_pr == PR_SRC ?
2146                                 PE_SRC_SEND_CAPABILITIES :
2147                                 PE_SNK_WAIT_FOR_CAPABILITIES);
2148                 break;
2149
2150         case PE_SRC_SEND_SOFT_RESET:
2151         case PE_SNK_SEND_SOFT_RESET:
2152                 if (IS_CTRL(rx_msg, MSG_ACCEPT)) {
2153                         usbpd_set_state(pd, pd->current_pr == PR_SRC ?
2154                                         PE_SRC_SEND_CAPABILITIES :
2155                                         PE_SNK_WAIT_FOR_CAPABILITIES);
2156                 } else {
2157                         usbpd_err(&pd->dev, "%s: Did not see Accept, do Hard Reset\n",
2158                                         usbpd_state_strings[pd->current_state]);
2159                         usbpd_set_state(pd, pd->current_pr == PR_SRC ?
2160                                         PE_SRC_HARD_RESET : PE_SNK_HARD_RESET);
2161                 }
2162                 break;
2163
2164         case PE_SNK_HARD_RESET:
2165                 /* prepare charger for VBUS change */
2166                 val.intval = 1;
2167                 power_supply_set_property(pd->usb_psy,
2168                                 POWER_SUPPLY_PROP_PD_IN_HARD_RESET, &val);
2169
2170                 pd->requested_voltage = 5000000;
2171
2172                 if (pd->requested_current) {
2173                         val.intval = pd->requested_current = 0;
2174                         power_supply_set_property(pd->usb_psy,
2175                                         POWER_SUPPLY_PROP_PD_CURRENT_MAX, &val);
2176                 }
2177
2178                 val.intval = pd->requested_voltage;
2179                 power_supply_set_property(pd->usb_psy,
2180                                 POWER_SUPPLY_PROP_VOLTAGE_MIN, &val);
2181
2182                 pd_send_hard_reset(pd);
2183                 pd->in_explicit_contract = false;
2184                 pd->selected_pdo = pd->requested_pdo = 0;
2185                 pd->rdo = 0;
2186                 reset_vdm_state(pd);
2187                 kobject_uevent(&pd->dev.kobj, KOBJ_CHANGE);
2188                 usbpd_set_state(pd, PE_SNK_TRANSITION_TO_DEFAULT);
2189                 break;
2190
2191         case PE_DRS_SEND_DR_SWAP:
2192                 if (IS_CTRL(rx_msg, MSG_ACCEPT))
2193                         dr_swap(pd);
2194
2195                 usbpd_set_state(pd, pd->current_pr == PR_SRC ?
2196                                 PE_SRC_READY : PE_SNK_READY);
2197                 break;
2198
2199         case PE_PRS_SRC_SNK_SEND_SWAP:
2200                 if (!IS_CTRL(rx_msg, MSG_ACCEPT)) {
2201                         pd->current_state = PE_SRC_READY;
2202                         break;
2203                 }
2204
2205                 pd->current_state = PE_PRS_SRC_SNK_TRANSITION_TO_OFF;
2206                 kick_sm(pd, SRC_TRANSITION_TIME);
2207                 break;
2208
2209         case PE_PRS_SRC_SNK_TRANSITION_TO_OFF:
2210                 pd->in_pr_swap = true;
2211                 pd->in_explicit_contract = false;
2212
2213                 if (pd->vbus_enabled) {
2214                         regulator_disable(pd->vbus);
2215                         pd->vbus_enabled = false;
2216                 }
2217
2218                 /* PE_PRS_SRC_SNK_Assert_Rd */
2219                 pd->current_pr = PR_SINK;
2220                 set_power_role(pd, pd->current_pr);
2221                 pd_phy_update_roles(pd->current_dr, pd->current_pr);
2222
2223                 /* allow time for Vbus discharge, must be < tSrcSwapStdby */
2224                 msleep(500);
2225
2226                 ret = pd_send_msg(pd, MSG_PS_RDY, NULL, 0, SOP_MSG);
2227                 if (ret) {
2228                         usbpd_err(&pd->dev, "Error sending PS_RDY\n");
2229                         usbpd_set_state(pd, PE_ERROR_RECOVERY);
2230                         break;
2231                 }
2232
2233                 pd->current_state = PE_PRS_SRC_SNK_WAIT_SOURCE_ON;
2234                 kick_sm(pd, PS_SOURCE_ON);
2235                 break;
2236
2237         case PE_PRS_SRC_SNK_WAIT_SOURCE_ON:
2238                 if (IS_CTRL(rx_msg, MSG_PS_RDY))
2239                         usbpd_set_state(pd, PE_SNK_STARTUP);
2240                 else
2241                         usbpd_set_state(pd, PE_ERROR_RECOVERY);
2242                 break;
2243
2244         case PE_PRS_SNK_SRC_SEND_SWAP:
2245                 if (!IS_CTRL(rx_msg, MSG_ACCEPT)) {
2246                         pd->current_state = PE_SNK_READY;
2247                         break;
2248                 }
2249
2250                 pd->in_pr_swap = true;
2251                 usbpd_set_state(pd, PE_PRS_SNK_SRC_TRANSITION_TO_OFF);
2252                 break;
2253
2254         case PE_PRS_SNK_SRC_TRANSITION_TO_OFF:
2255                 if (!IS_CTRL(rx_msg, MSG_PS_RDY)) {
2256                         usbpd_set_state(pd, PE_ERROR_RECOVERY);
2257                         break;
2258                 }
2259
2260                 /* PE_PRS_SNK_SRC_Assert_Rp */
2261                 pd->current_pr = PR_SRC;
2262                 set_power_role(pd, pd->current_pr);
2263                 pd->current_state = PE_PRS_SNK_SRC_SOURCE_ON;
2264
2265                 /* fall-through */
2266
2267         case PE_PRS_SNK_SRC_SOURCE_ON:
2268                 enable_vbus(pd);
2269                 msleep(200); /* allow time VBUS ramp-up, must be < tNewSrc */
2270
2271                 ret = pd_send_msg(pd, MSG_PS_RDY, NULL, 0, SOP_MSG);
2272                 if (ret) {
2273                         usbpd_err(&pd->dev, "Error sending PS_RDY\n");
2274                         usbpd_set_state(pd, PE_ERROR_RECOVERY);
2275                         break;
2276                 }
2277
2278                 usbpd_set_state(pd, PE_SRC_STARTUP);
2279                 break;
2280
2281         case PE_VCS_WAIT_FOR_VCONN:
2282                 if (IS_CTRL(rx_msg, MSG_PS_RDY)) {
2283                         /*
2284                          * hopefully redundant check but in case not enabled
2285                          * avoids unbalanced regulator disable count
2286                          */
2287                         if (pd->vconn_enabled)
2288                                 regulator_disable(pd->vconn);
2289                         pd->vconn_enabled = false;
2290
2291                         pd->current_state = pd->current_pr == PR_SRC ?
2292                                 PE_SRC_READY : PE_SNK_READY;
2293                 } else {
2294                         /* timed out; go to hard reset */
2295                         usbpd_set_state(pd, pd->current_pr == PR_SRC ?
2296                                         PE_SRC_HARD_RESET : PE_SNK_HARD_RESET);
2297                 }
2298
2299                 break;
2300
2301         default:
2302                 usbpd_err(&pd->dev, "Unhandled state %s\n",
2303                                 usbpd_state_strings[pd->current_state]);
2304                 break;
2305         }
2306
2307 sm_done:
2308         kfree(rx_msg);
2309
2310         if (!pd->sm_queued)
2311                 pm_relax(&pd->dev);
2312 }
2313
2314 static inline const char *src_current(enum power_supply_typec_mode typec_mode)
2315 {
2316         switch (typec_mode) {
2317         case POWER_SUPPLY_TYPEC_SOURCE_DEFAULT:
2318                 return "default";
2319         case POWER_SUPPLY_TYPEC_SOURCE_MEDIUM:
2320                 return "medium - 1.5A";
2321         case POWER_SUPPLY_TYPEC_SOURCE_HIGH:
2322                 return "high - 3.0A";
2323         default:
2324                 return "";
2325         }
2326 }
2327
2328 static int psy_changed(struct notifier_block *nb, unsigned long evt, void *ptr)
2329 {
2330         struct usbpd *pd = container_of(nb, struct usbpd, psy_nb);
2331         union power_supply_propval val;
2332         enum power_supply_typec_mode typec_mode;
2333         int ret;
2334
2335         if (ptr != pd->usb_psy || evt != PSY_EVENT_PROP_CHANGED)
2336                 return 0;
2337
2338         ret = power_supply_get_property(pd->usb_psy,
2339                         POWER_SUPPLY_PROP_TYPEC_MODE, &val);
2340         if (ret) {
2341                 usbpd_err(&pd->dev, "Unable to read USB TYPEC_MODE: %d\n", ret);
2342                 return ret;
2343         }
2344
2345         typec_mode = val.intval;
2346
2347         ret = power_supply_get_property(pd->usb_psy,
2348                         POWER_SUPPLY_PROP_PE_START, &val);
2349         if (ret) {
2350                 usbpd_err(&pd->dev, "Unable to read USB PROP_PE_START: %d\n",
2351                                 ret);
2352                 return ret;
2353         }
2354
2355         /* Don't proceed if PE_START=0 as other props may still change */
2356         if (!val.intval && !pd->pd_connected &&
2357                         typec_mode != POWER_SUPPLY_TYPEC_NONE)
2358                 return 0;
2359
2360         ret = power_supply_get_property(pd->usb_psy,
2361                         POWER_SUPPLY_PROP_PRESENT, &val);
2362         if (ret) {
2363                 usbpd_err(&pd->dev, "Unable to read USB PRESENT: %d\n", ret);
2364                 return ret;
2365         }
2366
2367         pd->vbus_present = val.intval;
2368
2369         ret = power_supply_get_property(pd->usb_psy,
2370                         POWER_SUPPLY_PROP_TYPE, &val);
2371         if (ret) {
2372                 usbpd_err(&pd->dev, "Unable to read USB TYPE: %d\n", ret);
2373                 return ret;
2374         }
2375
2376         pd->psy_type = val.intval;
2377
2378         /*
2379          * For sink hard reset, state machine needs to know when VBUS changes
2380          *   - when in PE_SNK_TRANSITION_TO_DEFAULT, notify when VBUS falls
2381          *   - when in PE_SNK_DISCOVERY, notify when VBUS rises
2382          */
2383         if (typec_mode && ((!pd->vbus_present &&
2384                         pd->current_state == PE_SNK_TRANSITION_TO_DEFAULT) ||
2385                 (pd->vbus_present && pd->current_state == PE_SNK_DISCOVERY))) {
2386                 usbpd_dbg(&pd->dev, "hard reset: typec mode:%d present:%d\n",
2387                         typec_mode, pd->vbus_present);
2388                 pd->typec_mode = typec_mode;
2389                 kick_sm(pd, 0);
2390                 return 0;
2391         }
2392
2393         if (pd->typec_mode == typec_mode)
2394                 return 0;
2395
2396         pd->typec_mode = typec_mode;
2397
2398         usbpd_dbg(&pd->dev, "typec mode:%d present:%d type:%d orientation:%d\n",
2399                         typec_mode, pd->vbus_present, pd->psy_type,
2400                         usbpd_get_plug_orientation(pd));
2401
2402         switch (typec_mode) {
2403         /* Disconnect */
2404         case POWER_SUPPLY_TYPEC_NONE:
2405                 if (pd->in_pr_swap) {
2406                         usbpd_dbg(&pd->dev, "Ignoring disconnect due to PR swap\n");
2407                         return 0;
2408                 }
2409
2410                 pd->current_pr = PR_NONE;
2411                 break;
2412
2413         /* Sink states */
2414         case POWER_SUPPLY_TYPEC_SOURCE_DEFAULT:
2415         case POWER_SUPPLY_TYPEC_SOURCE_MEDIUM:
2416         case POWER_SUPPLY_TYPEC_SOURCE_HIGH:
2417                 usbpd_info(&pd->dev, "Type-C Source (%s) connected\n",
2418                                 src_current(typec_mode));
2419
2420                 /* if waiting for SinkTxOk to start an AMS */
2421                 if (pd->spec_rev == USBPD_REV_30 &&
2422                         typec_mode == POWER_SUPPLY_TYPEC_SOURCE_HIGH &&
2423                         (pd->send_pr_swap || pd->send_dr_swap || pd->vdm_tx))
2424                         break;
2425
2426                 if (pd->current_pr == PR_SINK)
2427                         return 0;
2428
2429                 pd->current_pr = PR_SINK;
2430                 break;
2431
2432         /* Source states */
2433         case POWER_SUPPLY_TYPEC_SINK_POWERED_CABLE:
2434         case POWER_SUPPLY_TYPEC_SINK:
2435                 usbpd_info(&pd->dev, "Type-C Sink%s connected\n",
2436                                 typec_mode == POWER_SUPPLY_TYPEC_SINK ?
2437                                         "" : " (powered)");
2438
2439                 if (pd->current_pr == PR_SRC)
2440                         return 0;
2441
2442                 pd->current_pr = PR_SRC;
2443                 break;
2444
2445         case POWER_SUPPLY_TYPEC_SINK_DEBUG_ACCESSORY:
2446                 usbpd_info(&pd->dev, "Type-C Debug Accessory connected\n");
2447                 break;
2448         case POWER_SUPPLY_TYPEC_SINK_AUDIO_ADAPTER:
2449                 usbpd_info(&pd->dev, "Type-C Analog Audio Adapter connected\n");
2450                 break;
2451         default:
2452                 usbpd_warn(&pd->dev, "Unsupported typec mode:%d\n",
2453                                 typec_mode);
2454                 break;
2455         }
2456
2457         /* queue state machine due to CC state change */
2458         kick_sm(pd, 0);
2459         return 0;
2460 }
2461
2462 static enum dual_role_property usbpd_dr_properties[] = {
2463         DUAL_ROLE_PROP_SUPPORTED_MODES,
2464         DUAL_ROLE_PROP_MODE,
2465         DUAL_ROLE_PROP_PR,
2466         DUAL_ROLE_PROP_DR,
2467 };
2468
2469 static int usbpd_dr_get_property(struct dual_role_phy_instance *dual_role,
2470                 enum dual_role_property prop, unsigned int *val)
2471 {
2472         struct usbpd *pd = dual_role_get_drvdata(dual_role);
2473
2474         if (!pd)
2475                 return -ENODEV;
2476
2477         switch (prop) {
2478         case DUAL_ROLE_PROP_MODE:
2479                 /* For now associate UFP/DFP with data role only */
2480                 if (pd->current_dr == DR_UFP)
2481                         *val = DUAL_ROLE_PROP_MODE_UFP;
2482                 else if (pd->current_dr == DR_DFP)
2483                         *val = DUAL_ROLE_PROP_MODE_DFP;
2484                 else
2485                         *val = DUAL_ROLE_PROP_MODE_NONE;
2486                 break;
2487         case DUAL_ROLE_PROP_PR:
2488                 if (pd->current_pr == PR_SRC)
2489                         *val = DUAL_ROLE_PROP_PR_SRC;
2490                 else if (pd->current_pr == PR_SINK)
2491                         *val = DUAL_ROLE_PROP_PR_SNK;
2492                 else
2493                         *val = DUAL_ROLE_PROP_PR_NONE;
2494                 break;
2495         case DUAL_ROLE_PROP_DR:
2496                 if (pd->current_dr == DR_UFP)
2497                         *val = DUAL_ROLE_PROP_DR_DEVICE;
2498                 else if (pd->current_dr == DR_DFP)
2499                         *val = DUAL_ROLE_PROP_DR_HOST;
2500                 else
2501                         *val = DUAL_ROLE_PROP_DR_NONE;
2502                 break;
2503         default:
2504                 usbpd_warn(&pd->dev, "unsupported property %d\n", prop);
2505                 return -ENODATA;
2506         }
2507
2508         return 0;
2509 }
2510
2511 static int usbpd_dr_set_property(struct dual_role_phy_instance *dual_role,
2512                 enum dual_role_property prop, const unsigned int *val)
2513 {
2514         struct usbpd *pd = dual_role_get_drvdata(dual_role);
2515         bool do_swap = false;
2516
2517         if (!pd)
2518                 return -ENODEV;
2519
2520         switch (prop) {
2521         case DUAL_ROLE_PROP_MODE:
2522                 usbpd_dbg(&pd->dev, "Setting mode to %d\n", *val);
2523
2524                 /*
2525                  * Forces disconnect on CC and re-establishes connection.
2526                  * This does not use PD-based PR/DR swap
2527                  */
2528                 if (*val == DUAL_ROLE_PROP_MODE_UFP)
2529                         pd->forced_pr = POWER_SUPPLY_TYPEC_PR_SINK;
2530                 else if (*val == DUAL_ROLE_PROP_MODE_DFP)
2531                         pd->forced_pr = POWER_SUPPLY_TYPEC_PR_SOURCE;
2532
2533                 /* new mode will be applied in disconnect handler */
2534                 set_power_role(pd, PR_NONE);
2535
2536                 /* wait until it takes effect */
2537                 while (pd->forced_pr != POWER_SUPPLY_TYPEC_PR_NONE)
2538                         msleep(20);
2539
2540                 break;
2541
2542         case DUAL_ROLE_PROP_DR:
2543                 usbpd_dbg(&pd->dev, "Setting data_role to %d\n", *val);
2544
2545                 if (*val == DUAL_ROLE_PROP_DR_HOST) {
2546                         if (pd->current_dr == DR_UFP)
2547                                 do_swap = true;
2548                 } else if (*val == DUAL_ROLE_PROP_DR_DEVICE) {
2549                         if (pd->current_dr == DR_DFP)
2550                                 do_swap = true;
2551                 } else {
2552                         usbpd_warn(&pd->dev, "setting data_role to 'none' unsupported\n");
2553                         return -ENOTSUPP;
2554                 }
2555
2556                 if (do_swap) {
2557                         if (pd->current_state != PE_SRC_READY &&
2558                                         pd->current_state != PE_SNK_READY) {
2559                                 usbpd_err(&pd->dev, "data_role swap not allowed: PD not in Ready state\n");
2560                                 return -EAGAIN;
2561                         }
2562
2563                         if (pd->current_state == PE_SNK_READY &&
2564                                         !is_sink_tx_ok(pd)) {
2565                                 usbpd_err(&pd->dev, "Rp indicates SinkTxNG\n");
2566                                 return -EAGAIN;
2567                         }
2568
2569                         mutex_lock(&pd->swap_lock);
2570                         reinit_completion(&pd->is_ready);
2571                         pd->send_dr_swap = true;
2572                         kick_sm(pd, 0);
2573
2574                         /* wait for operation to complete */
2575                         if (!wait_for_completion_timeout(&pd->is_ready,
2576                                         msecs_to_jiffies(100))) {
2577                                 usbpd_err(&pd->dev, "data_role swap timed out\n");
2578                                 mutex_unlock(&pd->swap_lock);
2579                                 return -ETIMEDOUT;
2580                         }
2581
2582                         mutex_unlock(&pd->swap_lock);
2583
2584                         if ((*val == DUAL_ROLE_PROP_DR_HOST &&
2585                                         pd->current_dr != DR_DFP) ||
2586                                 (*val == DUAL_ROLE_PROP_DR_DEVICE &&
2587                                          pd->current_dr != DR_UFP)) {
2588                                 usbpd_err(&pd->dev, "incorrect state (%s) after data_role swap\n",
2589                                                 pd->current_dr == DR_DFP ?
2590                                                 "dfp" : "ufp");
2591                                 return -EPROTO;
2592                         }
2593                 }
2594
2595                 break;
2596
2597         case DUAL_ROLE_PROP_PR:
2598                 usbpd_dbg(&pd->dev, "Setting power_role to %d\n", *val);
2599
2600                 if (*val == DUAL_ROLE_PROP_PR_SRC) {
2601                         if (pd->current_pr == PR_SINK)
2602                                 do_swap = true;
2603                 } else if (*val == DUAL_ROLE_PROP_PR_SNK) {
2604                         if (pd->current_pr == PR_SRC)
2605                                 do_swap = true;
2606                 } else {
2607                         usbpd_warn(&pd->dev, "setting power_role to 'none' unsupported\n");
2608                         return -ENOTSUPP;
2609                 }
2610
2611                 if (do_swap) {
2612                         if (pd->current_state != PE_SRC_READY &&
2613                                         pd->current_state != PE_SNK_READY) {
2614                                 usbpd_err(&pd->dev, "power_role swap not allowed: PD not in Ready state\n");
2615                                 return -EAGAIN;
2616                         }
2617
2618                         if (pd->current_state == PE_SNK_READY &&
2619                                         !is_sink_tx_ok(pd)) {
2620                                 usbpd_err(&pd->dev, "Rp indicates SinkTxNG\n");
2621                                 return -EAGAIN;
2622                         }
2623
2624                         mutex_lock(&pd->swap_lock);
2625                         reinit_completion(&pd->is_ready);
2626                         pd->send_pr_swap = true;
2627                         kick_sm(pd, 0);
2628
2629                         /* wait for operation to complete */
2630                         if (!wait_for_completion_timeout(&pd->is_ready,
2631                                         msecs_to_jiffies(2000))) {
2632                                 usbpd_err(&pd->dev, "power_role swap timed out\n");
2633                                 mutex_unlock(&pd->swap_lock);
2634                                 return -ETIMEDOUT;
2635                         }
2636
2637                         mutex_unlock(&pd->swap_lock);
2638
2639                         if ((*val == DUAL_ROLE_PROP_PR_SRC &&
2640                                         pd->current_pr != PR_SRC) ||
2641                                 (*val == DUAL_ROLE_PROP_PR_SNK &&
2642                                          pd->current_pr != PR_SINK)) {
2643                                 usbpd_err(&pd->dev, "incorrect state (%s) after power_role swap\n",
2644                                                 pd->current_pr == PR_SRC ?
2645                                                 "source" : "sink");
2646                                 return -EPROTO;
2647                         }
2648                 }
2649                 break;
2650
2651         default:
2652                 usbpd_warn(&pd->dev, "unsupported property %d\n", prop);
2653                 return -ENOTSUPP;
2654         }
2655
2656         return 0;
2657 }
2658
2659 static int usbpd_dr_prop_writeable(struct dual_role_phy_instance *dual_role,
2660                 enum dual_role_property prop)
2661 {
2662         switch (prop) {
2663         case DUAL_ROLE_PROP_MODE:
2664         case DUAL_ROLE_PROP_DR:
2665         case DUAL_ROLE_PROP_PR:
2666                 return 1;
2667         default:
2668                 break;
2669         }
2670
2671         return 0;
2672 }
2673
2674 static int usbpd_uevent(struct device *dev, struct kobj_uevent_env *env)
2675 {
2676         struct usbpd *pd = dev_get_drvdata(dev);
2677         int i;
2678
2679         add_uevent_var(env, "DATA_ROLE=%s", pd->current_dr == DR_DFP ?
2680                         "dfp" : "ufp");
2681
2682         if (pd->current_pr == PR_SINK) {
2683                 add_uevent_var(env, "POWER_ROLE=sink");
2684                 add_uevent_var(env, "SRC_CAP_ID=%d", pd->src_cap_id);
2685
2686                 for (i = 0; i < ARRAY_SIZE(pd->received_pdos); i++)
2687                         add_uevent_var(env, "PDO%d=%08x", i,
2688                                         pd->received_pdos[i]);
2689
2690                 add_uevent_var(env, "REQUESTED_PDO=%d", pd->requested_pdo);
2691                 add_uevent_var(env, "SELECTED_PDO=%d", pd->selected_pdo);
2692         } else {
2693                 add_uevent_var(env, "POWER_ROLE=source");
2694                 for (i = 0; i < ARRAY_SIZE(default_src_caps); i++)
2695                         add_uevent_var(env, "PDO%d=%08x", i,
2696                                         default_src_caps[i]);
2697         }
2698
2699         add_uevent_var(env, "RDO=%08x", pd->rdo);
2700         add_uevent_var(env, "CONTRACT=%s", pd->in_explicit_contract ?
2701                                 "explicit" : "implicit");
2702         add_uevent_var(env, "ALT_MODE=%d", pd->vdm_state == MODE_ENTERED);
2703
2704         return 0;
2705 }
2706
2707 static ssize_t contract_show(struct device *dev, struct device_attribute *attr,
2708                 char *buf)
2709 {
2710         struct usbpd *pd = dev_get_drvdata(dev);
2711
2712         return snprintf(buf, PAGE_SIZE, "%s\n",
2713                         pd->in_explicit_contract ?  "explicit" : "implicit");
2714 }
2715 static DEVICE_ATTR_RO(contract);
2716
2717 static ssize_t current_pr_show(struct device *dev,
2718                 struct device_attribute *attr, char *buf)
2719 {
2720         struct usbpd *pd = dev_get_drvdata(dev);
2721         const char *pr = "none";
2722
2723         if (pd->current_pr == PR_SINK)
2724                 pr = "sink";
2725         else if (pd->current_pr == PR_SRC)
2726                 pr = "source";
2727
2728         return snprintf(buf, PAGE_SIZE, "%s\n", pr);
2729 }
2730 static DEVICE_ATTR_RO(current_pr);
2731
2732 static ssize_t initial_pr_show(struct device *dev,
2733                 struct device_attribute *attr, char *buf)
2734 {
2735         struct usbpd *pd = dev_get_drvdata(dev);
2736         const char *pr = "none";
2737
2738         if (pd->typec_mode >= POWER_SUPPLY_TYPEC_SOURCE_DEFAULT)
2739                 pr = "sink";
2740         else if (pd->typec_mode >= POWER_SUPPLY_TYPEC_SINK)
2741                 pr = "source";
2742
2743         return snprintf(buf, PAGE_SIZE, "%s\n", pr);
2744 }
2745 static DEVICE_ATTR_RO(initial_pr);
2746
2747 static ssize_t current_dr_show(struct device *dev,
2748                 struct device_attribute *attr, char *buf)
2749 {
2750         struct usbpd *pd = dev_get_drvdata(dev);
2751         const char *dr = "none";
2752
2753         if (pd->current_dr == DR_UFP)
2754                 dr = "ufp";
2755         else if (pd->current_dr == DR_DFP)
2756                 dr = "dfp";
2757
2758         return snprintf(buf, PAGE_SIZE, "%s\n", dr);
2759 }
2760 static DEVICE_ATTR_RO(current_dr);
2761
2762 static ssize_t initial_dr_show(struct device *dev,
2763                 struct device_attribute *attr, char *buf)
2764 {
2765         struct usbpd *pd = dev_get_drvdata(dev);
2766         const char *dr = "none";
2767
2768         if (pd->typec_mode >= POWER_SUPPLY_TYPEC_SOURCE_DEFAULT)
2769                 dr = "ufp";
2770         else if (pd->typec_mode >= POWER_SUPPLY_TYPEC_SINK)
2771                 dr = "dfp";
2772
2773         return snprintf(buf, PAGE_SIZE, "%s\n", dr);
2774 }
2775 static DEVICE_ATTR_RO(initial_dr);
2776
2777 static ssize_t src_cap_id_show(struct device *dev,
2778                 struct device_attribute *attr, char *buf)
2779 {
2780         struct usbpd *pd = dev_get_drvdata(dev);
2781
2782         return snprintf(buf, PAGE_SIZE, "%d\n", pd->src_cap_id);
2783 }
2784 static DEVICE_ATTR_RO(src_cap_id);
2785
2786 /* Dump received source PDOs in human-readable format */
2787 static ssize_t pdo_h_show(struct device *dev, struct device_attribute *attr,
2788                 char *buf)
2789 {
2790         struct usbpd *pd = dev_get_drvdata(dev);
2791         int i;
2792         ssize_t cnt = 0;
2793
2794         for (i = 0; i < ARRAY_SIZE(pd->received_pdos); i++) {
2795                 u32 pdo = pd->received_pdos[i];
2796
2797                 if (pdo == 0)
2798                         break;
2799
2800                 cnt += scnprintf(&buf[cnt], PAGE_SIZE - cnt, "PDO %d\n", i + 1);
2801
2802                 if (PD_SRC_PDO_TYPE(pdo) == PD_SRC_PDO_TYPE_FIXED) {
2803                         cnt += scnprintf(&buf[cnt], PAGE_SIZE - cnt,
2804                                         "\tFixed supply\n"
2805                                         "\tDual-Role Power:%d\n"
2806                                         "\tUSB Suspend Supported:%d\n"
2807                                         "\tExternally Powered:%d\n"
2808                                         "\tUSB Communications Capable:%d\n"
2809                                         "\tData Role Swap:%d\n"
2810                                         "\tPeak Current:%d\n"
2811                                         "\tVoltage:%d (mV)\n"
2812                                         "\tMax Current:%d (mA)\n",
2813                                         PD_SRC_PDO_FIXED_PR_SWAP(pdo),
2814                                         PD_SRC_PDO_FIXED_USB_SUSP(pdo),
2815                                         PD_SRC_PDO_FIXED_EXT_POWERED(pdo),
2816                                         PD_SRC_PDO_FIXED_USB_COMM(pdo),
2817                                         PD_SRC_PDO_FIXED_DR_SWAP(pdo),
2818                                         PD_SRC_PDO_FIXED_PEAK_CURR(pdo),
2819                                         PD_SRC_PDO_FIXED_VOLTAGE(pdo) * 50,
2820                                         PD_SRC_PDO_FIXED_MAX_CURR(pdo) * 10);
2821                 } else if (PD_SRC_PDO_TYPE(pdo) == PD_SRC_PDO_TYPE_BATTERY) {
2822                         cnt += scnprintf(&buf[cnt], PAGE_SIZE - cnt,
2823                                         "\tBattery supply\n"
2824                                         "\tMax Voltage:%d (mV)\n"
2825                                         "\tMin Voltage:%d (mV)\n"
2826                                         "\tMax Power:%d (mW)\n",
2827                                         PD_SRC_PDO_VAR_BATT_MAX_VOLT(pdo) * 50,
2828                                         PD_SRC_PDO_VAR_BATT_MIN_VOLT(pdo) * 50,
2829                                         PD_SRC_PDO_VAR_BATT_MAX(pdo) * 250);
2830                 } else if (PD_SRC_PDO_TYPE(pdo) == PD_SRC_PDO_TYPE_VARIABLE) {
2831                         cnt += scnprintf(&buf[cnt], PAGE_SIZE - cnt,
2832                                         "\tVariable supply\n"
2833                                         "\tMax Voltage:%d (mV)\n"
2834                                         "\tMin Voltage:%d (mV)\n"
2835                                         "\tMax Current:%d (mA)\n",
2836                                         PD_SRC_PDO_VAR_BATT_MAX_VOLT(pdo) * 50,
2837                                         PD_SRC_PDO_VAR_BATT_MIN_VOLT(pdo) * 50,
2838                                         PD_SRC_PDO_VAR_BATT_MAX(pdo) * 10);
2839                 } else if (PD_SRC_PDO_TYPE(pdo) == PD_SRC_PDO_TYPE_AUGMENTED) {
2840                         cnt += scnprintf(&buf[cnt], PAGE_SIZE - cnt,
2841                                         "\tProgrammable Power supply\n"
2842                                         "\tMax Voltage:%d (mV)\n"
2843                                         "\tMin Voltage:%d (mV)\n"
2844                                         "\tMax Current:%d (mA)\n",
2845                                         PD_APDO_MAX_VOLT(pdo) * 100,
2846                                         PD_APDO_MIN_VOLT(pdo) * 100,
2847                                         PD_APDO_MAX_CURR(pdo) * 50);
2848                 } else {
2849                         cnt += scnprintf(&buf[cnt], PAGE_SIZE - cnt,
2850                                         "Invalid PDO\n");
2851                 }
2852
2853                 buf[cnt++] = '\n';
2854         }
2855
2856         return cnt;
2857 }
2858 static DEVICE_ATTR_RO(pdo_h);
2859
2860 static ssize_t pdo_n_show(struct device *dev, struct device_attribute *attr,
2861                 char *buf);
2862
2863 #define PDO_ATTR(n) {                                   \
2864         .attr   = { .name = __stringify(pdo##n), .mode = S_IRUGO },     \
2865         .show   = pdo_n_show,                           \
2866 }
2867 static struct device_attribute dev_attr_pdos[] = {
2868         PDO_ATTR(1),
2869         PDO_ATTR(2),
2870         PDO_ATTR(3),
2871         PDO_ATTR(4),
2872         PDO_ATTR(5),
2873         PDO_ATTR(6),
2874         PDO_ATTR(7),
2875 };
2876
2877 static ssize_t pdo_n_show(struct device *dev, struct device_attribute *attr,
2878                 char *buf)
2879 {
2880         struct usbpd *pd = dev_get_drvdata(dev);
2881         int i;
2882
2883         for (i = 0; i < ARRAY_SIZE(dev_attr_pdos); i++)
2884                 if (attr == &dev_attr_pdos[i])
2885                         /* dump the PDO as a hex string */
2886                         return snprintf(buf, PAGE_SIZE, "%08x\n",
2887                                         pd->received_pdos[i]);
2888
2889         usbpd_err(&pd->dev, "Invalid PDO index\n");
2890         return -EINVAL;
2891 }
2892
2893 static ssize_t select_pdo_store(struct device *dev,
2894                 struct device_attribute *attr, const char *buf, size_t size)
2895 {
2896         struct usbpd *pd = dev_get_drvdata(dev);
2897         int src_cap_id;
2898         int pdo, uv = 0, ua = 0;
2899         int ret;
2900
2901         mutex_lock(&pd->swap_lock);
2902
2903         /* Only allowed if we are already in explicit sink contract */
2904         if (pd->current_state != PE_SNK_READY || !is_sink_tx_ok(pd)) {
2905                 usbpd_err(&pd->dev, "select_pdo: Cannot select new PDO yet\n");
2906                 ret = -EBUSY;
2907                 goto out;
2908         }
2909
2910         ret = sscanf(buf, "%d %d %d %d", &src_cap_id, &pdo, &uv, &ua);
2911         if (ret != 2 && ret != 4) {
2912                 usbpd_err(&pd->dev, "select_pdo: Must specify <src cap id> <PDO> [<uV> <uA>]\n");
2913                 ret = -EINVAL;
2914                 goto out;
2915         }
2916
2917         if (src_cap_id != pd->src_cap_id) {
2918                 usbpd_err(&pd->dev, "select_pdo: src_cap_id mismatch.  Requested:%d, current:%d\n",
2919                                 src_cap_id, pd->src_cap_id);
2920                 ret = -EINVAL;
2921                 goto out;
2922         }
2923
2924         if (pdo < 1 || pdo > 7) {
2925                 usbpd_err(&pd->dev, "select_pdo: invalid PDO:%d\n", pdo);
2926                 ret = -EINVAL;
2927                 goto out;
2928         }
2929
2930         ret = pd_select_pdo(pd, pdo, uv, ua);
2931         if (ret)
2932                 goto out;
2933
2934         reinit_completion(&pd->is_ready);
2935         pd->send_request = true;
2936         kick_sm(pd, 0);
2937
2938         /* wait for operation to complete */
2939         if (!wait_for_completion_timeout(&pd->is_ready,
2940                         msecs_to_jiffies(1000))) {
2941                 usbpd_err(&pd->dev, "select_pdo: request timed out\n");
2942                 ret = -ETIMEDOUT;
2943                 goto out;
2944         }
2945
2946         /* determine if request was accepted/rejected */
2947         if (pd->selected_pdo != pd->requested_pdo ||
2948                         pd->current_voltage != pd->requested_voltage) {
2949                 usbpd_err(&pd->dev, "select_pdo: request rejected\n");
2950                 ret = -EINVAL;
2951         }
2952
2953 out:
2954         pd->send_request = false;
2955         mutex_unlock(&pd->swap_lock);
2956         return ret ? ret : size;
2957 }
2958
2959 static ssize_t select_pdo_show(struct device *dev,
2960                 struct device_attribute *attr, char *buf)
2961 {
2962         struct usbpd *pd = dev_get_drvdata(dev);
2963
2964         return snprintf(buf, PAGE_SIZE, "%d\n", pd->selected_pdo);
2965 }
2966 static DEVICE_ATTR_RW(select_pdo);
2967
2968 static ssize_t rdo_show(struct device *dev, struct device_attribute *attr,
2969                 char *buf)
2970 {
2971         struct usbpd *pd = dev_get_drvdata(dev);
2972
2973         /* dump the RDO as a hex string */
2974         return snprintf(buf, PAGE_SIZE, "%08x\n", pd->rdo);
2975 }
2976 static DEVICE_ATTR_RO(rdo);
2977
2978 static ssize_t rdo_h_show(struct device *dev, struct device_attribute *attr,
2979                 char *buf)
2980 {
2981         struct usbpd *pd = dev_get_drvdata(dev);
2982         int pos = PD_RDO_OBJ_POS(pd->rdo);
2983         int type = PD_SRC_PDO_TYPE(pd->received_pdos[pos]);
2984         int len;
2985
2986         len = scnprintf(buf, PAGE_SIZE, "Request Data Object\n"
2987                         "\tObj Pos:%d\n"
2988                         "\tGiveback:%d\n"
2989                         "\tCapability Mismatch:%d\n"
2990                         "\tUSB Communications Capable:%d\n"
2991                         "\tNo USB Suspend:%d\n",
2992                         PD_RDO_OBJ_POS(pd->rdo),
2993                         PD_RDO_GIVEBACK(pd->rdo),
2994                         PD_RDO_MISMATCH(pd->rdo),
2995                         PD_RDO_USB_COMM(pd->rdo),
2996                         PD_RDO_NO_USB_SUSP(pd->rdo));
2997
2998         switch (type) {
2999         case PD_SRC_PDO_TYPE_FIXED:
3000         case PD_SRC_PDO_TYPE_VARIABLE:
3001                 len += scnprintf(buf + len, PAGE_SIZE - len,
3002                                 "(Fixed/Variable)\n"
3003                                 "\tOperating Current:%d (mA)\n"
3004                                 "\t%s Current:%d (mA)\n",
3005                                 PD_RDO_FIXED_CURR(pd->rdo) * 10,
3006                                 PD_RDO_GIVEBACK(pd->rdo) ? "Min" : "Max",
3007                                 PD_RDO_FIXED_CURR_MINMAX(pd->rdo) * 10);
3008                 break;
3009
3010         case PD_SRC_PDO_TYPE_BATTERY:
3011                 len += scnprintf(buf + len, PAGE_SIZE - len,
3012                                 "(Battery)\n"
3013                                 "\tOperating Power:%d (mW)\n"
3014                                 "\t%s Power:%d (mW)\n",
3015                                 PD_RDO_FIXED_CURR(pd->rdo) * 250,
3016                                 PD_RDO_GIVEBACK(pd->rdo) ? "Min" : "Max",
3017                                 PD_RDO_FIXED_CURR_MINMAX(pd->rdo) * 250);
3018                 break;
3019
3020         case PD_SRC_PDO_TYPE_AUGMENTED:
3021                 len += scnprintf(buf + len, PAGE_SIZE - len,
3022                                 "(Programmable)\n"
3023                                 "\tOutput Voltage:%d (mV)\n"
3024                                 "\tOperating Current:%d (mA)\n",
3025                                 PD_RDO_PROG_VOLTAGE(pd->rdo) * 20,
3026                                 PD_RDO_PROG_CURR(pd->rdo) * 50);
3027                 break;
3028         }
3029
3030         return len;
3031 }
3032 static DEVICE_ATTR_RO(rdo_h);
3033
3034 static ssize_t hard_reset_store(struct device *dev,
3035                 struct device_attribute *attr, const char *buf, size_t size)
3036 {
3037         struct usbpd *pd = dev_get_drvdata(dev);
3038         int val = 0;
3039
3040         if (sscanf(buf, "%d\n", &val) != 1)
3041                 return -EINVAL;
3042
3043         if (val)
3044                 usbpd_set_state(pd, pd->current_pr == PR_SRC ?
3045                                 PE_SRC_HARD_RESET : PE_SNK_HARD_RESET);
3046
3047         return size;
3048 }
3049 static DEVICE_ATTR_WO(hard_reset);
3050
3051 static struct attribute *usbpd_attrs[] = {
3052         &dev_attr_contract.attr,
3053         &dev_attr_initial_pr.attr,
3054         &dev_attr_current_pr.attr,
3055         &dev_attr_initial_dr.attr,
3056         &dev_attr_current_dr.attr,
3057         &dev_attr_src_cap_id.attr,
3058         &dev_attr_pdo_h.attr,
3059         &dev_attr_pdos[0].attr,
3060         &dev_attr_pdos[1].attr,
3061         &dev_attr_pdos[2].attr,
3062         &dev_attr_pdos[3].attr,
3063         &dev_attr_pdos[4].attr,
3064         &dev_attr_pdos[5].attr,
3065         &dev_attr_pdos[6].attr,
3066         &dev_attr_select_pdo.attr,
3067         &dev_attr_rdo.attr,
3068         &dev_attr_rdo_h.attr,
3069         &dev_attr_hard_reset.attr,
3070         NULL,
3071 };
3072 ATTRIBUTE_GROUPS(usbpd);
3073
3074 static struct class usbpd_class = {
3075         .name = "usbpd",
3076         .owner = THIS_MODULE,
3077         .dev_uevent = usbpd_uevent,
3078         .dev_groups = usbpd_groups,
3079 };
3080
3081 static int match_usbpd_device(struct device *dev, const void *data)
3082 {
3083         return dev->parent == data;
3084 }
3085
3086 static void devm_usbpd_put(struct device *dev, void *res)
3087 {
3088         struct usbpd **ppd = res;
3089
3090         put_device(&(*ppd)->dev);
3091 }
3092
3093 struct usbpd *devm_usbpd_get_by_phandle(struct device *dev, const char *phandle)
3094 {
3095         struct usbpd **ptr, *pd = NULL;
3096         struct device_node *pd_np;
3097         struct platform_device *pdev;
3098         struct device *pd_dev;
3099
3100         if (!usbpd_class.p) /* usbpd_init() not yet called */
3101                 return ERR_PTR(-EAGAIN);
3102
3103         if (!dev->of_node)
3104                 return ERR_PTR(-EINVAL);
3105
3106         pd_np = of_parse_phandle(dev->of_node, phandle, 0);
3107         if (!pd_np)
3108                 return ERR_PTR(-ENXIO);
3109
3110         pdev = of_find_device_by_node(pd_np);
3111         if (!pdev)
3112                 return ERR_PTR(-ENODEV);
3113
3114         pd_dev = class_find_device(&usbpd_class, NULL, &pdev->dev,
3115                         match_usbpd_device);
3116         if (!pd_dev) {
3117                 platform_device_put(pdev);
3118                 /* device was found but maybe hadn't probed yet, so defer */
3119                 return ERR_PTR(-EPROBE_DEFER);
3120         }
3121
3122         ptr = devres_alloc(devm_usbpd_put, sizeof(*ptr), GFP_KERNEL);
3123         if (!ptr) {
3124                 put_device(pd_dev);
3125                 platform_device_put(pdev);
3126                 return ERR_PTR(-ENOMEM);
3127         }
3128
3129         pd = dev_get_drvdata(pd_dev);
3130         if (!pd)
3131                 return ERR_PTR(-EPROBE_DEFER);
3132
3133         *ptr = pd;
3134         devres_add(dev, ptr);
3135
3136         return pd;
3137 }
3138 EXPORT_SYMBOL(devm_usbpd_get_by_phandle);
3139
3140 static int num_pd_instances;
3141
3142 /**
3143  * usbpd_create - Create a new instance of USB PD protocol/policy engine
3144  * @parent - parent device to associate with
3145  *
3146  * This creates a new usbpd class device which manages the state of a
3147  * USB PD-capable port. The parent device that is passed in should be
3148  * associated with the physical device port, e.g. a PD PHY.
3149  *
3150  * Return: struct usbpd pointer, or an ERR_PTR value
3151  */
3152 struct usbpd *usbpd_create(struct device *parent)
3153 {
3154         int ret;
3155         struct usbpd *pd;
3156
3157         pd = kzalloc(sizeof(*pd), GFP_KERNEL);
3158         if (!pd)
3159                 return ERR_PTR(-ENOMEM);
3160
3161         device_initialize(&pd->dev);
3162         pd->dev.class = &usbpd_class;
3163         pd->dev.parent = parent;
3164         dev_set_drvdata(&pd->dev, pd);
3165
3166         ret = dev_set_name(&pd->dev, "usbpd%d", num_pd_instances++);
3167         if (ret)
3168                 goto free_pd;
3169
3170         ret = device_init_wakeup(&pd->dev, true);
3171         if (ret)
3172                 goto free_pd;
3173
3174         ret = device_add(&pd->dev);
3175         if (ret)
3176                 goto free_pd;
3177
3178         pd->wq = alloc_ordered_workqueue("usbpd_wq", WQ_FREEZABLE);
3179         if (!pd->wq) {
3180                 ret = -ENOMEM;
3181                 goto del_pd;
3182         }
3183         INIT_WORK(&pd->sm_work, usbpd_sm);
3184         hrtimer_init(&pd->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3185         pd->timer.function = pd_timeout;
3186         mutex_init(&pd->swap_lock);
3187
3188         pd->usb_psy = power_supply_get_by_name("usb");
3189         if (!pd->usb_psy) {
3190                 usbpd_dbg(&pd->dev, "Could not get USB power_supply, deferring probe\n");
3191                 ret = -EPROBE_DEFER;
3192                 goto destroy_wq;
3193         }
3194
3195         /*
3196          * associate extcon with the parent dev as it could have a DT
3197          * node which will be useful for extcon_get_edev_by_phandle()
3198          */
3199         pd->extcon = devm_extcon_dev_allocate(parent, usbpd_extcon_cable);
3200         if (IS_ERR(pd->extcon)) {
3201                 usbpd_err(&pd->dev, "failed to allocate extcon device\n");
3202                 ret = PTR_ERR(pd->extcon);
3203                 goto put_psy;
3204         }
3205
3206         pd->extcon->mutually_exclusive = usbpd_extcon_exclusive;
3207         ret = devm_extcon_dev_register(parent, pd->extcon);
3208         if (ret) {
3209                 usbpd_err(&pd->dev, "failed to register extcon device\n");
3210                 goto put_psy;
3211         }
3212
3213         pd->vbus = devm_regulator_get(parent, "vbus");
3214         if (IS_ERR(pd->vbus)) {
3215                 ret = PTR_ERR(pd->vbus);
3216                 goto put_psy;
3217         }
3218
3219         pd->vconn = devm_regulator_get(parent, "vconn");
3220         if (IS_ERR(pd->vconn)) {
3221                 ret = PTR_ERR(pd->vconn);
3222                 goto put_psy;
3223         }
3224
3225         pd->vconn_is_external = device_property_present(parent,
3226                                         "qcom,vconn-uses-external-source");
3227
3228         pd->num_sink_caps = device_property_read_u32_array(parent,
3229                         "qcom,default-sink-caps", NULL, 0);
3230         if (pd->num_sink_caps > 0) {
3231                 int i;
3232                 u32 sink_caps[14];
3233
3234                 if (pd->num_sink_caps % 2 || pd->num_sink_caps > 14) {
3235                         ret = -EINVAL;
3236                         usbpd_err(&pd->dev, "default-sink-caps must be be specified as voltage/current, max 7 pairs\n");
3237                         goto put_psy;
3238                 }
3239
3240                 ret = device_property_read_u32_array(parent,
3241                                 "qcom,default-sink-caps", sink_caps,
3242                                 pd->num_sink_caps);
3243                 if (ret) {
3244                         usbpd_err(&pd->dev, "Error reading default-sink-caps\n");
3245                         goto put_psy;
3246                 }
3247
3248                 pd->num_sink_caps /= 2;
3249
3250                 for (i = 0; i < pd->num_sink_caps; i++) {
3251                         int v = sink_caps[i * 2] / 50;
3252                         int c = sink_caps[i * 2 + 1] / 10;
3253
3254                         pd->sink_caps[i] =
3255                                 PD_SNK_PDO_FIXED(0, 0, 0, 0, 0, v, c);
3256                 }
3257
3258                 /* First PDO includes additional capabilities */
3259                 pd->sink_caps[0] |= PD_SNK_PDO_FIXED(1, 0, 0, 1, 1, 0, 0);
3260         } else {
3261                 memcpy(pd->sink_caps, default_snk_caps,
3262                                 sizeof(default_snk_caps));
3263                 pd->num_sink_caps = ARRAY_SIZE(default_snk_caps);
3264         }
3265
3266         /*
3267          * Register the Android dual-role class (/sys/class/dual_role_usb/).
3268          * The first instance should be named "otg_default" as that's what
3269          * Android expects.
3270          * Note this is different than the /sys/class/usbpd/ created above.
3271          */
3272         pd->dr_desc.name = (num_pd_instances == 1) ?
3273                                 "otg_default" : dev_name(&pd->dev);
3274         pd->dr_desc.supported_modes = DUAL_ROLE_SUPPORTED_MODES_DFP_AND_UFP;
3275         pd->dr_desc.properties = usbpd_dr_properties;
3276         pd->dr_desc.num_properties = ARRAY_SIZE(usbpd_dr_properties);
3277         pd->dr_desc.get_property = usbpd_dr_get_property;
3278         pd->dr_desc.set_property = usbpd_dr_set_property;
3279         pd->dr_desc.property_is_writeable = usbpd_dr_prop_writeable;
3280
3281         pd->dual_role = devm_dual_role_instance_register(&pd->dev,
3282                         &pd->dr_desc);
3283         if (IS_ERR(pd->dual_role)) {
3284                 usbpd_err(&pd->dev, "could not register dual_role instance\n");
3285                 goto put_psy;
3286         } else {
3287                 pd->dual_role->drv_data = pd;
3288         }
3289
3290         pd->current_pr = PR_NONE;
3291         pd->current_dr = DR_NONE;
3292         list_add_tail(&pd->instance, &_usbpd);
3293
3294         spin_lock_init(&pd->rx_lock);
3295         INIT_LIST_HEAD(&pd->rx_q);
3296         INIT_LIST_HEAD(&pd->svid_handlers);
3297         init_completion(&pd->is_ready);
3298
3299         pd->psy_nb.notifier_call = psy_changed;
3300         ret = power_supply_reg_notifier(&pd->psy_nb);
3301         if (ret)
3302                 goto del_inst;
3303
3304         /* force read initial power_supply values */
3305         psy_changed(&pd->psy_nb, PSY_EVENT_PROP_CHANGED, pd->usb_psy);
3306
3307         return pd;
3308
3309 del_inst:
3310         list_del(&pd->instance);
3311 put_psy:
3312         power_supply_put(pd->usb_psy);
3313 destroy_wq:
3314         destroy_workqueue(pd->wq);
3315 del_pd:
3316         device_del(&pd->dev);
3317 free_pd:
3318         num_pd_instances--;
3319         kfree(pd);
3320         return ERR_PTR(ret);
3321 }
3322 EXPORT_SYMBOL(usbpd_create);
3323
3324 /**
3325  * usbpd_destroy - Removes and frees a usbpd instance
3326  * @pd: the instance to destroy
3327  */
3328 void usbpd_destroy(struct usbpd *pd)
3329 {
3330         if (!pd)
3331                 return;
3332
3333         list_del(&pd->instance);
3334         power_supply_unreg_notifier(&pd->psy_nb);
3335         power_supply_put(pd->usb_psy);
3336         destroy_workqueue(pd->wq);
3337         device_del(&pd->dev);
3338         kfree(pd);
3339 }
3340 EXPORT_SYMBOL(usbpd_destroy);
3341
3342 static int __init usbpd_init(void)
3343 {
3344         usbpd_ipc_log = ipc_log_context_create(NUM_LOG_PAGES, "usb_pd", 0);
3345         return class_register(&usbpd_class);
3346 }
3347 module_init(usbpd_init);
3348
3349 static void __exit usbpd_exit(void)
3350 {
3351         class_unregister(&usbpd_class);
3352 }
3353 module_exit(usbpd_exit);
3354
3355 MODULE_DESCRIPTION("USB Power Delivery Policy Engine");
3356 MODULE_LICENSE("GPL v2");