1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright 2020 Google LLC
4  *
5  * This driver provides the ability to view and manage Type C ports through the
6  * Chrome OS EC.
7  */
8 
9 #include <linux/acpi.h>
10 #include <linux/list.h>
11 #include <linux/module.h>
12 #include <linux/of.h>
13 #include <linux/platform_data/cros_ec_commands.h>
14 #include <linux/platform_data/cros_ec_proto.h>
15 #include <linux/platform_data/cros_usbpd_notify.h>
16 #include <linux/platform_device.h>
17 #include <linux/usb/pd.h>
18 #include <linux/usb/pd_vdo.h>
19 #include <linux/usb/typec.h>
20 #include <linux/usb/typec_altmode.h>
21 #include <linux/usb/typec_dp.h>
22 #include <linux/usb/typec_mux.h>
23 #include <linux/usb/typec_tbt.h>
24 #include <linux/usb/role.h>
25 
26 #define DRV_NAME "cros-ec-typec"
27 
28 /* Supported alt modes. */
29 enum {
30 	CROS_EC_ALTMODE_DP = 0,
31 	CROS_EC_ALTMODE_TBT,
32 	CROS_EC_ALTMODE_MAX,
33 };
34 
35 /* Container for altmode pointer nodes. */
36 struct cros_typec_altmode_node {
37 	struct typec_altmode *amode;
38 	struct list_head list;
39 };
40 
41 /* Per port data. */
42 struct cros_typec_port {
43 	struct typec_port *port;
44 	/* Initial capabilities for the port. */
45 	struct typec_capability caps;
46 	struct typec_partner *partner;
47 	struct typec_cable *cable;
48 	/* SOP' plug. */
49 	struct typec_plug *plug;
50 	/* Port partner PD identity info. */
51 	struct usb_pd_identity p_identity;
52 	/* Port cable PD identity info. */
53 	struct usb_pd_identity c_identity;
54 	struct typec_switch *ori_sw;
55 	struct typec_mux *mux;
56 	struct usb_role_switch *role_sw;
57 
58 	/* Variables keeping track of switch state. */
59 	struct typec_mux_state state;
60 	uint8_t mux_flags;
61 	uint8_t role;
62 
63 	/* Port alt modes. */
64 	struct typec_altmode p_altmode[CROS_EC_ALTMODE_MAX];
65 
66 	/* Flag indicating that PD partner discovery data parsing is completed. */
67 	bool sop_disc_done;
68 	bool sop_prime_disc_done;
69 	struct ec_response_typec_discovery *disc_data;
70 	struct list_head partner_mode_list;
71 	struct list_head plug_mode_list;
72 };
73 
74 /* Platform-specific data for the Chrome OS EC Type C controller. */
75 struct cros_typec_data {
76 	struct device *dev;
77 	struct cros_ec_device *ec;
78 	int num_ports;
79 	unsigned int pd_ctrl_ver;
80 	/* Array of ports, indexed by port number. */
81 	struct cros_typec_port *ports[EC_USB_PD_MAX_PORTS];
82 	struct notifier_block nb;
83 	struct work_struct port_work;
84 	bool typec_cmd_supported;
85 	bool needs_mux_ack;
86 };
87 
88 static int cros_typec_parse_port_props(struct typec_capability *cap,
89 				       struct fwnode_handle *fwnode,
90 				       struct device *dev)
91 {
92 	const char *buf;
93 	int ret;
94 
95 	memset(cap, 0, sizeof(*cap));
96 	ret = fwnode_property_read_string(fwnode, "power-role", &buf);
97 	if (ret) {
98 		dev_err(dev, "power-role not found: %d\n", ret);
99 		return ret;
100 	}
101 
102 	ret = typec_find_port_power_role(buf);
103 	if (ret < 0)
104 		return ret;
105 	cap->type = ret;
106 
107 	ret = fwnode_property_read_string(fwnode, "data-role", &buf);
108 	if (ret) {
109 		dev_err(dev, "data-role not found: %d\n", ret);
110 		return ret;
111 	}
112 
113 	ret = typec_find_port_data_role(buf);
114 	if (ret < 0)
115 		return ret;
116 	cap->data = ret;
117 
118 	ret = fwnode_property_read_string(fwnode, "try-power-role", &buf);
119 	if (ret) {
120 		dev_err(dev, "try-power-role not found: %d\n", ret);
121 		return ret;
122 	}
123 
124 	ret = typec_find_power_role(buf);
125 	if (ret < 0)
126 		return ret;
127 	cap->prefer_role = ret;
128 
129 	cap->fwnode = fwnode;
130 
131 	return 0;
132 }
133 
134 static int cros_typec_get_switch_handles(struct cros_typec_port *port,
135 					 struct fwnode_handle *fwnode,
136 					 struct device *dev)
137 {
138 	port->mux = fwnode_typec_mux_get(fwnode, NULL);
139 	if (IS_ERR(port->mux)) {
140 		dev_dbg(dev, "Mux handle not found.\n");
141 		goto mux_err;
142 	}
143 
144 	port->ori_sw = fwnode_typec_switch_get(fwnode);
145 	if (IS_ERR(port->ori_sw)) {
146 		dev_dbg(dev, "Orientation switch handle not found.\n");
147 		goto ori_sw_err;
148 	}
149 
150 	port->role_sw = fwnode_usb_role_switch_get(fwnode);
151 	if (IS_ERR(port->role_sw)) {
152 		dev_dbg(dev, "USB role switch handle not found.\n");
153 		goto role_sw_err;
154 	}
155 
156 	return 0;
157 
158 role_sw_err:
159 	usb_role_switch_put(port->role_sw);
160 ori_sw_err:
161 	typec_switch_put(port->ori_sw);
162 mux_err:
163 	typec_mux_put(port->mux);
164 
165 	return -ENODEV;
166 }
167 
168 static int cros_typec_add_partner(struct cros_typec_data *typec, int port_num,
169 				  bool pd_en)
170 {
171 	struct cros_typec_port *port = typec->ports[port_num];
172 	struct typec_partner_desc p_desc = {
173 		.usb_pd = pd_en,
174 	};
175 	int ret = 0;
176 
177 	/*
178 	 * Fill an initial PD identity, which will then be updated with info
179 	 * from the EC.
180 	 */
181 	p_desc.identity = &port->p_identity;
182 
183 	port->partner = typec_register_partner(port->port, &p_desc);
184 	if (IS_ERR(port->partner)) {
185 		ret = PTR_ERR(port->partner);
186 		port->partner = NULL;
187 	}
188 
189 	return ret;
190 }
191 
192 static void cros_typec_unregister_altmodes(struct cros_typec_data *typec, int port_num,
193 					   bool is_partner)
194 {
195 	struct cros_typec_port *port = typec->ports[port_num];
196 	struct cros_typec_altmode_node *node, *tmp;
197 	struct list_head *head;
198 
199 	head = is_partner ? &port->partner_mode_list : &port->plug_mode_list;
200 	list_for_each_entry_safe(node, tmp, head, list) {
201 		list_del(&node->list);
202 		typec_unregister_altmode(node->amode);
203 		devm_kfree(typec->dev, node);
204 	}
205 }
206 
207 static int cros_typec_usb_disconnect_state(struct cros_typec_port *port)
208 {
209 	port->state.alt = NULL;
210 	port->state.mode = TYPEC_STATE_USB;
211 	port->state.data = NULL;
212 
213 	usb_role_switch_set_role(port->role_sw, USB_ROLE_NONE);
214 	typec_switch_set(port->ori_sw, TYPEC_ORIENTATION_NONE);
215 
216 	return typec_mux_set(port->mux, &port->state);
217 }
218 
219 static void cros_typec_remove_partner(struct cros_typec_data *typec,
220 				      int port_num)
221 {
222 	struct cros_typec_port *port = typec->ports[port_num];
223 
224 	if (!port->partner)
225 		return;
226 
227 	cros_typec_unregister_altmodes(typec, port_num, true);
228 
229 	cros_typec_usb_disconnect_state(port);
230 
231 	typec_unregister_partner(port->partner);
232 	port->partner = NULL;
233 	memset(&port->p_identity, 0, sizeof(port->p_identity));
234 	port->sop_disc_done = false;
235 }
236 
237 static void cros_typec_remove_cable(struct cros_typec_data *typec,
238 				    int port_num)
239 {
240 	struct cros_typec_port *port = typec->ports[port_num];
241 
242 	if (!port->cable)
243 		return;
244 
245 	cros_typec_unregister_altmodes(typec, port_num, false);
246 
247 	typec_unregister_plug(port->plug);
248 	port->plug = NULL;
249 	typec_unregister_cable(port->cable);
250 	port->cable = NULL;
251 	memset(&port->c_identity, 0, sizeof(port->c_identity));
252 	port->sop_prime_disc_done = false;
253 }
254 
255 static void cros_unregister_ports(struct cros_typec_data *typec)
256 {
257 	int i;
258 
259 	for (i = 0; i < typec->num_ports; i++) {
260 		if (!typec->ports[i])
261 			continue;
262 
263 		cros_typec_remove_partner(typec, i);
264 		cros_typec_remove_cable(typec, i);
265 
266 		usb_role_switch_put(typec->ports[i]->role_sw);
267 		typec_switch_put(typec->ports[i]->ori_sw);
268 		typec_mux_put(typec->ports[i]->mux);
269 		typec_unregister_port(typec->ports[i]->port);
270 	}
271 }
272 
273 /*
274  * Fake the alt mode structs until we actually start registering Type C port
275  * and partner alt modes.
276  */
277 static void cros_typec_register_port_altmodes(struct cros_typec_data *typec,
278 					      int port_num)
279 {
280 	struct cros_typec_port *port = typec->ports[port_num];
281 
282 	/* All PD capable CrOS devices are assumed to support DP altmode. */
283 	port->p_altmode[CROS_EC_ALTMODE_DP].svid = USB_TYPEC_DP_SID;
284 	port->p_altmode[CROS_EC_ALTMODE_DP].mode = USB_TYPEC_DP_MODE;
285 
286 	/*
287 	 * Register TBT compatibility alt mode. The EC will not enter the mode
288 	 * if it doesn't support it, so it's safe to register it unconditionally
289 	 * here for now.
290 	 */
291 	port->p_altmode[CROS_EC_ALTMODE_TBT].svid = USB_TYPEC_TBT_SID;
292 	port->p_altmode[CROS_EC_ALTMODE_TBT].mode = TYPEC_ANY_MODE;
293 
294 	port->state.alt = NULL;
295 	port->state.mode = TYPEC_STATE_USB;
296 	port->state.data = NULL;
297 }
298 
299 static int cros_typec_init_ports(struct cros_typec_data *typec)
300 {
301 	struct device *dev = typec->dev;
302 	struct typec_capability *cap;
303 	struct fwnode_handle *fwnode;
304 	struct cros_typec_port *cros_port;
305 	const char *port_prop;
306 	int ret;
307 	int nports;
308 	u32 port_num = 0;
309 
310 	nports = device_get_child_node_count(dev);
311 	if (nports == 0) {
312 		dev_err(dev, "No port entries found.\n");
313 		return -ENODEV;
314 	}
315 
316 	if (nports > typec->num_ports) {
317 		dev_err(dev, "More ports listed than can be supported.\n");
318 		return -EINVAL;
319 	}
320 
321 	/* DT uses "reg" to specify port number. */
322 	port_prop = dev->of_node ? "reg" : "port-number";
323 	device_for_each_child_node(dev, fwnode) {
324 		if (fwnode_property_read_u32(fwnode, port_prop, &port_num)) {
325 			ret = -EINVAL;
326 			dev_err(dev, "No port-number for port, aborting.\n");
327 			goto unregister_ports;
328 		}
329 
330 		if (port_num >= typec->num_ports) {
331 			dev_err(dev, "Invalid port number.\n");
332 			ret = -EINVAL;
333 			goto unregister_ports;
334 		}
335 
336 		dev_dbg(dev, "Registering port %d\n", port_num);
337 
338 		cros_port = devm_kzalloc(dev, sizeof(*cros_port), GFP_KERNEL);
339 		if (!cros_port) {
340 			ret = -ENOMEM;
341 			goto unregister_ports;
342 		}
343 
344 		typec->ports[port_num] = cros_port;
345 		cap = &cros_port->caps;
346 
347 		ret = cros_typec_parse_port_props(cap, fwnode, dev);
348 		if (ret < 0)
349 			goto unregister_ports;
350 
351 		cros_port->port = typec_register_port(dev, cap);
352 		if (IS_ERR(cros_port->port)) {
353 			dev_err(dev, "Failed to register port %d\n", port_num);
354 			ret = PTR_ERR(cros_port->port);
355 			goto unregister_ports;
356 		}
357 
358 		ret = cros_typec_get_switch_handles(cros_port, fwnode, dev);
359 		if (ret)
360 			dev_dbg(dev, "No switch control for port %d\n",
361 				port_num);
362 
363 		cros_typec_register_port_altmodes(typec, port_num);
364 
365 		cros_port->disc_data = devm_kzalloc(dev, EC_PROTO2_MAX_RESPONSE_SIZE, GFP_KERNEL);
366 		if (!cros_port->disc_data) {
367 			ret = -ENOMEM;
368 			goto unregister_ports;
369 		}
370 
371 		INIT_LIST_HEAD(&cros_port->partner_mode_list);
372 		INIT_LIST_HEAD(&cros_port->plug_mode_list);
373 	}
374 
375 	return 0;
376 
377 unregister_ports:
378 	cros_unregister_ports(typec);
379 	return ret;
380 }
381 
382 static int cros_typec_usb_safe_state(struct cros_typec_port *port)
383 {
384 	port->state.mode = TYPEC_STATE_SAFE;
385 
386 	return typec_mux_set(port->mux, &port->state);
387 }
388 
389 /*
390  * Spoof the VDOs that were likely communicated by the partner for TBT alt
391  * mode.
392  */
393 static int cros_typec_enable_tbt(struct cros_typec_data *typec,
394 				 int port_num,
395 				 struct ec_response_usb_pd_control_v2 *pd_ctrl)
396 {
397 	struct cros_typec_port *port = typec->ports[port_num];
398 	struct typec_thunderbolt_data data;
399 	int ret;
400 
401 	if (typec->pd_ctrl_ver < 2) {
402 		dev_err(typec->dev,
403 			"PD_CTRL version too old: %d\n", typec->pd_ctrl_ver);
404 		return -ENOTSUPP;
405 	}
406 
407 	/* Device Discover Mode VDO */
408 	data.device_mode = TBT_MODE;
409 
410 	if (pd_ctrl->control_flags & USB_PD_CTRL_TBT_LEGACY_ADAPTER)
411 		data.device_mode = TBT_SET_ADAPTER(TBT_ADAPTER_TBT3);
412 
413 	/* Cable Discover Mode VDO */
414 	data.cable_mode = TBT_MODE;
415 	data.cable_mode |= TBT_SET_CABLE_SPEED(pd_ctrl->cable_speed);
416 
417 	if (pd_ctrl->control_flags & USB_PD_CTRL_OPTICAL_CABLE)
418 		data.cable_mode |= TBT_CABLE_OPTICAL;
419 
420 	if (pd_ctrl->control_flags & USB_PD_CTRL_ACTIVE_LINK_UNIDIR)
421 		data.cable_mode |= TBT_CABLE_LINK_TRAINING;
422 
423 	data.cable_mode |= TBT_SET_CABLE_ROUNDED(pd_ctrl->cable_gen);
424 
425 	/* Enter Mode VDO */
426 	data.enter_vdo = TBT_SET_CABLE_SPEED(pd_ctrl->cable_speed);
427 
428 	if (pd_ctrl->control_flags & USB_PD_CTRL_ACTIVE_CABLE)
429 		data.enter_vdo |= TBT_ENTER_MODE_ACTIVE_CABLE;
430 
431 	if (!port->state.alt) {
432 		port->state.alt = &port->p_altmode[CROS_EC_ALTMODE_TBT];
433 		ret = cros_typec_usb_safe_state(port);
434 		if (ret)
435 			return ret;
436 	}
437 
438 	port->state.data = &data;
439 	port->state.mode = TYPEC_TBT_MODE;
440 
441 	return typec_mux_set(port->mux, &port->state);
442 }
443 
444 /* Spoof the VDOs that were likely communicated by the partner. */
445 static int cros_typec_enable_dp(struct cros_typec_data *typec,
446 				int port_num,
447 				struct ec_response_usb_pd_control_v2 *pd_ctrl)
448 {
449 	struct cros_typec_port *port = typec->ports[port_num];
450 	struct typec_displayport_data dp_data;
451 	int ret;
452 
453 	if (typec->pd_ctrl_ver < 2) {
454 		dev_err(typec->dev,
455 			"PD_CTRL version too old: %d\n", typec->pd_ctrl_ver);
456 		return -ENOTSUPP;
457 	}
458 
459 	if (!pd_ctrl->dp_mode) {
460 		dev_err(typec->dev, "No valid DP mode provided.\n");
461 		return -EINVAL;
462 	}
463 
464 	/* Status VDO. */
465 	dp_data.status = DP_STATUS_ENABLED;
466 	if (port->mux_flags & USB_PD_MUX_HPD_IRQ)
467 		dp_data.status |= DP_STATUS_IRQ_HPD;
468 	if (port->mux_flags & USB_PD_MUX_HPD_LVL)
469 		dp_data.status |= DP_STATUS_HPD_STATE;
470 
471 	/* Configuration VDO. */
472 	dp_data.conf = DP_CONF_SET_PIN_ASSIGN(pd_ctrl->dp_mode);
473 	if (!port->state.alt) {
474 		port->state.alt = &port->p_altmode[CROS_EC_ALTMODE_DP];
475 		ret = cros_typec_usb_safe_state(port);
476 		if (ret)
477 			return ret;
478 	}
479 
480 	port->state.data = &dp_data;
481 	port->state.mode = TYPEC_MODAL_STATE(ffs(pd_ctrl->dp_mode));
482 
483 	return typec_mux_set(port->mux, &port->state);
484 }
485 
486 static int cros_typec_enable_usb4(struct cros_typec_data *typec,
487 				  int port_num,
488 				  struct ec_response_usb_pd_control_v2 *pd_ctrl)
489 {
490 	struct cros_typec_port *port = typec->ports[port_num];
491 	struct enter_usb_data data;
492 
493 	data.eudo = EUDO_USB_MODE_USB4 << EUDO_USB_MODE_SHIFT;
494 
495 	/* Cable Speed */
496 	data.eudo |= pd_ctrl->cable_speed << EUDO_CABLE_SPEED_SHIFT;
497 
498 	/* Cable Type */
499 	if (pd_ctrl->control_flags & USB_PD_CTRL_OPTICAL_CABLE)
500 		data.eudo |= EUDO_CABLE_TYPE_OPTICAL << EUDO_CABLE_TYPE_SHIFT;
501 	else if (pd_ctrl->control_flags & USB_PD_CTRL_ACTIVE_CABLE)
502 		data.eudo |= EUDO_CABLE_TYPE_RE_TIMER << EUDO_CABLE_TYPE_SHIFT;
503 
504 	data.active_link_training = !!(pd_ctrl->control_flags &
505 				       USB_PD_CTRL_ACTIVE_LINK_UNIDIR);
506 
507 	port->state.alt = NULL;
508 	port->state.data = &data;
509 	port->state.mode = TYPEC_MODE_USB4;
510 
511 	return typec_mux_set(port->mux, &port->state);
512 }
513 
514 static int cros_typec_configure_mux(struct cros_typec_data *typec, int port_num,
515 				uint8_t mux_flags,
516 				struct ec_response_usb_pd_control_v2 *pd_ctrl)
517 {
518 	struct cros_typec_port *port = typec->ports[port_num];
519 	struct ec_params_usb_pd_mux_ack mux_ack;
520 	enum typec_orientation orientation;
521 	int ret;
522 
523 	if (mux_flags == USB_PD_MUX_NONE) {
524 		ret = cros_typec_usb_disconnect_state(port);
525 		goto mux_ack;
526 	}
527 
528 	if (mux_flags & USB_PD_MUX_POLARITY_INVERTED)
529 		orientation = TYPEC_ORIENTATION_REVERSE;
530 	else
531 		orientation = TYPEC_ORIENTATION_NORMAL;
532 
533 	ret = typec_switch_set(port->ori_sw, orientation);
534 	if (ret)
535 		return ret;
536 
537 	ret = usb_role_switch_set_role(typec->ports[port_num]->role_sw,
538 					pd_ctrl->role & PD_CTRL_RESP_ROLE_DATA
539 					? USB_ROLE_HOST : USB_ROLE_DEVICE);
540 	if (ret)
541 		return ret;
542 
543 	if (mux_flags & USB_PD_MUX_USB4_ENABLED) {
544 		ret = cros_typec_enable_usb4(typec, port_num, pd_ctrl);
545 	} else if (mux_flags & USB_PD_MUX_TBT_COMPAT_ENABLED) {
546 		ret = cros_typec_enable_tbt(typec, port_num, pd_ctrl);
547 	} else if (mux_flags & USB_PD_MUX_DP_ENABLED) {
548 		ret = cros_typec_enable_dp(typec, port_num, pd_ctrl);
549 	} else if (mux_flags & USB_PD_MUX_SAFE_MODE) {
550 		ret = cros_typec_usb_safe_state(port);
551 	} else if (mux_flags & USB_PD_MUX_USB_ENABLED) {
552 		port->state.alt = NULL;
553 		port->state.mode = TYPEC_STATE_USB;
554 		ret = typec_mux_set(port->mux, &port->state);
555 	} else {
556 		dev_dbg(typec->dev,
557 			"Unrecognized mode requested, mux flags: %x\n",
558 			mux_flags);
559 	}
560 
561 mux_ack:
562 	if (!typec->needs_mux_ack)
563 		return ret;
564 
565 	/* Sending Acknowledgment to EC */
566 	mux_ack.port = port_num;
567 
568 	if (cros_ec_command(typec->ec, 0, EC_CMD_USB_PD_MUX_ACK, &mux_ack,
569 			    sizeof(mux_ack), NULL, 0) < 0)
570 		dev_warn(typec->dev,
571 			 "Failed to send Mux ACK to EC for port: %d\n",
572 			 port_num);
573 
574 	return ret;
575 }
576 
577 static void cros_typec_set_port_params_v0(struct cros_typec_data *typec,
578 		int port_num, struct ec_response_usb_pd_control *resp)
579 {
580 	struct typec_port *port = typec->ports[port_num]->port;
581 	enum typec_orientation polarity;
582 
583 	if (!resp->enabled)
584 		polarity = TYPEC_ORIENTATION_NONE;
585 	else if (!resp->polarity)
586 		polarity = TYPEC_ORIENTATION_NORMAL;
587 	else
588 		polarity = TYPEC_ORIENTATION_REVERSE;
589 
590 	typec_set_pwr_role(port, resp->role ? TYPEC_SOURCE : TYPEC_SINK);
591 	typec_set_orientation(port, polarity);
592 }
593 
594 static void cros_typec_set_port_params_v1(struct cros_typec_data *typec,
595 		int port_num, struct ec_response_usb_pd_control_v1 *resp)
596 {
597 	struct typec_port *port = typec->ports[port_num]->port;
598 	enum typec_orientation polarity;
599 	bool pd_en;
600 	int ret;
601 
602 	if (!(resp->enabled & PD_CTRL_RESP_ENABLED_CONNECTED))
603 		polarity = TYPEC_ORIENTATION_NONE;
604 	else if (!resp->polarity)
605 		polarity = TYPEC_ORIENTATION_NORMAL;
606 	else
607 		polarity = TYPEC_ORIENTATION_REVERSE;
608 	typec_set_orientation(port, polarity);
609 	typec_set_data_role(port, resp->role & PD_CTRL_RESP_ROLE_DATA ?
610 			TYPEC_HOST : TYPEC_DEVICE);
611 	typec_set_pwr_role(port, resp->role & PD_CTRL_RESP_ROLE_POWER ?
612 			TYPEC_SOURCE : TYPEC_SINK);
613 	typec_set_vconn_role(port, resp->role & PD_CTRL_RESP_ROLE_VCONN ?
614 			TYPEC_SOURCE : TYPEC_SINK);
615 
616 	/* Register/remove partners when a connect/disconnect occurs. */
617 	if (resp->enabled & PD_CTRL_RESP_ENABLED_CONNECTED) {
618 		if (typec->ports[port_num]->partner)
619 			return;
620 
621 		pd_en = resp->enabled & PD_CTRL_RESP_ENABLED_PD_CAPABLE;
622 		ret = cros_typec_add_partner(typec, port_num, pd_en);
623 		if (ret)
624 			dev_warn(typec->dev,
625 				 "Failed to register partner on port: %d\n",
626 				 port_num);
627 	} else {
628 		cros_typec_remove_partner(typec, port_num);
629 		cros_typec_remove_cable(typec, port_num);
630 	}
631 }
632 
633 static int cros_typec_get_mux_info(struct cros_typec_data *typec, int port_num,
634 				   struct ec_response_usb_pd_mux_info *resp)
635 {
636 	struct ec_params_usb_pd_mux_info req = {
637 		.port = port_num,
638 	};
639 
640 	return cros_ec_command(typec->ec, 0, EC_CMD_USB_PD_MUX_INFO, &req,
641 			       sizeof(req), resp, sizeof(*resp));
642 }
643 
644 /*
645  * Helper function to register partner/plug altmodes.
646  */
647 static int cros_typec_register_altmodes(struct cros_typec_data *typec, int port_num,
648 					bool is_partner)
649 {
650 	struct cros_typec_port *port = typec->ports[port_num];
651 	struct ec_response_typec_discovery *sop_disc = port->disc_data;
652 	struct cros_typec_altmode_node *node;
653 	struct typec_altmode_desc desc;
654 	struct typec_altmode *amode;
655 	int num_altmodes = 0;
656 	int ret = 0;
657 	int i, j;
658 
659 	for (i = 0; i < sop_disc->svid_count; i++) {
660 		for (j = 0; j < sop_disc->svids[i].mode_count; j++) {
661 			memset(&desc, 0, sizeof(desc));
662 			desc.svid = sop_disc->svids[i].svid;
663 			desc.mode = j;
664 			desc.vdo = sop_disc->svids[i].mode_vdo[j];
665 
666 			if (is_partner)
667 				amode = typec_partner_register_altmode(port->partner, &desc);
668 			else
669 				amode = typec_plug_register_altmode(port->plug, &desc);
670 
671 			if (IS_ERR(amode)) {
672 				ret = PTR_ERR(amode);
673 				goto err_cleanup;
674 			}
675 
676 			/* If no memory is available we should unregister and exit. */
677 			node = devm_kzalloc(typec->dev, sizeof(*node), GFP_KERNEL);
678 			if (!node) {
679 				ret = -ENOMEM;
680 				typec_unregister_altmode(amode);
681 				goto err_cleanup;
682 			}
683 
684 			node->amode = amode;
685 
686 			if (is_partner)
687 				list_add_tail(&node->list, &port->partner_mode_list);
688 			else
689 				list_add_tail(&node->list, &port->plug_mode_list);
690 			num_altmodes++;
691 		}
692 	}
693 
694 	if (is_partner)
695 		ret = typec_partner_set_num_altmodes(port->partner, num_altmodes);
696 	else
697 		ret = typec_plug_set_num_altmodes(port->plug, num_altmodes);
698 
699 	if (ret < 0) {
700 		dev_err(typec->dev, "Unable to set %s num_altmodes for port: %d\n",
701 			is_partner ? "partner" : "plug", port_num);
702 		goto err_cleanup;
703 	}
704 
705 	return 0;
706 
707 err_cleanup:
708 	cros_typec_unregister_altmodes(typec, port_num, is_partner);
709 	return ret;
710 }
711 
712 /*
713  * Parse the PD identity data from the EC PD discovery responses and copy that to the supplied
714  * PD identity struct.
715  */
716 static void cros_typec_parse_pd_identity(struct usb_pd_identity *id,
717 					 struct ec_response_typec_discovery *disc)
718 {
719 	int i;
720 
721 	/* First, update the PD identity VDOs for the partner. */
722 	if (disc->identity_count > 0)
723 		id->id_header = disc->discovery_vdo[0];
724 	if (disc->identity_count > 1)
725 		id->cert_stat = disc->discovery_vdo[1];
726 	if (disc->identity_count > 2)
727 		id->product = disc->discovery_vdo[2];
728 
729 	/* Copy the remaining identity VDOs till a maximum of 6. */
730 	for (i = 3; i < disc->identity_count && i < VDO_MAX_OBJECTS; i++)
731 		id->vdo[i - 3] = disc->discovery_vdo[i];
732 }
733 
734 static int cros_typec_handle_sop_prime_disc(struct cros_typec_data *typec, int port_num, u16 pd_revision)
735 {
736 	struct cros_typec_port *port = typec->ports[port_num];
737 	struct ec_response_typec_discovery *disc = port->disc_data;
738 	struct typec_cable_desc c_desc = {};
739 	struct typec_plug_desc p_desc;
740 	struct ec_params_typec_discovery req = {
741 		.port = port_num,
742 		.partner_type = TYPEC_PARTNER_SOP_PRIME,
743 	};
744 	u32 cable_plug_type;
745 	int ret = 0;
746 
747 	memset(disc, 0, EC_PROTO2_MAX_RESPONSE_SIZE);
748 	ret = cros_ec_command(typec->ec, 0, EC_CMD_TYPEC_DISCOVERY, &req, sizeof(req),
749 			      disc, EC_PROTO2_MAX_RESPONSE_SIZE);
750 	if (ret < 0) {
751 		dev_err(typec->dev, "Failed to get SOP' discovery data for port: %d\n", port_num);
752 		goto sop_prime_disc_exit;
753 	}
754 
755 	/* Parse the PD identity data, even if only 0s were returned. */
756 	cros_typec_parse_pd_identity(&port->c_identity, disc);
757 
758 	if (disc->identity_count != 0) {
759 		cable_plug_type = VDO_TYPEC_CABLE_TYPE(port->c_identity.vdo[0]);
760 		switch (cable_plug_type) {
761 		case CABLE_ATYPE:
762 			c_desc.type = USB_PLUG_TYPE_A;
763 			break;
764 		case CABLE_BTYPE:
765 			c_desc.type = USB_PLUG_TYPE_B;
766 			break;
767 		case CABLE_CTYPE:
768 			c_desc.type = USB_PLUG_TYPE_C;
769 			break;
770 		case CABLE_CAPTIVE:
771 			c_desc.type = USB_PLUG_CAPTIVE;
772 			break;
773 		default:
774 			c_desc.type = USB_PLUG_NONE;
775 		}
776 		c_desc.active = PD_IDH_PTYPE(port->c_identity.id_header) == IDH_PTYPE_ACABLE;
777 	}
778 
779 	c_desc.identity = &port->c_identity;
780 	c_desc.pd_revision = pd_revision;
781 
782 	port->cable = typec_register_cable(port->port, &c_desc);
783 	if (IS_ERR(port->cable)) {
784 		ret = PTR_ERR(port->cable);
785 		port->cable = NULL;
786 		goto sop_prime_disc_exit;
787 	}
788 
789 	p_desc.index = TYPEC_PLUG_SOP_P;
790 	port->plug = typec_register_plug(port->cable, &p_desc);
791 	if (IS_ERR(port->plug)) {
792 		ret = PTR_ERR(port->plug);
793 		port->plug = NULL;
794 		goto sop_prime_disc_exit;
795 	}
796 
797 	ret = cros_typec_register_altmodes(typec, port_num, false);
798 	if (ret < 0) {
799 		dev_err(typec->dev, "Failed to register plug altmodes, port: %d\n", port_num);
800 		goto sop_prime_disc_exit;
801 	}
802 
803 	return 0;
804 
805 sop_prime_disc_exit:
806 	cros_typec_remove_cable(typec, port_num);
807 	return ret;
808 }
809 
810 static int cros_typec_handle_sop_disc(struct cros_typec_data *typec, int port_num, u16 pd_revision)
811 {
812 	struct cros_typec_port *port = typec->ports[port_num];
813 	struct ec_response_typec_discovery *sop_disc = port->disc_data;
814 	struct ec_params_typec_discovery req = {
815 		.port = port_num,
816 		.partner_type = TYPEC_PARTNER_SOP,
817 	};
818 	int ret = 0;
819 
820 	if (!port->partner) {
821 		dev_err(typec->dev,
822 			"SOP Discovery received without partner registered, port: %d\n",
823 			port_num);
824 		ret = -EINVAL;
825 		goto disc_exit;
826 	}
827 
828 	typec_partner_set_pd_revision(port->partner, pd_revision);
829 
830 	memset(sop_disc, 0, EC_PROTO2_MAX_RESPONSE_SIZE);
831 	ret = cros_ec_command(typec->ec, 0, EC_CMD_TYPEC_DISCOVERY, &req, sizeof(req),
832 			      sop_disc, EC_PROTO2_MAX_RESPONSE_SIZE);
833 	if (ret < 0) {
834 		dev_err(typec->dev, "Failed to get SOP discovery data for port: %d\n", port_num);
835 		goto disc_exit;
836 	}
837 
838 	cros_typec_parse_pd_identity(&port->p_identity, sop_disc);
839 
840 	ret = typec_partner_set_identity(port->partner);
841 	if (ret < 0) {
842 		dev_err(typec->dev, "Failed to update partner PD identity, port: %d\n", port_num);
843 		goto disc_exit;
844 	}
845 
846 	ret = cros_typec_register_altmodes(typec, port_num, true);
847 	if (ret < 0) {
848 		dev_err(typec->dev, "Failed to register partner altmodes, port: %d\n", port_num);
849 		goto disc_exit;
850 	}
851 
852 disc_exit:
853 	return ret;
854 }
855 
856 static int cros_typec_send_clear_event(struct cros_typec_data *typec, int port_num, u32 events_mask)
857 {
858 	struct ec_params_typec_control req = {
859 		.port = port_num,
860 		.command = TYPEC_CONTROL_COMMAND_CLEAR_EVENTS,
861 		.clear_events_mask = events_mask,
862 	};
863 
864 	return cros_ec_command(typec->ec, 0, EC_CMD_TYPEC_CONTROL, &req,
865 			       sizeof(req), NULL, 0);
866 }
867 
868 static void cros_typec_handle_status(struct cros_typec_data *typec, int port_num)
869 {
870 	struct ec_response_typec_status resp;
871 	struct ec_params_typec_status req = {
872 		.port = port_num,
873 	};
874 	int ret;
875 
876 	ret = cros_ec_command(typec->ec, 0, EC_CMD_TYPEC_STATUS, &req, sizeof(req),
877 			      &resp, sizeof(resp));
878 	if (ret < 0) {
879 		dev_warn(typec->dev, "EC_CMD_TYPEC_STATUS failed for port: %d\n", port_num);
880 		return;
881 	}
882 
883 	/* If we got a hard reset, unregister everything and return. */
884 	if (resp.events & PD_STATUS_EVENT_HARD_RESET) {
885 		cros_typec_remove_partner(typec, port_num);
886 		cros_typec_remove_cable(typec, port_num);
887 
888 		ret = cros_typec_send_clear_event(typec, port_num,
889 						  PD_STATUS_EVENT_HARD_RESET);
890 		if (ret < 0)
891 			dev_warn(typec->dev,
892 				 "Failed hard reset event clear, port: %d\n", port_num);
893 		return;
894 	}
895 
896 	/* Handle any events appropriately. */
897 	if (resp.events & PD_STATUS_EVENT_SOP_DISC_DONE && !typec->ports[port_num]->sop_disc_done) {
898 		u16 sop_revision;
899 
900 		/* Convert BCD to the format preferred by the TypeC framework */
901 		sop_revision = (le16_to_cpu(resp.sop_revision) & 0xff00) >> 4;
902 		ret = cros_typec_handle_sop_disc(typec, port_num, sop_revision);
903 		if (ret < 0)
904 			dev_err(typec->dev, "Couldn't parse SOP Disc data, port: %d\n", port_num);
905 		else {
906 			typec->ports[port_num]->sop_disc_done = true;
907 			ret = cros_typec_send_clear_event(typec, port_num,
908 							  PD_STATUS_EVENT_SOP_DISC_DONE);
909 			if (ret < 0)
910 				dev_warn(typec->dev,
911 					 "Failed SOP Disc event clear, port: %d\n", port_num);
912 		}
913 		if (resp.sop_connected)
914 			typec_set_pwr_opmode(typec->ports[port_num]->port, TYPEC_PWR_MODE_PD);
915 	}
916 
917 	if (resp.events & PD_STATUS_EVENT_SOP_PRIME_DISC_DONE &&
918 	    !typec->ports[port_num]->sop_prime_disc_done) {
919 		u16 sop_prime_revision;
920 
921 		/* Convert BCD to the format preferred by the TypeC framework */
922 		sop_prime_revision = (le16_to_cpu(resp.sop_prime_revision) & 0xff00) >> 4;
923 		ret = cros_typec_handle_sop_prime_disc(typec, port_num, sop_prime_revision);
924 		if (ret < 0)
925 			dev_err(typec->dev, "Couldn't parse SOP' Disc data, port: %d\n", port_num);
926 		else {
927 			typec->ports[port_num]->sop_prime_disc_done = true;
928 			ret = cros_typec_send_clear_event(typec, port_num,
929 							  PD_STATUS_EVENT_SOP_PRIME_DISC_DONE);
930 			if (ret < 0)
931 				dev_warn(typec->dev,
932 					 "Failed SOP Disc event clear, port: %d\n", port_num);
933 		}
934 	}
935 }
936 
937 static int cros_typec_port_update(struct cros_typec_data *typec, int port_num)
938 {
939 	struct ec_params_usb_pd_control req;
940 	struct ec_response_usb_pd_control_v2 resp;
941 	struct ec_response_usb_pd_mux_info mux_resp;
942 	int ret;
943 
944 	if (port_num < 0 || port_num >= typec->num_ports) {
945 		dev_err(typec->dev, "cannot get status for invalid port %d\n",
946 			port_num);
947 		return -EINVAL;
948 	}
949 
950 	req.port = port_num;
951 	req.role = USB_PD_CTRL_ROLE_NO_CHANGE;
952 	req.mux = USB_PD_CTRL_MUX_NO_CHANGE;
953 	req.swap = USB_PD_CTRL_SWAP_NONE;
954 
955 	ret = cros_ec_command(typec->ec, typec->pd_ctrl_ver,
956 			      EC_CMD_USB_PD_CONTROL, &req, sizeof(req),
957 			      &resp, sizeof(resp));
958 	if (ret < 0)
959 		return ret;
960 
961 	dev_dbg(typec->dev, "Enabled %d: 0x%hhx\n", port_num, resp.enabled);
962 	dev_dbg(typec->dev, "Role %d: 0x%hhx\n", port_num, resp.role);
963 	dev_dbg(typec->dev, "Polarity %d: 0x%hhx\n", port_num, resp.polarity);
964 	dev_dbg(typec->dev, "State %d: %s\n", port_num, resp.state);
965 
966 	if (typec->pd_ctrl_ver != 0)
967 		cros_typec_set_port_params_v1(typec, port_num,
968 			(struct ec_response_usb_pd_control_v1 *)&resp);
969 	else
970 		cros_typec_set_port_params_v0(typec, port_num,
971 			(struct ec_response_usb_pd_control *) &resp);
972 
973 	if (typec->typec_cmd_supported)
974 		cros_typec_handle_status(typec, port_num);
975 
976 	/* Update the switches if they exist, according to requested state */
977 	ret = cros_typec_get_mux_info(typec, port_num, &mux_resp);
978 	if (ret < 0) {
979 		dev_warn(typec->dev,
980 			 "Failed to get mux info for port: %d, err = %d\n",
981 			 port_num, ret);
982 		return 0;
983 	}
984 
985 	/* No change needs to be made, let's exit early. */
986 	if (typec->ports[port_num]->mux_flags == mux_resp.flags &&
987 	    typec->ports[port_num]->role == resp.role)
988 		return 0;
989 
990 	typec->ports[port_num]->mux_flags = mux_resp.flags;
991 	typec->ports[port_num]->role = resp.role;
992 	ret = cros_typec_configure_mux(typec, port_num, mux_resp.flags, &resp);
993 	if (ret)
994 		dev_warn(typec->dev, "Configure muxes failed, err = %d\n", ret);
995 
996 	return ret;
997 }
998 
999 static int cros_typec_get_cmd_version(struct cros_typec_data *typec)
1000 {
1001 	struct ec_params_get_cmd_versions_v1 req_v1;
1002 	struct ec_response_get_cmd_versions resp;
1003 	int ret;
1004 
1005 	/* We're interested in the PD control command version. */
1006 	req_v1.cmd = EC_CMD_USB_PD_CONTROL;
1007 	ret = cros_ec_command(typec->ec, 1, EC_CMD_GET_CMD_VERSIONS,
1008 			      &req_v1, sizeof(req_v1), &resp,
1009 				    sizeof(resp));
1010 	if (ret < 0)
1011 		return ret;
1012 
1013 	if (resp.version_mask & EC_VER_MASK(2))
1014 		typec->pd_ctrl_ver = 2;
1015 	else if (resp.version_mask & EC_VER_MASK(1))
1016 		typec->pd_ctrl_ver = 1;
1017 	else
1018 		typec->pd_ctrl_ver = 0;
1019 
1020 	dev_dbg(typec->dev, "PD Control has version mask 0x%02x\n",
1021 		typec->pd_ctrl_ver & 0xff);
1022 
1023 	return 0;
1024 }
1025 
1026 static void cros_typec_port_work(struct work_struct *work)
1027 {
1028 	struct cros_typec_data *typec = container_of(work, struct cros_typec_data, port_work);
1029 	int ret, i;
1030 
1031 	for (i = 0; i < typec->num_ports; i++) {
1032 		ret = cros_typec_port_update(typec, i);
1033 		if (ret < 0)
1034 			dev_warn(typec->dev, "Update failed for port: %d\n", i);
1035 	}
1036 }
1037 
1038 static int cros_ec_typec_event(struct notifier_block *nb,
1039 			       unsigned long host_event, void *_notify)
1040 {
1041 	struct cros_typec_data *typec = container_of(nb, struct cros_typec_data, nb);
1042 
1043 	flush_work(&typec->port_work);
1044 	schedule_work(&typec->port_work);
1045 
1046 	return NOTIFY_OK;
1047 }
1048 
1049 #ifdef CONFIG_ACPI
1050 static const struct acpi_device_id cros_typec_acpi_id[] = {
1051 	{ "GOOG0014", 0 },
1052 	{}
1053 };
1054 MODULE_DEVICE_TABLE(acpi, cros_typec_acpi_id);
1055 #endif
1056 
1057 #ifdef CONFIG_OF
1058 static const struct of_device_id cros_typec_of_match[] = {
1059 	{ .compatible = "google,cros-ec-typec", },
1060 	{}
1061 };
1062 MODULE_DEVICE_TABLE(of, cros_typec_of_match);
1063 #endif
1064 
1065 static int cros_typec_probe(struct platform_device *pdev)
1066 {
1067 	struct cros_ec_dev *ec_dev = NULL;
1068 	struct device *dev = &pdev->dev;
1069 	struct cros_typec_data *typec;
1070 	struct ec_response_usb_pd_ports resp;
1071 	int ret, i;
1072 
1073 	typec = devm_kzalloc(dev, sizeof(*typec), GFP_KERNEL);
1074 	if (!typec)
1075 		return -ENOMEM;
1076 
1077 	typec->dev = dev;
1078 	typec->ec = dev_get_drvdata(pdev->dev.parent);
1079 	platform_set_drvdata(pdev, typec);
1080 
1081 	ret = cros_typec_get_cmd_version(typec);
1082 	if (ret < 0) {
1083 		dev_err(dev, "failed to get PD command version info\n");
1084 		return ret;
1085 	}
1086 
1087 	ec_dev = dev_get_drvdata(&typec->ec->ec->dev);
1088 	typec->typec_cmd_supported = cros_ec_check_features(ec_dev, EC_FEATURE_TYPEC_CMD);
1089 	typec->needs_mux_ack = cros_ec_check_features(ec_dev, EC_FEATURE_TYPEC_MUX_REQUIRE_AP_ACK);
1090 
1091 	ret = cros_ec_command(typec->ec, 0, EC_CMD_USB_PD_PORTS, NULL, 0,
1092 			      &resp, sizeof(resp));
1093 	if (ret < 0)
1094 		return ret;
1095 
1096 	typec->num_ports = resp.num_ports;
1097 	if (typec->num_ports > EC_USB_PD_MAX_PORTS) {
1098 		dev_warn(typec->dev,
1099 			 "Too many ports reported: %d, limiting to max: %d\n",
1100 			 typec->num_ports, EC_USB_PD_MAX_PORTS);
1101 		typec->num_ports = EC_USB_PD_MAX_PORTS;
1102 	}
1103 
1104 	ret = cros_typec_init_ports(typec);
1105 	if (ret < 0)
1106 		return ret;
1107 
1108 	INIT_WORK(&typec->port_work, cros_typec_port_work);
1109 
1110 	/*
1111 	 * Safe to call port update here, since we haven't registered the
1112 	 * PD notifier yet.
1113 	 */
1114 	for (i = 0; i < typec->num_ports; i++) {
1115 		ret = cros_typec_port_update(typec, i);
1116 		if (ret < 0)
1117 			goto unregister_ports;
1118 	}
1119 
1120 	typec->nb.notifier_call = cros_ec_typec_event;
1121 	ret = cros_usbpd_register_notify(&typec->nb);
1122 	if (ret < 0)
1123 		goto unregister_ports;
1124 
1125 	return 0;
1126 
1127 unregister_ports:
1128 	cros_unregister_ports(typec);
1129 	return ret;
1130 }
1131 
1132 static int __maybe_unused cros_typec_suspend(struct device *dev)
1133 {
1134 	struct cros_typec_data *typec = dev_get_drvdata(dev);
1135 
1136 	cancel_work_sync(&typec->port_work);
1137 
1138 	return 0;
1139 }
1140 
1141 static int __maybe_unused cros_typec_resume(struct device *dev)
1142 {
1143 	struct cros_typec_data *typec = dev_get_drvdata(dev);
1144 
1145 	/* Refresh port state. */
1146 	schedule_work(&typec->port_work);
1147 
1148 	return 0;
1149 }
1150 
1151 static const struct dev_pm_ops cros_typec_pm_ops = {
1152 	SET_SYSTEM_SLEEP_PM_OPS(cros_typec_suspend, cros_typec_resume)
1153 };
1154 
1155 static struct platform_driver cros_typec_driver = {
1156 	.driver	= {
1157 		.name = DRV_NAME,
1158 		.acpi_match_table = ACPI_PTR(cros_typec_acpi_id),
1159 		.of_match_table = of_match_ptr(cros_typec_of_match),
1160 		.pm = &cros_typec_pm_ops,
1161 	},
1162 	.probe = cros_typec_probe,
1163 };
1164 
1165 module_platform_driver(cros_typec_driver);
1166 
1167 MODULE_AUTHOR("Prashant Malani <pmalani@chromium.org>");
1168 MODULE_DESCRIPTION("Chrome OS EC Type C control");
1169 MODULE_LICENSE("GPL");
1170