xref: /linux/drivers/usb/typec/ucsi/ucsi.c (revision 55311a92bc9564b058a036074f85200a5954ccd2)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * USB Type-C Connector System Software Interface driver
4  *
5  * Copyright (C) 2017, Intel Corporation
6  * Author: Heikki Krogerus <heikki.krogerus@linux.intel.com>
7  */
8 
9 #include <linux/completion.h>
10 #include <linux/property.h>
11 #include <linux/device.h>
12 #include <linux/module.h>
13 #include <linux/delay.h>
14 #include <linux/slab.h>
15 #include <linux/usb/typec_dp.h>
16 #include <linux/usb/typec_tbt.h>
17 
18 #include "ucsi.h"
19 #include "trace.h"
20 
21 /*
22  * UCSI_TIMEOUT_MS - PPM communication timeout
23  *
24  * Ideally we could use MIN_TIME_TO_RESPOND_WITH_BUSY (which is defined in UCSI
25  * specification) here as reference, but unfortunately we can't. It is very
26  * difficult to estimate the time it takes for the system to process the command
27  * before it is actually passed to the PPM.
28  */
29 #define UCSI_TIMEOUT_MS		10000
30 
31 /*
32  * UCSI_SWAP_TIMEOUT_MS - Timeout for role swap requests
33  *
34  * 5 seconds is close to the time it takes for CapsCounter to reach 0, so even
35  * if the PPM does not generate Connector Change events before that with
36  * partners that do not support USB Power Delivery, this should still work.
37  */
38 #define UCSI_SWAP_TIMEOUT_MS	5000
39 
40 void ucsi_notify_common(struct ucsi *ucsi, u32 cci)
41 {
42 	/* Ignore bogus data in CCI if busy indicator is set. */
43 	if (cci & UCSI_CCI_BUSY)
44 		return;
45 
46 	if (UCSI_CCI_CONNECTOR(cci)) {
47 		if (!ucsi->cap.num_connectors ||
48 		    UCSI_CCI_CONNECTOR(cci) <= ucsi->cap.num_connectors)
49 			ucsi_connector_change(ucsi, UCSI_CCI_CONNECTOR(cci));
50 		else
51 			dev_err(ucsi->dev, "bogus connector number in CCI: %lu\n",
52 				UCSI_CCI_CONNECTOR(cci));
53 	}
54 
55 	if (cci & UCSI_CCI_ACK_COMPLETE &&
56 	    test_and_clear_bit(ACK_PENDING, &ucsi->flags))
57 		complete(&ucsi->complete);
58 
59 	if (cci & UCSI_CCI_COMMAND_COMPLETE &&
60 	    test_and_clear_bit(COMMAND_PENDING, &ucsi->flags))
61 		complete(&ucsi->complete);
62 }
63 EXPORT_SYMBOL_GPL(ucsi_notify_common);
64 
65 int ucsi_sync_control_common(struct ucsi *ucsi, u64 command, u32 *cci,
66 			     void *data, size_t size, void *msg_out,
67 			     size_t msg_out_size)
68 {
69 	bool ack = UCSI_COMMAND(command) == UCSI_ACK_CC_CI;
70 	int ret;
71 
72 	if (ack)
73 		set_bit(ACK_PENDING, &ucsi->flags);
74 	else
75 		set_bit(COMMAND_PENDING, &ucsi->flags);
76 
77 	reinit_completion(&ucsi->complete);
78 
79 	if (msg_out && msg_out_size) {
80 		if (!ucsi->ops->write_message_out) {
81 			ret = -EOPNOTSUPP;
82 			goto out_clear_bit;
83 		}
84 
85 		ret = ucsi->ops->write_message_out(ucsi, msg_out, msg_out_size);
86 		if (ret)
87 			goto out_clear_bit;
88 	}
89 
90 	ret = ucsi->ops->async_control(ucsi, command);
91 	if (ret)
92 		goto out_clear_bit;
93 
94 	if (!wait_for_completion_timeout(&ucsi->complete, 5 * HZ))
95 		ret = -ETIMEDOUT;
96 
97 out_clear_bit:
98 	if (ack)
99 		clear_bit(ACK_PENDING, &ucsi->flags);
100 	else
101 		clear_bit(COMMAND_PENDING, &ucsi->flags);
102 
103 	if (!ret && cci)
104 		ret = ucsi->ops->read_cci(ucsi, cci);
105 
106 	if (!ret && data &&
107 	    (*cci & UCSI_CCI_COMMAND_COMPLETE))
108 		ret = ucsi->ops->read_message_in(ucsi, data, size);
109 
110 	return ret;
111 }
112 EXPORT_SYMBOL_GPL(ucsi_sync_control_common);
113 
114 static int ucsi_acknowledge(struct ucsi *ucsi, bool conn_ack)
115 {
116 	u64 ctrl;
117 
118 	ctrl = UCSI_ACK_CC_CI;
119 	ctrl |= UCSI_ACK_COMMAND_COMPLETE;
120 	if (conn_ack) {
121 		clear_bit(EVENT_PENDING, &ucsi->flags);
122 		ctrl |= UCSI_ACK_CONNECTOR_CHANGE;
123 	}
124 
125 	return ucsi->ops->sync_control(ucsi, ctrl, NULL, NULL, 0, NULL, 0);
126 }
127 
128 static int ucsi_run_command(struct ucsi *ucsi, u64 command, u32 *cci,
129 			    void *data, size_t size, void *msg_out,
130 			    size_t msg_out_size, bool conn_ack)
131 {
132 	int ret, err;
133 
134 	*cci = 0;
135 
136 	if (size > UCSI_MAX_DATA_LENGTH(ucsi))
137 		return -EINVAL;
138 
139 	ret = ucsi->ops->sync_control(ucsi, command, cci, data, size,
140 				      msg_out, msg_out_size);
141 
142 	if (*cci & UCSI_CCI_BUSY)
143 		return ucsi_run_command(ucsi, UCSI_CANCEL, cci,
144 					NULL, 0, NULL, 0, false) ?: -EBUSY;
145 	if (ret)
146 		return ret;
147 
148 	if (!(*cci & UCSI_CCI_COMMAND_COMPLETE))
149 		return -EIO;
150 
151 	if (*cci & UCSI_CCI_NOT_SUPPORTED)
152 		err = -EOPNOTSUPP;
153 	else if (*cci & UCSI_CCI_ERROR)
154 		err = -EIO;
155 	else
156 		err = 0;
157 
158 	/*
159 	 * Don't ACK connection change if there was an error.
160 	 */
161 	ret = ucsi_acknowledge(ucsi, err ? false : conn_ack);
162 	if (ret)
163 		return ret;
164 
165 	return err ?: UCSI_CCI_LENGTH(*cci);
166 }
167 
168 static int ucsi_read_error(struct ucsi *ucsi, u8 connector_num)
169 {
170 	u64 command;
171 	u16 error;
172 	u32 cci;
173 	int ret;
174 
175 	command = UCSI_GET_ERROR_STATUS | UCSI_CONNECTOR_NUMBER(connector_num);
176 	ret = ucsi_run_command(ucsi, command, &cci, &error,
177 			       sizeof(error), NULL, 0, false);
178 	if (ret < 0)
179 		return ret;
180 
181 	switch (error) {
182 	case UCSI_ERROR_INCOMPATIBLE_PARTNER:
183 		return -EOPNOTSUPP;
184 	case UCSI_ERROR_CC_COMMUNICATION_ERR:
185 		return -ECOMM;
186 	case UCSI_ERROR_CONTRACT_NEGOTIATION_FAIL:
187 		return -EPROTO;
188 	case UCSI_ERROR_DEAD_BATTERY:
189 		dev_warn(ucsi->dev, "Dead battery condition!\n");
190 		return -EPERM;
191 	case UCSI_ERROR_INVALID_CON_NUM:
192 	case UCSI_ERROR_UNREGONIZED_CMD:
193 	case UCSI_ERROR_INVALID_CMD_ARGUMENT:
194 		dev_err(ucsi->dev, "possible UCSI driver bug %u\n", error);
195 		return -EINVAL;
196 	case UCSI_ERROR_OVERCURRENT:
197 		dev_warn(ucsi->dev, "Overcurrent condition\n");
198 		break;
199 	case UCSI_ERROR_PARTNER_REJECTED_SWAP:
200 		dev_warn(ucsi->dev, "Partner rejected swap\n");
201 		break;
202 	case UCSI_ERROR_HARD_RESET:
203 		dev_warn(ucsi->dev, "Hard reset occurred\n");
204 		break;
205 	case UCSI_ERROR_PPM_POLICY_CONFLICT:
206 		dev_warn(ucsi->dev, "PPM Policy conflict\n");
207 		break;
208 	case UCSI_ERROR_SWAP_REJECTED:
209 		dev_warn(ucsi->dev, "Swap rejected\n");
210 		break;
211 	case UCSI_ERROR_REVERSE_CURRENT_PROTECTION:
212 		dev_warn(ucsi->dev, "Reverse Current Protection detected\n");
213 		break;
214 	case UCSI_ERROR_SET_SINK_PATH_REJECTED:
215 		dev_warn(ucsi->dev, "Set Sink Path rejected\n");
216 		break;
217 	case UCSI_ERROR_UNDEFINED:
218 	default:
219 		dev_err(ucsi->dev, "unknown error %u\n", error);
220 		break;
221 	}
222 
223 	return -EIO;
224 }
225 
226 static int ucsi_send_command_common(struct ucsi *ucsi, u64 cmd,
227 				    void *data, size_t size, void *msg_out,
228 				    size_t msg_out_size, bool conn_ack)
229 {
230 	u8 connector_num;
231 	u32 cci;
232 	int ret;
233 
234 	if (ucsi->version > UCSI_VERSION_1_2) {
235 		switch (UCSI_COMMAND(cmd)) {
236 		case UCSI_GET_ALTERNATE_MODES:
237 			connector_num = UCSI_GET_ALTMODE_GET_CONNECTOR_NUMBER(cmd);
238 			break;
239 		case UCSI_PPM_RESET:
240 		case UCSI_CANCEL:
241 		case UCSI_ACK_CC_CI:
242 		case UCSI_SET_NOTIFICATION_ENABLE:
243 		case UCSI_GET_CAPABILITY:
244 			connector_num = 0;
245 			break;
246 		default:
247 			connector_num = UCSI_DEFAULT_GET_CONNECTOR_NUMBER(cmd);
248 			break;
249 		}
250 	} else {
251 		connector_num = 0;
252 	}
253 
254 	mutex_lock(&ucsi->ppm_lock);
255 
256 	ret = ucsi_run_command(ucsi, cmd, &cci, data, size,
257 			       msg_out, msg_out_size, conn_ack);
258 
259 	if (cci & UCSI_CCI_ERROR)
260 		ret = ucsi_read_error(ucsi, connector_num);
261 
262 	trace_ucsi_run_command(cmd, ret);
263 
264 	mutex_unlock(&ucsi->ppm_lock);
265 	return ret;
266 }
267 
268 int ucsi_send_command(struct ucsi *ucsi, u64 command,
269 		      void *data, size_t size)
270 {
271 	return ucsi_send_command_common(ucsi, command, data,
272 					size, NULL, 0, false);
273 }
274 EXPORT_SYMBOL_GPL(ucsi_send_command);
275 
276 int ucsi_write_message_out_command(struct ucsi *ucsi, u64 command,
277 				   void *data, size_t size, void *msg_out,
278 				   size_t msg_out_size)
279 {
280 	if (msg_out_size > UCSI_MAX_MSG_OUT_DATA_LEN(ucsi))
281 		return -EINVAL;
282 
283 	return ucsi_send_command_common(ucsi, command, data,
284 					size, msg_out, msg_out_size, false);
285 }
286 EXPORT_SYMBOL_GPL(ucsi_write_message_out_command);
287 
288 /* -------------------------------------------------------------------------- */
289 
290 struct ucsi_work {
291 	struct delayed_work work;
292 	struct list_head node;
293 	unsigned long delay;
294 	unsigned int count;
295 	struct ucsi_connector *con;
296 	int (*cb)(struct ucsi_connector *);
297 };
298 
299 static void ucsi_poll_worker(struct work_struct *work)
300 {
301 	struct ucsi_work *uwork = container_of(work, struct ucsi_work, work.work);
302 	struct ucsi_connector *con = uwork->con;
303 	int ret;
304 
305 	mutex_lock(&con->lock);
306 
307 	if (!con->partner) {
308 		list_del(&uwork->node);
309 		mutex_unlock(&con->lock);
310 		kfree(uwork);
311 		return;
312 	}
313 
314 	ret = uwork->cb(con);
315 
316 	if (uwork->count-- && (ret == -EBUSY || ret == -ETIMEDOUT)) {
317 		queue_delayed_work(con->wq, &uwork->work, uwork->delay);
318 	} else {
319 		list_del(&uwork->node);
320 		kfree(uwork);
321 	}
322 
323 	mutex_unlock(&con->lock);
324 }
325 
326 static int ucsi_partner_task(struct ucsi_connector *con,
327 			     int (*cb)(struct ucsi_connector *),
328 			     int retries, unsigned long delay)
329 {
330 	struct ucsi_work *uwork;
331 
332 	if (!con->partner)
333 		return 0;
334 
335 	uwork = kzalloc_obj(*uwork);
336 	if (!uwork)
337 		return -ENOMEM;
338 
339 	INIT_DELAYED_WORK(&uwork->work, ucsi_poll_worker);
340 	uwork->count = retries;
341 	uwork->delay = delay;
342 	uwork->con = con;
343 	uwork->cb = cb;
344 
345 	list_add_tail(&uwork->node, &con->partner_tasks);
346 	queue_delayed_work(con->wq, &uwork->work, delay);
347 
348 	return 0;
349 }
350 
351 /* -------------------------------------------------------------------------- */
352 
353 void ucsi_altmode_update_active(struct ucsi_connector *con)
354 {
355 	const struct typec_altmode *altmode = NULL;
356 	u64 command;
357 	u16 svid = 0;
358 	int ret;
359 	u8 cur;
360 	int i;
361 
362 	command = UCSI_GET_CURRENT_CAM | UCSI_CONNECTOR_NUMBER(con->num);
363 	ret = ucsi_send_command(con->ucsi, command, &cur, sizeof(cur));
364 	if (ret < 0) {
365 		if (con->ucsi->version > 0x0100) {
366 			dev_err(con->ucsi->dev,
367 				"GET_CURRENT_CAM command failed\n");
368 			return;
369 		}
370 		cur = 0xff;
371 	}
372 
373 	if (cur < UCSI_MAX_ALTMODES)
374 		altmode = typec_altmode_get_partner(con->port_altmode[cur]);
375 
376 	for (i = 0; con->partner_altmode[i]; i++)
377 		typec_altmode_update_active(con->partner_altmode[i],
378 					    con->partner_altmode[i] == altmode);
379 
380 	if (altmode)
381 		svid = altmode->svid;
382 	typec_altmode_state_update(con->partner, svid, 0);
383 }
384 
385 static int ucsi_altmode_next_mode(struct typec_altmode **alt, u16 svid)
386 {
387 	u8 mode = 1;
388 	int i;
389 
390 	for (i = 0; alt[i]; i++) {
391 		if (i > MODE_DISCOVERY_MAX)
392 			return -ERANGE;
393 
394 		if (alt[i]->svid == svid)
395 			mode++;
396 	}
397 
398 	return mode;
399 }
400 
401 static int ucsi_next_altmode(struct typec_altmode **alt)
402 {
403 	int i = 0;
404 
405 	for (i = 0; i < UCSI_MAX_ALTMODES; i++)
406 		if (!alt[i])
407 			return i;
408 
409 	return -ENOENT;
410 }
411 
412 static int ucsi_get_num_altmode(struct typec_altmode **alt)
413 {
414 	int i;
415 
416 	for (i = 0; i < UCSI_MAX_ALTMODES; i++)
417 		if (!alt[i])
418 			break;
419 
420 	return i;
421 }
422 
423 static int ucsi_register_altmode(struct ucsi_connector *con,
424 				 struct typec_altmode_desc *desc,
425 				 u8 recipient)
426 {
427 	struct typec_altmode *alt;
428 	bool override;
429 	int ret;
430 	int i;
431 
432 	override = !!(con->ucsi->cap.features & UCSI_CAP_ALT_MODE_OVERRIDE);
433 
434 	switch (recipient) {
435 	case UCSI_RECIPIENT_CON:
436 		i = ucsi_next_altmode(con->port_altmode);
437 		if (i < 0) {
438 			ret = i;
439 			goto err;
440 		}
441 
442 		ret = ucsi_altmode_next_mode(con->port_altmode, desc->svid);
443 		if (ret < 0)
444 			return ret;
445 
446 		desc->mode = ret;
447 
448 		switch (desc->svid) {
449 		case USB_TYPEC_DP_SID:
450 			alt = ucsi_register_displayport(con, override, i, desc);
451 			break;
452 		case USB_TYPEC_NVIDIA_VLINK_SID:
453 			if (desc->vdo == USB_TYPEC_NVIDIA_VLINK_DBG_VDO)
454 				alt = typec_port_register_altmode(con->port,
455 								  desc);
456 			else
457 				alt = ucsi_register_displayport(con, override,
458 								i, desc);
459 			break;
460 		case USB_TYPEC_TBT_SID:
461 			alt = ucsi_register_thunderbolt(con, override, i, desc);
462 			break;
463 		default:
464 			alt = typec_port_register_altmode(con->port, desc);
465 			break;
466 		}
467 
468 		if (IS_ERR(alt)) {
469 			ret = PTR_ERR(alt);
470 			goto err;
471 		}
472 
473 		con->port_altmode[i] = alt;
474 		break;
475 	case UCSI_RECIPIENT_SOP:
476 		i = ucsi_next_altmode(con->partner_altmode);
477 		if (i < 0) {
478 			ret = i;
479 			goto err;
480 		}
481 
482 		ret = ucsi_altmode_next_mode(con->partner_altmode, desc->svid);
483 		if (ret < 0)
484 			return ret;
485 
486 		desc->mode = ret;
487 
488 		alt = typec_partner_register_altmode(con->partner, desc);
489 		if (IS_ERR(alt)) {
490 			ret = PTR_ERR(alt);
491 			goto err;
492 		}
493 
494 		con->partner_altmode[i] = alt;
495 		break;
496 	case UCSI_RECIPIENT_SOP_P:
497 		i = ucsi_next_altmode(con->plug_altmode);
498 		if (i < 0) {
499 			ret = i;
500 			goto err;
501 		}
502 
503 		ret = ucsi_altmode_next_mode(con->plug_altmode, desc->svid);
504 		if (ret < 0)
505 			return ret;
506 
507 		desc->mode = ret;
508 
509 		alt = typec_plug_register_altmode(con->plug, desc);
510 		if (IS_ERR(alt)) {
511 			ret = PTR_ERR(alt);
512 			goto err;
513 		}
514 
515 		con->plug_altmode[i] = alt;
516 		break;
517 	default:
518 		return -EINVAL;
519 	}
520 
521 	trace_ucsi_register_altmode(recipient, alt);
522 
523 	return 0;
524 
525 err:
526 	dev_err(con->ucsi->dev, "failed to registers svid 0x%04x mode %d\n",
527 		desc->svid, desc->mode);
528 
529 	return ret;
530 }
531 
532 static int
533 ucsi_register_altmodes_nvidia(struct ucsi_connector *con, u8 recipient)
534 {
535 	int max_altmodes = UCSI_MAX_ALTMODES;
536 	struct typec_altmode_desc desc;
537 	struct ucsi_altmode alt;
538 	struct ucsi_altmode orig[UCSI_MAX_ALTMODES];
539 	struct ucsi_altmode updated[UCSI_MAX_ALTMODES];
540 	struct ucsi *ucsi = con->ucsi;
541 	bool multi_dp = false;
542 	u64 command;
543 	int ret;
544 	int len;
545 	int i;
546 	int k = 0;
547 
548 	if (recipient == UCSI_RECIPIENT_CON)
549 		max_altmodes = con->ucsi->cap.num_alt_modes;
550 
551 	memset(orig, 0, sizeof(orig));
552 	memset(updated, 0, sizeof(updated));
553 
554 	/* First get all the alternate modes */
555 	for (i = 0; i < max_altmodes; i++) {
556 		memset(&alt, 0, sizeof(alt));
557 		command = UCSI_GET_ALTERNATE_MODES;
558 		command |= UCSI_GET_ALTMODE_RECIPIENT(recipient);
559 		command |= UCSI_GET_ALTMODE_CONNECTOR_NUMBER(con->num);
560 		command |= UCSI_GET_ALTMODE_OFFSET(i);
561 		len = ucsi_send_command(con->ucsi, command, &alt, sizeof(alt));
562 		/*
563 		 * We are collecting all altmodes first and then registering.
564 		 * Some type-C device will return zero length data beyond last
565 		 * alternate modes. We should not return if length is zero.
566 		 */
567 		if (len < 0)
568 			return len;
569 
570 		/* We got all altmodes, now break out and register them */
571 		if (!len || !alt.svid)
572 			break;
573 
574 		orig[k].mid = alt.mid;
575 		orig[k].svid = alt.svid;
576 		k++;
577 	}
578 	/*
579 	 * Update the original altmode table as some ppms may report
580 	 * multiple DP altmodes.
581 	 */
582 	multi_dp = ucsi->ops->update_altmodes(ucsi, recipient, orig, updated);
583 
584 	/* now register altmodes */
585 	for (i = 0; i < max_altmodes; i++) {
586 		memset(&desc, 0, sizeof(desc));
587 		if (multi_dp) {
588 			desc.svid = updated[i].svid;
589 			desc.vdo = updated[i].mid;
590 		} else {
591 			desc.svid = orig[i].svid;
592 			desc.vdo = orig[i].mid;
593 		}
594 		desc.roles = TYPEC_PORT_DRD;
595 
596 		if (!desc.svid)
597 			return 0;
598 
599 		ret = ucsi_register_altmode(con, &desc, recipient);
600 		if (ret)
601 			return ret;
602 	}
603 
604 	return 0;
605 }
606 
607 static int ucsi_register_altmodes(struct ucsi_connector *con, u8 recipient)
608 {
609 	int max_altmodes = UCSI_MAX_ALTMODES;
610 	struct typec_altmode_desc desc;
611 	struct ucsi_altmode alt[2];
612 	u64 command;
613 	int num;
614 	int ret;
615 	int len;
616 	int j;
617 	int i;
618 
619 	if (!(con->ucsi->cap.features & UCSI_CAP_ALT_MODE_DETAILS))
620 		return 0;
621 
622 	if (recipient == UCSI_RECIPIENT_SOP && con->partner_altmode[0])
623 		return 0;
624 
625 	if (con->ucsi->ops->update_altmodes)
626 		return ucsi_register_altmodes_nvidia(con, recipient);
627 
628 	if (recipient == UCSI_RECIPIENT_CON)
629 		max_altmodes = con->ucsi->cap.num_alt_modes;
630 
631 	for (i = 0; i < max_altmodes;) {
632 		memset(alt, 0, sizeof(alt));
633 		command = UCSI_GET_ALTERNATE_MODES;
634 		command |= UCSI_GET_ALTMODE_RECIPIENT(recipient);
635 		command |= UCSI_GET_ALTMODE_CONNECTOR_NUMBER(con->num);
636 		command |= UCSI_GET_ALTMODE_OFFSET(i);
637 		len = ucsi_send_command(con->ucsi, command, alt, sizeof(alt));
638 		if (len == -EBUSY)
639 			continue;
640 		if (len <= 0)
641 			return len;
642 
643 		/*
644 		 * This code is requesting one alt mode at a time, but some PPMs
645 		 * may still return two. If that happens both alt modes need be
646 		 * registered and the offset for the next alt mode has to be
647 		 * incremented.
648 		 */
649 		num = len / sizeof(alt[0]);
650 		i += num;
651 
652 		for (j = 0; j < num; j++) {
653 			if (!alt[j].svid)
654 				return 0;
655 
656 			memset(&desc, 0, sizeof(desc));
657 			desc.vdo = alt[j].mid;
658 			desc.svid = alt[j].svid;
659 			desc.roles = TYPEC_PORT_DRD;
660 			desc.mode_selection = con->ucsi->ops->add_partner_altmodes &&
661 					!con->typec_cap.no_mode_control;
662 
663 			ret = ucsi_register_altmode(con, &desc, recipient);
664 			if (ret)
665 				return ret;
666 		}
667 	}
668 
669 	return 0;
670 }
671 
672 static void ucsi_unregister_altmodes(struct ucsi_connector *con, u8 recipient)
673 {
674 	const struct typec_altmode *pdev;
675 	struct typec_altmode **adev;
676 	int i = 0;
677 
678 	switch (recipient) {
679 	case UCSI_RECIPIENT_CON:
680 		adev = con->port_altmode;
681 		break;
682 	case UCSI_RECIPIENT_SOP:
683 		adev = con->partner_altmode;
684 		break;
685 	case UCSI_RECIPIENT_SOP_P:
686 		adev = con->plug_altmode;
687 		break;
688 	default:
689 		return;
690 	}
691 
692 	while (adev[i]) {
693 		if (recipient == UCSI_RECIPIENT_SOP) {
694 			pdev = typec_altmode_get_partner(adev[i]);
695 
696 			if (adev[i]->svid == USB_TYPEC_DP_SID ||
697 			    (adev[i]->svid == USB_TYPEC_NVIDIA_VLINK_SID &&
698 			     adev[i]->vdo != USB_TYPEC_NVIDIA_VLINK_DBG_VDO))
699 				ucsi_displayport_remove_partner((void *)pdev);
700 			else if (adev[i]->svid == USB_TYPEC_TBT_SID)
701 				ucsi_thunderbolt_remove_partner((void *)pdev);
702 		}
703 		typec_unregister_altmode(adev[i]);
704 		adev[i++] = NULL;
705 	}
706 }
707 
708 static int ucsi_get_connector_status(struct ucsi_connector *con, bool conn_ack)
709 {
710 	u64 command = UCSI_GET_CONNECTOR_STATUS | UCSI_CONNECTOR_NUMBER(con->num);
711 	size_t size = min(sizeof(con->status),
712 			  UCSI_MAX_DATA_LENGTH(con->ucsi));
713 	int ret;
714 
715 	ret = ucsi_send_command_common(con->ucsi, command, &con->status, size,
716 				       NULL, 0, conn_ack);
717 
718 	return ret < 0 ? ret : 0;
719 }
720 
721 static int ucsi_read_pdos(struct ucsi_connector *con,
722 			  enum typec_role role, int is_partner,
723 			  u32 *pdos, int offset, int num_pdos)
724 {
725 	struct ucsi *ucsi = con->ucsi;
726 	u64 command;
727 	int ret;
728 
729 	if (is_partner &&
730 	    ucsi->quirks & UCSI_NO_PARTNER_PDOS &&
731 	    (UCSI_CONSTAT(con, PWR_DIR) || !is_source(role)))
732 		return 0;
733 
734 	command = UCSI_COMMAND(UCSI_GET_PDOS) | UCSI_CONNECTOR_NUMBER(con->num);
735 	command |= UCSI_GET_PDOS_PARTNER_PDO(is_partner);
736 	command |= UCSI_GET_PDOS_PDO_OFFSET(offset);
737 	command |= UCSI_GET_PDOS_NUM_PDOS(num_pdos - 1);
738 	command |= is_source(role) ? UCSI_GET_PDOS_SRC_PDOS : 0;
739 	ret = ucsi_send_command(ucsi, command, pdos + offset,
740 				num_pdos * sizeof(u32));
741 	if (ret < 0 && ret != -ETIMEDOUT)
742 		dev_err(ucsi->dev, "UCSI_GET_PDOS failed (%d)\n", ret);
743 
744 	return ret;
745 }
746 
747 static int ucsi_get_pdos(struct ucsi_connector *con, enum typec_role role,
748 			 int is_partner, u32 *pdos)
749 {
750 	struct ucsi *ucsi = con->ucsi;
751 	u8 num_pdos;
752 	int ret;
753 
754 	if (!(ucsi->cap.features & UCSI_CAP_PDO_DETAILS))
755 		return 0;
756 
757 	/* UCSI max payload means only getting at most 4 PDOs at a time */
758 	ret = ucsi_read_pdos(con, role, is_partner, pdos, 0, UCSI_MAX_PDOS);
759 	if (ret < 0)
760 		return ret;
761 
762 	num_pdos = ret / sizeof(u32); /* number of bytes to 32-bit PDOs */
763 	if (num_pdos < UCSI_MAX_PDOS)
764 		return num_pdos;
765 
766 	/* get the remaining PDOs, if any */
767 	ret = ucsi_read_pdos(con, role, is_partner, pdos, UCSI_MAX_PDOS,
768 			     PDO_MAX_OBJECTS - UCSI_MAX_PDOS);
769 	if (ret < 0)
770 		return ret;
771 
772 	return ret / sizeof(u32) + num_pdos;
773 }
774 
775 static int ucsi_get_src_pdos(struct ucsi_connector *con)
776 {
777 	int ret;
778 
779 	ret = ucsi_get_pdos(con, TYPEC_SOURCE, 1, con->src_pdos);
780 	if (ret < 0)
781 		return ret;
782 
783 	con->num_pdos = ret;
784 
785 	ucsi_port_psy_changed(con);
786 
787 	return ret;
788 }
789 
790 static struct usb_power_delivery_capabilities *ucsi_get_pd_caps(struct ucsi_connector *con,
791 								enum typec_role role,
792 								bool is_partner)
793 {
794 	struct usb_power_delivery_capabilities_desc pd_caps;
795 	int ret;
796 
797 	ret = ucsi_get_pdos(con, role, is_partner, pd_caps.pdo);
798 	if (ret <= 0)
799 		return ERR_PTR(ret);
800 
801 	if (ret < PDO_MAX_OBJECTS)
802 		pd_caps.pdo[ret] = 0;
803 
804 	pd_caps.role = role;
805 
806 	return usb_power_delivery_register_capabilities(is_partner ? con->partner_pd : con->pd,
807 							&pd_caps);
808 }
809 
810 static int ucsi_get_pd_message(struct ucsi_connector *con, u8 recipient,
811 			       size_t bytes, void *data, u8 type)
812 {
813 	size_t len = min(bytes, UCSI_MAX_DATA_LENGTH(con->ucsi));
814 	u64 command;
815 	u8 offset;
816 	int ret;
817 
818 	for (offset = 0; offset < bytes; offset += len) {
819 		len = min(len, bytes - offset);
820 
821 		command = UCSI_COMMAND(UCSI_GET_PD_MESSAGE) | UCSI_CONNECTOR_NUMBER(con->num);
822 		command |= UCSI_GET_PD_MESSAGE_RECIPIENT(recipient);
823 		command |= UCSI_GET_PD_MESSAGE_OFFSET(offset);
824 		command |= UCSI_GET_PD_MESSAGE_BYTES(len);
825 		command |= UCSI_GET_PD_MESSAGE_TYPE(type);
826 
827 		ret = ucsi_send_command(con->ucsi, command, data + offset, len);
828 		if (ret < 0)
829 			return ret;
830 	}
831 
832 	return 0;
833 }
834 
835 static int ucsi_get_partner_identity(struct ucsi_connector *con)
836 {
837 	u32 vdo[7] = {};
838 	int ret;
839 
840 	ret = ucsi_get_pd_message(con, UCSI_RECIPIENT_SOP, sizeof(vdo), vdo,
841 				  UCSI_GET_PD_MESSAGE_TYPE_IDENTITY);
842 	if (ret < 0)
843 		return ret;
844 
845 	/* VDM Header is not part of struct usb_pd_identity, so dropping it. */
846 	con->partner_identity = *(struct usb_pd_identity *)&vdo[1];
847 
848 	ret = typec_partner_set_identity(con->partner);
849 	if (ret < 0)
850 		dev_err(con->ucsi->dev, "Failed to set partner identity (%d)\n", ret);
851 
852 	return ret;
853 }
854 
855 static int ucsi_get_cable_identity(struct ucsi_connector *con)
856 {
857 	u32 vdo[7] = {};
858 	int ret;
859 
860 	ret = ucsi_get_pd_message(con, UCSI_RECIPIENT_SOP_P, sizeof(vdo), vdo,
861 				  UCSI_GET_PD_MESSAGE_TYPE_IDENTITY);
862 	if (ret < 0)
863 		return ret;
864 
865 	con->cable_identity = *(struct usb_pd_identity *)&vdo[1];
866 
867 	ret = typec_cable_set_identity(con->cable);
868 	if (ret < 0)
869 		dev_err(con->ucsi->dev, "Failed to set cable identity (%d)\n", ret);
870 
871 	return ret;
872 }
873 
874 static int ucsi_check_altmodes(struct ucsi_connector *con)
875 {
876 	int ret, num_partner_am;
877 
878 	ret = ucsi_register_altmodes(con, UCSI_RECIPIENT_SOP);
879 	if (ret && ret != -ETIMEDOUT)
880 		dev_err(con->ucsi->dev,
881 			"con%d: failed to register partner alt modes (%d)\n",
882 			con->num, ret);
883 
884 	/* Ignoring the errors in this case. */
885 	if (con->partner_altmode[0]) {
886 		num_partner_am = ucsi_get_num_altmode(con->partner_altmode);
887 		typec_partner_set_num_altmodes(con->partner, num_partner_am);
888 		if (con->ucsi->ops->add_partner_altmodes)
889 			con->ucsi->ops->add_partner_altmodes(con);
890 		ucsi_altmode_update_active(con);
891 		return 0;
892 	} else {
893 		typec_partner_set_num_altmodes(con->partner, 0);
894 	}
895 
896 	return ret;
897 }
898 
899 static void ucsi_register_device_pdos(struct ucsi_connector *con)
900 {
901 	struct ucsi *ucsi = con->ucsi;
902 	struct usb_power_delivery_desc desc = { ucsi->cap.pd_version };
903 	struct usb_power_delivery_capabilities *pd_cap;
904 
905 	if (con->pd)
906 		return;
907 
908 	con->pd = usb_power_delivery_register(ucsi->dev, &desc);
909 
910 	pd_cap = ucsi_get_pd_caps(con, TYPEC_SOURCE, false);
911 	if (!IS_ERR(pd_cap))
912 		con->port_source_caps = pd_cap;
913 
914 	pd_cap = ucsi_get_pd_caps(con, TYPEC_SINK, false);
915 	if (!IS_ERR(pd_cap))
916 		con->port_sink_caps = pd_cap;
917 
918 	typec_port_set_usb_power_delivery(con->port, con->pd);
919 }
920 
921 static int ucsi_register_partner_pdos(struct ucsi_connector *con)
922 {
923 	struct usb_power_delivery_desc desc = { con->ucsi->cap.pd_version };
924 	struct usb_power_delivery_capabilities *cap;
925 
926 	if (con->partner_pd)
927 		return 0;
928 
929 	con->partner_pd = typec_partner_usb_power_delivery_register(con->partner, &desc);
930 	if (IS_ERR(con->partner_pd))
931 		return PTR_ERR(con->partner_pd);
932 
933 	cap = ucsi_get_pd_caps(con, TYPEC_SOURCE, true);
934 	if (IS_ERR(cap))
935 	    return PTR_ERR(cap);
936 
937 	con->partner_source_caps = cap;
938 
939 	cap = ucsi_get_pd_caps(con, TYPEC_SINK, true);
940 	if (IS_ERR(cap))
941 	    return PTR_ERR(cap);
942 
943 	con->partner_sink_caps = cap;
944 
945 	return typec_partner_set_usb_power_delivery(con->partner, con->partner_pd);
946 }
947 
948 static void ucsi_unregister_partner_pdos(struct ucsi_connector *con)
949 {
950 	usb_power_delivery_unregister_capabilities(con->partner_sink_caps);
951 	con->partner_sink_caps = NULL;
952 	usb_power_delivery_unregister_capabilities(con->partner_source_caps);
953 	con->partner_source_caps = NULL;
954 	usb_power_delivery_unregister(con->partner_pd);
955 	con->partner_pd = NULL;
956 }
957 
958 static int ucsi_register_plug(struct ucsi_connector *con)
959 {
960 	struct typec_plug *plug;
961 	struct typec_plug_desc desc = {.index = TYPEC_PLUG_SOP_P};
962 
963 	plug = typec_register_plug(con->cable, &desc);
964 	if (IS_ERR(plug)) {
965 		dev_err(con->ucsi->dev,
966 			"con%d: failed to register plug (%ld)\n", con->num,
967 			PTR_ERR(plug));
968 		return PTR_ERR(plug);
969 	}
970 
971 	con->plug = plug;
972 	return 0;
973 }
974 
975 static void ucsi_unregister_plug(struct ucsi_connector *con)
976 {
977 	if (!con->plug)
978 		return;
979 
980 	ucsi_unregister_altmodes(con, UCSI_RECIPIENT_SOP_P);
981 	typec_unregister_plug(con->plug);
982 	con->plug = NULL;
983 }
984 
985 static int ucsi_register_cable(struct ucsi_connector *con)
986 {
987 	struct ucsi_cable_property cable_prop;
988 	struct typec_cable *cable;
989 	struct typec_cable_desc desc = {};
990 	u64 command;
991 	int ret;
992 
993 	command = UCSI_GET_CABLE_PROPERTY | UCSI_CONNECTOR_NUMBER(con->num);
994 	ret = ucsi_send_command(con->ucsi, command, &cable_prop, sizeof(cable_prop));
995 	if (ret < 0) {
996 		dev_err(con->ucsi->dev, "GET_CABLE_PROPERTY failed (%d)\n", ret);
997 		return ret;
998 	}
999 
1000 	switch (UCSI_CABLE_PROP_FLAG_PLUG_TYPE(cable_prop.flags)) {
1001 	case UCSI_CABLE_PROPERTY_PLUG_TYPE_A:
1002 		desc.type = USB_PLUG_TYPE_A;
1003 		break;
1004 	case UCSI_CABLE_PROPERTY_PLUG_TYPE_B:
1005 		desc.type = USB_PLUG_TYPE_B;
1006 		break;
1007 	case UCSI_CABLE_PROPERTY_PLUG_TYPE_C:
1008 		desc.type = USB_PLUG_TYPE_C;
1009 		break;
1010 	default:
1011 		desc.type = USB_PLUG_NONE;
1012 		break;
1013 	}
1014 
1015 	if (con->ucsi->cap.features & UCSI_CAP_GET_PD_MESSAGE)
1016 		desc.identity = &con->cable_identity;
1017 	desc.active = !!(UCSI_CABLE_PROP_FLAG_ACTIVE_CABLE & cable_prop.flags);
1018 
1019 	if (con->ucsi->version >= UCSI_VERSION_2_1)
1020 		desc.pd_revision = UCSI_CABLE_PROP_FLAG_PD_MAJOR_REV_AS_BCD(cable_prop.flags);
1021 
1022 	cable = typec_register_cable(con->port, &desc);
1023 	if (IS_ERR(cable)) {
1024 		dev_err(con->ucsi->dev,
1025 			"con%d: failed to register cable (%ld)\n", con->num,
1026 			PTR_ERR(cable));
1027 		return PTR_ERR(cable);
1028 	}
1029 
1030 	con->cable = cable;
1031 	return 0;
1032 }
1033 
1034 static void ucsi_unregister_cable(struct ucsi_connector *con)
1035 {
1036 	if (!con->cable)
1037 		return;
1038 
1039 	ucsi_unregister_plug(con);
1040 	typec_unregister_cable(con->cable);
1041 	memset(&con->cable_identity, 0, sizeof(con->cable_identity));
1042 	con->cable = NULL;
1043 }
1044 
1045 static int ucsi_check_connector_capability(struct ucsi_connector *con)
1046 {
1047 	u64 pd_revision;
1048 	u64 command;
1049 	int ret;
1050 
1051 	if (!con->partner || con->ucsi->version < UCSI_VERSION_2_1)
1052 		return 0;
1053 
1054 	command = UCSI_GET_CONNECTOR_CAPABILITY | UCSI_CONNECTOR_NUMBER(con->num);
1055 	ret = ucsi_send_command(con->ucsi, command, &con->cap, sizeof(con->cap));
1056 	if (ret < 0) {
1057 		dev_err(con->ucsi->dev, "GET_CONNECTOR_CAPABILITY failed (%d)\n", ret);
1058 		return ret;
1059 	}
1060 
1061 	pd_revision = UCSI_CONCAP(con, PARTNER_PD_REVISION_V2_1);
1062 	typec_partner_set_pd_revision(con->partner, UCSI_SPEC_REVISION_TO_BCD(pd_revision));
1063 
1064 	return ret;
1065 }
1066 
1067 static void ucsi_orientation(struct ucsi_connector *con)
1068 {
1069 	if (con->ucsi->version < UCSI_VERSION_2_0)
1070 		return;
1071 
1072 	if (!UCSI_CONSTAT(con, CONNECTED)) {
1073 		typec_set_orientation(con->port, TYPEC_ORIENTATION_NONE);
1074 		return;
1075 	}
1076 
1077 	switch (UCSI_CONSTAT(con, ORIENTATION)) {
1078 	case UCSI_CONSTAT_ORIENTATION_NORMAL:
1079 		typec_set_orientation(con->port, TYPEC_ORIENTATION_NORMAL);
1080 		break;
1081 	case UCSI_CONSTAT_ORIENTATION_REVERSE:
1082 		typec_set_orientation(con->port, TYPEC_ORIENTATION_REVERSE);
1083 		break;
1084 	default:
1085 		break;
1086 	}
1087 }
1088 
1089 static void ucsi_pwr_opmode_change(struct ucsi_connector *con)
1090 {
1091 	switch (UCSI_CONSTAT(con, PWR_OPMODE)) {
1092 	case UCSI_CONSTAT_PWR_OPMODE_PD:
1093 		con->rdo = UCSI_CONSTAT(con, RDO);
1094 		typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_PD);
1095 		ucsi_partner_task(con, ucsi_get_src_pdos, 30, 0);
1096 		ucsi_partner_task(con, ucsi_check_altmodes, 30, HZ);
1097 		ucsi_partner_task(con, ucsi_register_partner_pdos, 1, HZ);
1098 		ucsi_partner_task(con, ucsi_check_connector_capability, 1, HZ);
1099 		break;
1100 	case UCSI_CONSTAT_PWR_OPMODE_TYPEC1_5:
1101 		con->rdo = 0;
1102 		typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_1_5A);
1103 		ucsi_port_psy_changed(con);
1104 		break;
1105 	case UCSI_CONSTAT_PWR_OPMODE_TYPEC3_0:
1106 		con->rdo = 0;
1107 		typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_3_0A);
1108 		ucsi_port_psy_changed(con);
1109 		break;
1110 	default:
1111 		con->rdo = 0;
1112 		typec_set_pwr_opmode(con->port, TYPEC_PWR_MODE_USB);
1113 		ucsi_port_psy_changed(con);
1114 		break;
1115 	}
1116 }
1117 
1118 static int ucsi_register_partner(struct ucsi_connector *con)
1119 {
1120 	u8 pwr_opmode = UCSI_CONSTAT(con, PWR_OPMODE);
1121 	struct typec_partner_desc desc;
1122 	struct typec_partner *partner;
1123 
1124 	if (con->partner)
1125 		return 0;
1126 
1127 	memset(&desc, 0, sizeof(desc));
1128 
1129 	switch (UCSI_CONSTAT(con, PARTNER_TYPE)) {
1130 	case UCSI_CONSTAT_PARTNER_TYPE_DEBUG:
1131 		desc.accessory = TYPEC_ACCESSORY_DEBUG;
1132 		break;
1133 	case UCSI_CONSTAT_PARTNER_TYPE_AUDIO:
1134 		desc.accessory = TYPEC_ACCESSORY_AUDIO;
1135 		break;
1136 	default:
1137 		break;
1138 	}
1139 
1140 	if (pwr_opmode == UCSI_CONSTAT_PWR_OPMODE_PD)
1141 		ucsi_register_device_pdos(con);
1142 
1143 	if (con->ucsi->cap.features & UCSI_CAP_GET_PD_MESSAGE)
1144 		desc.identity = &con->partner_identity;
1145 	desc.usb_pd = pwr_opmode == UCSI_CONSTAT_PWR_OPMODE_PD;
1146 
1147 	if (con->ucsi->version >= UCSI_VERSION_2_1) {
1148 		u64 pd_revision = UCSI_CONCAP(con, PARTNER_PD_REVISION_V2_1);
1149 		desc.pd_revision = UCSI_SPEC_REVISION_TO_BCD(pd_revision);
1150 	}
1151 
1152 	partner = typec_register_partner(con->port, &desc);
1153 	if (IS_ERR(partner)) {
1154 		dev_err(con->ucsi->dev,
1155 			"con%d: failed to register partner (%ld)\n", con->num,
1156 			PTR_ERR(partner));
1157 		return PTR_ERR(partner);
1158 	}
1159 
1160 	con->partner = partner;
1161 
1162 	if (con->ucsi->version >= UCSI_VERSION_3_0 &&
1163 	    UCSI_CONSTAT(con, PARTNER_FLAG_USB4_GEN4))
1164 		typec_partner_set_usb_mode(partner, USB_MODE_USB4);
1165 	else if (con->ucsi->version >= UCSI_VERSION_2_0 &&
1166 		 UCSI_CONSTAT(con, PARTNER_FLAG_USB4_GEN3))
1167 		typec_partner_set_usb_mode(partner, USB_MODE_USB4);
1168 
1169 	return 0;
1170 }
1171 
1172 static void ucsi_unregister_partner(struct ucsi_connector *con)
1173 {
1174 	if (!con->partner)
1175 		return;
1176 
1177 	typec_set_mode(con->port, TYPEC_STATE_SAFE);
1178 	if (con->ucsi->ops->remove_partner_altmodes)
1179 		con->ucsi->ops->remove_partner_altmodes(con);
1180 
1181 	typec_partner_set_usb_power_delivery(con->partner, NULL);
1182 	ucsi_unregister_partner_pdos(con);
1183 	ucsi_unregister_altmodes(con, UCSI_RECIPIENT_SOP);
1184 	ucsi_unregister_cable(con);
1185 	typec_unregister_partner(con->partner);
1186 	memset(&con->partner_identity, 0, sizeof(con->partner_identity));
1187 	con->partner = NULL;
1188 }
1189 
1190 static void ucsi_partner_change(struct ucsi_connector *con)
1191 {
1192 	enum usb_role u_role = USB_ROLE_NONE;
1193 	int ret;
1194 
1195 	switch (UCSI_CONSTAT(con, PARTNER_TYPE)) {
1196 	case UCSI_CONSTAT_PARTNER_TYPE_UFP:
1197 	case UCSI_CONSTAT_PARTNER_TYPE_CABLE_AND_UFP:
1198 		u_role = USB_ROLE_HOST;
1199 		fallthrough;
1200 	case UCSI_CONSTAT_PARTNER_TYPE_CABLE:
1201 		typec_set_data_role(con->port, TYPEC_HOST);
1202 		break;
1203 	case UCSI_CONSTAT_PARTNER_TYPE_DFP:
1204 		u_role = USB_ROLE_DEVICE;
1205 		typec_set_data_role(con->port, TYPEC_DEVICE);
1206 		break;
1207 	default:
1208 		break;
1209 	}
1210 
1211 	if (UCSI_CONSTAT(con, CONNECTED)) {
1212 		switch (UCSI_CONSTAT(con, PARTNER_TYPE)) {
1213 		case UCSI_CONSTAT_PARTNER_TYPE_DEBUG:
1214 			typec_set_mode(con->port, TYPEC_MODE_DEBUG);
1215 			break;
1216 		case UCSI_CONSTAT_PARTNER_TYPE_AUDIO:
1217 			typec_set_mode(con->port, TYPEC_MODE_AUDIO);
1218 			break;
1219 		default:
1220 			if (UCSI_CONSTAT(con, PARTNER_FLAG_USB))
1221 				typec_set_mode(con->port, TYPEC_STATE_USB);
1222 		}
1223 
1224 		if (((con->ucsi->version >= UCSI_VERSION_3_0 &&
1225 		    UCSI_CONSTAT(con, PARTNER_FLAG_USB4_GEN4)) ||
1226 		    (con->ucsi->version >= UCSI_VERSION_2_0 &&
1227 		    UCSI_CONSTAT(con, PARTNER_FLAG_USB4_GEN3))) && con->partner)
1228 			typec_partner_set_usb_mode(con->partner, USB_MODE_USB4);
1229 	}
1230 
1231 	if ((!UCSI_CONSTAT(con, PARTNER_FLAG_USB)) &&
1232 	    ((con->ucsi->quirks & UCSI_USB4_IMPLIES_USB) &&
1233 	     (!(UCSI_CONSTAT(con, PARTNER_FLAG_USB4_GEN3) ||
1234 		UCSI_CONSTAT(con, PARTNER_FLAG_USB4_GEN4)))))
1235 		u_role = USB_ROLE_NONE;
1236 
1237 	ret = usb_role_switch_set_role(con->usb_role_sw, u_role);
1238 	if (ret)
1239 		dev_err(con->ucsi->dev, "con:%d: failed to set usb role:%d\n",
1240 			con->num, u_role);
1241 }
1242 
1243 static int ucsi_check_connection(struct ucsi_connector *con)
1244 {
1245 	u8 prev_state = UCSI_CONSTAT(con, CONNECTED);
1246 	int ret;
1247 
1248 	ret = ucsi_get_connector_status(con, false);
1249 	if (ret) {
1250 		dev_err(con->ucsi->dev, "GET_CONNECTOR_STATUS failed (%d)\n", ret);
1251 		return ret;
1252 	}
1253 
1254 	if (UCSI_CONSTAT(con, CONNECTED)) {
1255 		if (prev_state)
1256 			return 0;
1257 		ucsi_register_partner(con);
1258 		ucsi_pwr_opmode_change(con);
1259 		ucsi_partner_change(con);
1260 	} else {
1261 		ucsi_partner_change(con);
1262 		ucsi_port_psy_changed(con);
1263 		ucsi_unregister_partner(con);
1264 	}
1265 
1266 	return 0;
1267 }
1268 
1269 static int ucsi_check_cable(struct ucsi_connector *con)
1270 {
1271 	int ret, num_plug_am;
1272 
1273 	if (con->cable)
1274 		return 0;
1275 
1276 	ret = ucsi_register_cable(con);
1277 	if (ret < 0)
1278 		return ret;
1279 
1280 	if (con->ucsi->cap.features & UCSI_CAP_GET_PD_MESSAGE) {
1281 		ret = ucsi_get_cable_identity(con);
1282 		if (ret < 0)
1283 			return ret;
1284 	}
1285 
1286 	if (con->ucsi->cap.features & UCSI_CAP_ALT_MODE_DETAILS) {
1287 		ret = ucsi_register_plug(con);
1288 		if (ret < 0)
1289 			return ret;
1290 
1291 		ret = ucsi_register_altmodes(con, UCSI_RECIPIENT_SOP_P);
1292 		if (ret < 0)
1293 			return ret;
1294 
1295 		if (con->plug_altmode[0]) {
1296 			num_plug_am = ucsi_get_num_altmode(con->plug_altmode);
1297 			typec_plug_set_num_altmodes(con->plug, num_plug_am);
1298 		} else {
1299 			typec_plug_set_num_altmodes(con->plug, 0);
1300 		}
1301 	}
1302 
1303 	return 0;
1304 }
1305 
1306 static void ucsi_handle_connector_change(struct work_struct *work)
1307 {
1308 	struct ucsi_connector *con = container_of(work, struct ucsi_connector,
1309 						  work);
1310 	struct ucsi *ucsi = con->ucsi;
1311 	u8 curr_scale, volt_scale;
1312 	enum typec_role role, prev_role;
1313 	u16 change;
1314 	int ret;
1315 	u32 val;
1316 
1317 	mutex_lock(&con->lock);
1318 
1319 	if (!test_and_set_bit(EVENT_PENDING, &ucsi->flags))
1320 		dev_err_once(ucsi->dev, "%s entered without EVENT_PENDING\n",
1321 			     __func__);
1322 
1323 	prev_role = UCSI_CONSTAT(con, PWR_DIR);
1324 
1325 	ret = ucsi_get_connector_status(con, true);
1326 	if (ret) {
1327 		dev_err(ucsi->dev, "%s: GET_CONNECTOR_STATUS failed (%d)\n",
1328 			__func__, ret);
1329 		clear_bit(EVENT_PENDING, &con->ucsi->flags);
1330 		goto out_unlock;
1331 	}
1332 
1333 	trace_ucsi_connector_change(con->num, con);
1334 
1335 	if (ucsi->ops->connector_status)
1336 		ucsi->ops->connector_status(con);
1337 
1338 	change = UCSI_CONSTAT(con, CHANGE);
1339 	role = UCSI_CONSTAT(con, PWR_DIR);
1340 
1341 	if ((change & UCSI_CONSTAT_POWER_DIR_CHANGE) && role != prev_role) {
1342 		typec_set_pwr_role(con->port, role);
1343 
1344 		/* Some power_supply properties vary depending on the power direction when
1345 		 * connected
1346 		 */
1347 		if (UCSI_CONSTAT(con, CONNECTED))
1348 			ucsi_port_psy_changed(con);
1349 
1350 		/* Complete pending power role swap */
1351 		if (!completion_done(&con->complete))
1352 			complete(&con->complete);
1353 	}
1354 
1355 	if (change & UCSI_CONSTAT_CONNECT_CHANGE) {
1356 		typec_set_pwr_role(con->port, role);
1357 		ucsi_port_psy_changed(con);
1358 		ucsi_partner_change(con);
1359 		ucsi_orientation(con);
1360 
1361 		if (UCSI_CONSTAT(con, CONNECTED)) {
1362 			ucsi_register_partner(con);
1363 			ucsi_partner_task(con, ucsi_check_connection, 1, HZ);
1364 			if (con->ucsi->cap.features & UCSI_CAP_GET_PD_MESSAGE)
1365 				ucsi_partner_task(con, ucsi_get_partner_identity, 1, HZ);
1366 			if (con->ucsi->cap.features & UCSI_CAP_CABLE_DETAILS)
1367 				ucsi_partner_task(con, ucsi_check_cable, 1, HZ);
1368 
1369 			if (UCSI_CONSTAT(con, PWR_OPMODE) == UCSI_CONSTAT_PWR_OPMODE_PD) {
1370 				ucsi_partner_task(con, ucsi_register_partner_pdos, 1, HZ);
1371 				ucsi_partner_task(con, ucsi_check_connector_capability, 1, HZ);
1372 			}
1373 		} else {
1374 			ucsi_unregister_partner(con);
1375 		}
1376 	}
1377 
1378 	if (change & (UCSI_CONSTAT_POWER_OPMODE_CHANGE | UCSI_CONSTAT_POWER_LEVEL_CHANGE))
1379 		ucsi_pwr_opmode_change(con);
1380 
1381 	if (con->partner && (change & UCSI_CONSTAT_PARTNER_CHANGE)) {
1382 		ucsi_partner_change(con);
1383 		ucsi_altmode_update_active(con);
1384 
1385 		/* Complete pending data role swap */
1386 		if (!completion_done(&con->complete))
1387 			complete(&con->complete);
1388 	}
1389 
1390 	if (change & UCSI_CONSTAT_CAM_CHANGE)
1391 		ucsi_partner_task(con, ucsi_check_altmodes, 1, HZ);
1392 
1393 	if (change & (UCSI_CONSTAT_BC_CHANGE | UCSI_CONSTAT_SINK_PATH_CHANGE))
1394 		ucsi_port_psy_changed(con);
1395 
1396 	if (con->ucsi->version >= UCSI_VERSION_2_1 &&
1397 	    UCSI_CONSTAT(con, PWR_READING_READY_V2_1)) {
1398 		curr_scale = UCSI_CONSTAT(con, CURRENT_SCALE_V2_1);
1399 		volt_scale = UCSI_CONSTAT(con, VOLTAGE_SCALE_V2_1);
1400 
1401 		val = UCSI_CONSTAT(con, PEAK_CURRENT_V2_1);
1402 		con->peak_current = UCSI_CONSTAT_CURR_SCALE_MULT * curr_scale * val;
1403 
1404 		val = UCSI_CONSTAT(con, AVG_CURRENT_V2_1);
1405 		con->avg_current = UCSI_CONSTAT_CURR_SCALE_MULT * curr_scale * val;
1406 
1407 		val = UCSI_CONSTAT(con, VBUS_VOLTAGE_V2_1);
1408 		con->vbus_voltage = UCSI_CONSTAT_VOLT_SCALE_MULT * volt_scale * val;
1409 	}
1410 
1411 out_unlock:
1412 	mutex_unlock(&con->lock);
1413 }
1414 
1415 /**
1416  * ucsi_connector_change - Process Connector Change Event
1417  * @ucsi: UCSI Interface
1418  * @num: Connector number
1419  */
1420 void ucsi_connector_change(struct ucsi *ucsi, u8 num)
1421 {
1422 	struct ucsi_connector *con;
1423 
1424 	if (!(ucsi->ntfy & UCSI_ENABLE_NTFY_CONNECTOR_CHANGE)) {
1425 		dev_dbg(ucsi->dev, "Early connector change event\n");
1426 		return;
1427 	}
1428 
1429 	if (!num || num > ucsi->cap.num_connectors) {
1430 		dev_warn_ratelimited(ucsi->dev,
1431 				     "Bogus connector change on %u (max %u)\n",
1432 				     num, ucsi->cap.num_connectors);
1433 		return;
1434 	}
1435 
1436 	con = &ucsi->connector[num - 1];
1437 
1438 	if (!test_and_set_bit(EVENT_PENDING, &ucsi->flags))
1439 		schedule_work(&con->work);
1440 }
1441 EXPORT_SYMBOL_GPL(ucsi_connector_change);
1442 
1443 /* -------------------------------------------------------------------------- */
1444 
1445 /*
1446  * Hard Reset bit field was defined with value 1 in UCSI spec version 1.0.
1447  * Starting with spec version 1.1, Hard Reset bit field was removed from the
1448  * CONNECTOR_RESET command, until spec 2.0 reintroduced it with value 0, so, in effect,
1449  * the value to pass in to the command for a Hard Reset is different depending
1450  * on the supported UCSI version by the LPM.
1451  *
1452  * For performing a Data Reset on LPMs supporting version 2.0 and greater,
1453  * this function needs to be called with the second argument set to 0.
1454  */
1455 static int ucsi_reset_connector(struct ucsi_connector *con, bool hard)
1456 {
1457 	u64 command;
1458 
1459 	command = UCSI_CONNECTOR_RESET | UCSI_CONNECTOR_NUMBER(con->num);
1460 
1461 	if (con->ucsi->version < UCSI_VERSION_1_1)
1462 		command |= hard ? UCSI_CONNECTOR_RESET_HARD_VER_1_0 : 0;
1463 	else if (con->ucsi->version >= UCSI_VERSION_2_0)
1464 		command |= hard ? 0 : UCSI_CONNECTOR_RESET_DATA_VER_2_0;
1465 
1466 	return ucsi_send_command(con->ucsi, command, NULL, 0);
1467 }
1468 
1469 static int ucsi_reset_ppm(struct ucsi *ucsi)
1470 {
1471 	u64 command;
1472 	unsigned long tmo;
1473 	u32 cci;
1474 	int ret;
1475 
1476 	mutex_lock(&ucsi->ppm_lock);
1477 
1478 	ret = ucsi->ops->poll_cci(ucsi, &cci);
1479 	if (ret < 0)
1480 		goto out;
1481 
1482 	/*
1483 	 * If UCSI_CCI_RESET_COMPLETE is already set we must clear
1484 	 * the flag before we start another reset. Send a
1485 	 * UCSI_SET_NOTIFICATION_ENABLE command to achieve this.
1486 	 * Ignore a timeout and try the reset anyway if this fails.
1487 	 */
1488 	if (cci & UCSI_CCI_RESET_COMPLETE) {
1489 		command = UCSI_SET_NOTIFICATION_ENABLE;
1490 		ret = ucsi->ops->async_control(ucsi, command);
1491 		if (ret < 0)
1492 			goto out;
1493 
1494 		tmo = jiffies + msecs_to_jiffies(UCSI_TIMEOUT_MS);
1495 		do {
1496 			ret = ucsi->ops->poll_cci(ucsi, &cci);
1497 			if (ret < 0)
1498 				goto out;
1499 			if (cci & UCSI_CCI_COMMAND_COMPLETE)
1500 				break;
1501 			if (time_is_before_jiffies(tmo))
1502 				break;
1503 			msleep(20);
1504 		} while (1);
1505 
1506 		WARN_ON(cci & UCSI_CCI_RESET_COMPLETE);
1507 	}
1508 
1509 	command = UCSI_PPM_RESET;
1510 	ret = ucsi->ops->async_control(ucsi, command);
1511 	if (ret < 0)
1512 		goto out;
1513 
1514 	tmo = jiffies + msecs_to_jiffies(UCSI_TIMEOUT_MS);
1515 
1516 	do {
1517 		if (time_is_before_jiffies(tmo)) {
1518 			ret = -ETIMEDOUT;
1519 			goto out;
1520 		}
1521 
1522 		/* Give the PPM time to process a reset before reading CCI */
1523 		msleep(20);
1524 
1525 		ret = ucsi->ops->poll_cci(ucsi, &cci);
1526 		if (ret)
1527 			goto out;
1528 
1529 		/* If the PPM is still doing something else, reset it again. */
1530 		if (cci & ~UCSI_CCI_RESET_COMPLETE) {
1531 			ret = ucsi->ops->async_control(ucsi, command);
1532 			if (ret < 0)
1533 				goto out;
1534 		}
1535 
1536 	} while (!(cci & UCSI_CCI_RESET_COMPLETE));
1537 
1538 out:
1539 	mutex_unlock(&ucsi->ppm_lock);
1540 	return ret;
1541 }
1542 
1543 static int ucsi_role_cmd(struct ucsi_connector *con, u64 command)
1544 {
1545 	int ret;
1546 
1547 	ret = ucsi_send_command(con->ucsi, command, NULL, 0);
1548 	if (ret == -ETIMEDOUT) {
1549 		u64 c;
1550 
1551 		/* PPM most likely stopped responding. Resetting everything. */
1552 		ucsi_reset_ppm(con->ucsi);
1553 
1554 		c = UCSI_SET_NOTIFICATION_ENABLE | con->ucsi->ntfy;
1555 		ucsi_send_command(con->ucsi, c, NULL, 0);
1556 
1557 		ucsi_reset_connector(con, true);
1558 	}
1559 
1560 	return ret;
1561 }
1562 
1563 static int ucsi_dr_swap(struct typec_port *port, enum typec_data_role role)
1564 {
1565 	struct ucsi_connector *con = typec_get_drvdata(port);
1566 	u8 partner_type;
1567 	u64 command;
1568 	int ret = 0;
1569 
1570 	mutex_lock(&con->lock);
1571 
1572 	if (!con->partner) {
1573 		ret = -ENOTCONN;
1574 		goto out_unlock;
1575 	}
1576 
1577 	partner_type = UCSI_CONSTAT(con, PARTNER_TYPE);
1578 	if ((partner_type == UCSI_CONSTAT_PARTNER_TYPE_DFP &&
1579 	     role == TYPEC_DEVICE) ||
1580 	    (partner_type == UCSI_CONSTAT_PARTNER_TYPE_UFP &&
1581 	     role == TYPEC_HOST))
1582 		goto out_unlock;
1583 
1584 	reinit_completion(&con->complete);
1585 
1586 	command = UCSI_SET_UOR | UCSI_CONNECTOR_NUMBER(con->num);
1587 	command |= UCSI_SET_UOR_ROLE(role);
1588 	command |= UCSI_SET_UOR_ACCEPT_ROLE_SWAPS;
1589 	ret = ucsi_role_cmd(con, command);
1590 	if (ret < 0)
1591 		goto out_unlock;
1592 
1593 	mutex_unlock(&con->lock);
1594 
1595 	if (!wait_for_completion_timeout(&con->complete,
1596 					 msecs_to_jiffies(UCSI_SWAP_TIMEOUT_MS)))
1597 		return -ETIMEDOUT;
1598 
1599 	return 0;
1600 
1601 out_unlock:
1602 	mutex_unlock(&con->lock);
1603 
1604 	return ret;
1605 }
1606 
1607 static int ucsi_pr_swap(struct typec_port *port, enum typec_role role)
1608 {
1609 	struct ucsi_connector *con = typec_get_drvdata(port);
1610 	enum typec_role cur_role;
1611 	u64 command;
1612 	int ret = 0;
1613 
1614 	mutex_lock(&con->lock);
1615 
1616 	if (!con->partner) {
1617 		ret = -ENOTCONN;
1618 		goto out_unlock;
1619 	}
1620 
1621 	cur_role = UCSI_CONSTAT(con, PWR_DIR);
1622 
1623 	if (cur_role == role)
1624 		goto out_unlock;
1625 
1626 	reinit_completion(&con->complete);
1627 
1628 	command = UCSI_SET_PDR | UCSI_CONNECTOR_NUMBER(con->num);
1629 	command |= UCSI_SET_PDR_ROLE(role);
1630 	command |= UCSI_SET_PDR_ACCEPT_ROLE_SWAPS;
1631 	ret = ucsi_role_cmd(con, command);
1632 	if (ret < 0)
1633 		goto out_unlock;
1634 
1635 	mutex_unlock(&con->lock);
1636 
1637 	if (!wait_for_completion_timeout(&con->complete,
1638 					 msecs_to_jiffies(UCSI_SWAP_TIMEOUT_MS)))
1639 		return -ETIMEDOUT;
1640 
1641 	mutex_lock(&con->lock);
1642 
1643 	/* Something has gone wrong while swapping the role */
1644 	if (UCSI_CONSTAT(con, PWR_OPMODE) != UCSI_CONSTAT_PWR_OPMODE_PD) {
1645 		ucsi_reset_connector(con, true);
1646 		ret = -EPROTO;
1647 	}
1648 
1649 out_unlock:
1650 	mutex_unlock(&con->lock);
1651 
1652 	return ret;
1653 }
1654 
1655 static const struct typec_operations ucsi_ops = {
1656 	.dr_set = ucsi_dr_swap,
1657 	.pr_set = ucsi_pr_swap
1658 };
1659 
1660 /* Caller must call fwnode_handle_put() after use */
1661 static struct fwnode_handle *ucsi_find_fwnode(struct ucsi_connector *con)
1662 {
1663 	struct fwnode_handle *fwnode;
1664 	int i = 1;
1665 
1666 	device_for_each_child_node(con->ucsi->dev, fwnode)
1667 		if (i++ == con->num)
1668 			return fwnode;
1669 	return NULL;
1670 }
1671 
1672 static int ucsi_register_port(struct ucsi *ucsi, struct ucsi_connector *con)
1673 {
1674 	struct typec_capability *cap = &con->typec_cap;
1675 	enum typec_accessory *accessory = cap->accessory;
1676 	enum usb_role u_role = USB_ROLE_NONE;
1677 	u64 command;
1678 	char *name;
1679 	int ret;
1680 
1681 	name = kasprintf(GFP_KERNEL, "%s-con%d", dev_name(ucsi->dev), con->num);
1682 	if (!name)
1683 		return -ENOMEM;
1684 
1685 	con->wq = create_singlethread_workqueue(name);
1686 	kfree(name);
1687 	if (!con->wq)
1688 		return -ENOMEM;
1689 
1690 	INIT_WORK(&con->work, ucsi_handle_connector_change);
1691 	init_completion(&con->complete);
1692 	mutex_init(&con->lock);
1693 	lockdep_set_class(&con->lock, &con->lock_key);
1694 	INIT_LIST_HEAD(&con->partner_tasks);
1695 	con->ucsi = ucsi;
1696 
1697 	cap->fwnode = ucsi_find_fwnode(con);
1698 	con->usb_role_sw = fwnode_usb_role_switch_get(cap->fwnode);
1699 	if (IS_ERR(con->usb_role_sw))
1700 		return dev_err_probe(ucsi->dev, PTR_ERR(con->usb_role_sw),
1701 			"con%d: failed to get usb role switch\n", con->num);
1702 
1703 	/* Delay other interactions with the con until registration is complete */
1704 	mutex_lock(&con->lock);
1705 
1706 	/* Get connector capability */
1707 	command = UCSI_GET_CONNECTOR_CAPABILITY;
1708 	command |= UCSI_CONNECTOR_NUMBER(con->num);
1709 	ret = ucsi_send_command(ucsi, command, &con->cap, sizeof(con->cap));
1710 	if (ret < 0)
1711 		goto out_unlock;
1712 
1713 	if (UCSI_CONCAP(con, OPMODE_DRP))
1714 		cap->data = TYPEC_PORT_DRD;
1715 	else if (UCSI_CONCAP(con, OPMODE_DFP))
1716 		cap->data = TYPEC_PORT_DFP;
1717 	else if (UCSI_CONCAP(con, OPMODE_UFP))
1718 		cap->data = TYPEC_PORT_UFP;
1719 
1720 	if (UCSI_CONCAP(con, PROVIDER) && UCSI_CONCAP(con, CONSUMER))
1721 		cap->type = TYPEC_PORT_DRP;
1722 	else if (UCSI_CONCAP(con, PROVIDER))
1723 		cap->type = TYPEC_PORT_SRC;
1724 	else if (UCSI_CONCAP(con, CONSUMER))
1725 		cap->type = TYPEC_PORT_SNK;
1726 
1727 	cap->revision = ucsi->cap.typec_version;
1728 	cap->pd_revision = ucsi->cap.pd_version;
1729 	cap->svdm_version = SVDM_VER_2_0;
1730 	cap->prefer_role = TYPEC_NO_PREFERRED_ROLE;
1731 
1732 	if (UCSI_CONCAP(con, OPMODE_AUDIO_ACCESSORY))
1733 		*accessory++ = TYPEC_ACCESSORY_AUDIO;
1734 	if (UCSI_CONCAP(con, OPMODE_DEBUG_ACCESSORY))
1735 		*accessory = TYPEC_ACCESSORY_DEBUG;
1736 
1737 	if (UCSI_CONCAP_USB2_SUPPORT(con))
1738 		cap->usb_capability |= USB_CAPABILITY_USB2;
1739 	if (UCSI_CONCAP_USB3_SUPPORT(con))
1740 		cap->usb_capability |= USB_CAPABILITY_USB3;
1741 	if (UCSI_CONCAP_USB4_SUPPORT(con))
1742 		cap->usb_capability |= USB_CAPABILITY_USB4;
1743 
1744 	cap->driver_data = con;
1745 	cap->ops = &ucsi_ops;
1746 	cap->no_mode_control = !(con->ucsi->cap.features & UCSI_CAP_ALT_MODE_OVERRIDE);
1747 
1748 	if (ucsi->version >= UCSI_VERSION_2_0)
1749 		con->typec_cap.orientation_aware = true;
1750 
1751 	if (ucsi->ops->update_connector)
1752 		ucsi->ops->update_connector(con);
1753 
1754 	ret = ucsi_register_port_psy(con);
1755 	if (ret)
1756 		goto out;
1757 
1758 	/* Register the connector */
1759 	con->port = typec_register_port(ucsi->dev, cap);
1760 	if (IS_ERR(con->port)) {
1761 		ret = PTR_ERR(con->port);
1762 		goto out;
1763 	}
1764 
1765 	if (!(ucsi->quirks & UCSI_DELAY_DEVICE_PDOS))
1766 		ucsi_register_device_pdos(con);
1767 
1768 	/* Alternate modes */
1769 	ret = ucsi_register_altmodes(con, UCSI_RECIPIENT_CON);
1770 	if (ret) {
1771 		dev_err(ucsi->dev, "con%d: failed to register alt modes\n",
1772 			con->num);
1773 		goto out;
1774 	}
1775 
1776 	/* Get the status */
1777 	ret = ucsi_get_connector_status(con, false);
1778 	if (ret) {
1779 		dev_err(ucsi->dev, "con%d: failed to get status\n", con->num);
1780 		goto out;
1781 	}
1782 
1783 	if (ucsi->ops->connector_status)
1784 		ucsi->ops->connector_status(con);
1785 
1786 	switch (UCSI_CONSTAT(con, PARTNER_TYPE)) {
1787 	case UCSI_CONSTAT_PARTNER_TYPE_UFP:
1788 	case UCSI_CONSTAT_PARTNER_TYPE_CABLE_AND_UFP:
1789 		u_role = USB_ROLE_HOST;
1790 		fallthrough;
1791 	case UCSI_CONSTAT_PARTNER_TYPE_CABLE:
1792 		typec_set_data_role(con->port, TYPEC_HOST);
1793 		break;
1794 	case UCSI_CONSTAT_PARTNER_TYPE_DFP:
1795 		u_role = USB_ROLE_DEVICE;
1796 		typec_set_data_role(con->port, TYPEC_DEVICE);
1797 		break;
1798 	default:
1799 		break;
1800 	}
1801 
1802 	/* Check if there is already something connected */
1803 	if (UCSI_CONSTAT(con, CONNECTED)) {
1804 		typec_set_pwr_role(con->port, UCSI_CONSTAT(con, PWR_DIR));
1805 		ucsi_register_partner(con);
1806 		ucsi_pwr_opmode_change(con);
1807 		ucsi_orientation(con);
1808 		ucsi_port_psy_changed(con);
1809 		if (con->ucsi->cap.features & UCSI_CAP_GET_PD_MESSAGE)
1810 			ucsi_get_partner_identity(con);
1811 		if (con->ucsi->cap.features & UCSI_CAP_CABLE_DETAILS)
1812 			ucsi_check_cable(con);
1813 	}
1814 
1815 	/* Only notify USB controller if partner supports USB data */
1816 	if (!(UCSI_CONSTAT(con, PARTNER_FLAG_USB)))
1817 		u_role = USB_ROLE_NONE;
1818 
1819 	ret = usb_role_switch_set_role(con->usb_role_sw, u_role);
1820 	if (ret) {
1821 		dev_err(ucsi->dev, "con:%d: failed to set usb role:%d\n",
1822 			con->num, u_role);
1823 		ret = 0;
1824 	}
1825 
1826 	if (con->partner && UCSI_CONSTAT(con, PWR_OPMODE) == UCSI_CONSTAT_PWR_OPMODE_PD) {
1827 		ucsi_register_device_pdos(con);
1828 		ucsi_get_src_pdos(con);
1829 		ucsi_check_altmodes(con);
1830 		ucsi_check_connector_capability(con);
1831 	}
1832 
1833 	trace_ucsi_register_port(con->num, con);
1834 
1835 out:
1836 	fwnode_handle_put(cap->fwnode);
1837 out_unlock:
1838 	mutex_unlock(&con->lock);
1839 
1840 	if (ret && con->wq) {
1841 		destroy_workqueue(con->wq);
1842 		con->wq = NULL;
1843 	}
1844 
1845 	return ret;
1846 }
1847 
1848 static u64 ucsi_get_supported_notifications(struct ucsi *ucsi)
1849 {
1850 	u16 features = ucsi->cap.features;
1851 	u64 ntfy = UCSI_ENABLE_NTFY_ALL;
1852 
1853 	if (!(features & UCSI_CAP_ALT_MODE_DETAILS))
1854 		ntfy &= ~UCSI_ENABLE_NTFY_CAM_CHANGE;
1855 
1856 	if (!(features & UCSI_CAP_PDO_DETAILS))
1857 		ntfy &= ~(UCSI_ENABLE_NTFY_PWR_LEVEL_CHANGE |
1858 			  UCSI_ENABLE_NTFY_CAP_CHANGE);
1859 
1860 	if (!(features & UCSI_CAP_EXT_SUPPLY_NOTIFICATIONS))
1861 		ntfy &= ~UCSI_ENABLE_NTFY_EXT_PWR_SRC_CHANGE;
1862 
1863 	if (!(features & UCSI_CAP_PD_RESET))
1864 		ntfy &= ~UCSI_ENABLE_NTFY_PD_RESET_COMPLETE;
1865 
1866 	if (ucsi->version <= UCSI_VERSION_1_2)
1867 		return ntfy;
1868 
1869 	ntfy |= UCSI_ENABLE_NTFY_SINK_PATH_STS_CHANGE;
1870 
1871 	if (features & UCSI_CAP_GET_ATTENTION_VDO)
1872 		ntfy |= UCSI_ENABLE_NTFY_ATTENTION;
1873 
1874 	if (features & UCSI_CAP_FW_UPDATE_REQUEST)
1875 		ntfy |= UCSI_ENABLE_NTFY_LPM_FW_UPDATE_REQ;
1876 
1877 	if (features & UCSI_CAP_SECURITY_REQUEST)
1878 		ntfy |= UCSI_ENABLE_NTFY_SECURITY_REQ_PARTNER;
1879 
1880 	if (features & UCSI_CAP_SET_RETIMER_MODE)
1881 		ntfy |= UCSI_ENABLE_NTFY_SET_RETIMER_MODE;
1882 
1883 	return ntfy;
1884 }
1885 
1886 /**
1887  * ucsi_init - Initialize UCSI interface
1888  * @ucsi: UCSI to be initialized
1889  *
1890  * Registers all ports @ucsi has and enables all notification events.
1891  */
1892 static int ucsi_init(struct ucsi *ucsi)
1893 {
1894 	struct ucsi_connector *con, *connector;
1895 	u64 command, ntfy;
1896 	u32 cci;
1897 	int ret;
1898 	int i;
1899 
1900 	/* Reset the PPM */
1901 	ret = ucsi_reset_ppm(ucsi);
1902 	if (ret) {
1903 		dev_err(ucsi->dev, "failed to reset PPM!\n");
1904 		goto err;
1905 	}
1906 
1907 	/* Enable basic notifications */
1908 	ntfy = UCSI_ENABLE_NTFY_CMD_COMPLETE | UCSI_ENABLE_NTFY_ERROR;
1909 	command = UCSI_SET_NOTIFICATION_ENABLE | ntfy;
1910 	ret = ucsi_send_command(ucsi, command, NULL, 0);
1911 	if (ret < 0)
1912 		goto err_reset;
1913 
1914 	/* Get PPM capabilities */
1915 	command = UCSI_GET_CAPABILITY;
1916 	ret = ucsi_send_command(ucsi, command, &ucsi->cap,
1917 				BITS_TO_BYTES(UCSI_GET_CAPABILITY_SIZE));
1918 	if (ret < 0)
1919 		goto err_reset;
1920 
1921 	if (!ucsi->cap.num_connectors) {
1922 		ret = -ENODEV;
1923 		goto err_reset;
1924 	}
1925 	/* Check if reserved bit set. This is out of spec but happens in buggy FW */
1926 	if (ucsi->cap.num_connectors & 0x80) {
1927 		dev_warn(ucsi->dev, "UCSI: Invalid num_connectors %d. Likely buggy FW\n",
1928 			 ucsi->cap.num_connectors);
1929 		ucsi->cap.num_connectors &= 0x7f; // clear bit and carry on
1930 	}
1931 
1932 	/* Allocate the connectors. Released in ucsi_unregister() */
1933 	connector = kzalloc_objs(*connector, ucsi->cap.num_connectors + 1);
1934 	if (!connector) {
1935 		ret = -ENOMEM;
1936 		goto err_reset;
1937 	}
1938 
1939 	for (i = 0; i < ucsi->cap.num_connectors; i++)
1940 		lockdep_register_key(&connector[i].lock_key);
1941 
1942 	/* Register all connectors */
1943 	for (i = 0; i < ucsi->cap.num_connectors; i++) {
1944 		connector[i].num = i + 1;
1945 		ret = ucsi_register_port(ucsi, &connector[i]);
1946 		if (ret)
1947 			goto err_unregister;
1948 	}
1949 
1950 	/* Enable all supported notifications */
1951 	ntfy = ucsi_get_supported_notifications(ucsi);
1952 	command = UCSI_SET_NOTIFICATION_ENABLE | ntfy;
1953 	ret = ucsi_send_command(ucsi, command, NULL, 0);
1954 	if (ret < 0)
1955 		goto err_unregister;
1956 
1957 	ucsi->connector = connector;
1958 	ucsi->ntfy = ntfy;
1959 
1960 	mutex_lock(&ucsi->ppm_lock);
1961 	ret = ucsi->ops->read_cci(ucsi, &cci);
1962 	mutex_unlock(&ucsi->ppm_lock);
1963 	if (ret)
1964 		return ret;
1965 	if (UCSI_CCI_CONNECTOR(cci))
1966 		ucsi_connector_change(ucsi, UCSI_CCI_CONNECTOR(cci));
1967 
1968 	return 0;
1969 
1970 err_unregister:
1971 	for (i = 0; i < ucsi->cap.num_connectors; i++)
1972 		lockdep_unregister_key(&connector[i].lock_key);
1973 
1974 	for (con = connector; con->port; con++) {
1975 		if (con->wq)
1976 			destroy_workqueue(con->wq);
1977 		ucsi_unregister_partner(con);
1978 		ucsi_unregister_altmodes(con, UCSI_RECIPIENT_CON);
1979 		ucsi_unregister_port_psy(con);
1980 
1981 		usb_power_delivery_unregister_capabilities(con->port_sink_caps);
1982 		con->port_sink_caps = NULL;
1983 		usb_power_delivery_unregister_capabilities(con->port_source_caps);
1984 		con->port_source_caps = NULL;
1985 		usb_power_delivery_unregister(con->pd);
1986 		con->pd = NULL;
1987 		typec_unregister_port(con->port);
1988 		con->port = NULL;
1989 	}
1990 	kfree(connector);
1991 err_reset:
1992 	memset(&ucsi->cap, 0, sizeof(ucsi->cap));
1993 	ucsi_reset_ppm(ucsi);
1994 err:
1995 	return ret;
1996 }
1997 
1998 static void ucsi_resume_work(struct work_struct *work)
1999 {
2000 	struct ucsi *ucsi = container_of(work, struct ucsi, resume_work);
2001 	struct ucsi_connector *con;
2002 	u64 command;
2003 	int ret;
2004 
2005 	/* Restore UCSI notification enable mask after system resume */
2006 	command = UCSI_SET_NOTIFICATION_ENABLE | ucsi->ntfy;
2007 	ret = ucsi_send_command(ucsi, command, NULL, 0);
2008 	if (ret < 0) {
2009 		dev_err(ucsi->dev, "failed to re-enable notifications (%d)\n", ret);
2010 		return;
2011 	}
2012 
2013 	for (con = ucsi->connector; con->port; con++) {
2014 		mutex_lock(&con->lock);
2015 		ucsi_partner_task(con, ucsi_check_connection, 1, 0);
2016 		mutex_unlock(&con->lock);
2017 	}
2018 }
2019 
2020 int ucsi_resume(struct ucsi *ucsi)
2021 {
2022 	if (ucsi->connector)
2023 		queue_work(system_long_wq, &ucsi->resume_work);
2024 	return 0;
2025 }
2026 EXPORT_SYMBOL_GPL(ucsi_resume);
2027 
2028 static void ucsi_init_work(struct work_struct *work)
2029 {
2030 	struct ucsi *ucsi = container_of(work, struct ucsi, work.work);
2031 	int ret;
2032 
2033 	ret = ucsi_init(ucsi);
2034 	if (ret)
2035 		dev_err_probe(ucsi->dev, ret, "PPM init failed\n");
2036 
2037 	if (ret == -EPROBE_DEFER) {
2038 		if (ucsi->work_count++ > UCSI_ROLE_SWITCH_WAIT_COUNT) {
2039 			dev_err(ucsi->dev, "PPM init failed, stop trying\n");
2040 			return;
2041 		}
2042 
2043 		queue_delayed_work(system_long_wq, &ucsi->work,
2044 				   UCSI_ROLE_SWITCH_INTERVAL);
2045 	}
2046 }
2047 
2048 /**
2049  * ucsi_get_drvdata - Return private driver data pointer
2050  * @ucsi: UCSI interface
2051  */
2052 void *ucsi_get_drvdata(struct ucsi *ucsi)
2053 {
2054 	return ucsi->driver_data;
2055 }
2056 EXPORT_SYMBOL_GPL(ucsi_get_drvdata);
2057 
2058 /**
2059  * ucsi_set_drvdata - Assign private driver data pointer
2060  * @ucsi: UCSI interface
2061  * @data: Private data pointer
2062  */
2063 void ucsi_set_drvdata(struct ucsi *ucsi, void *data)
2064 {
2065 	ucsi->driver_data = data;
2066 }
2067 EXPORT_SYMBOL_GPL(ucsi_set_drvdata);
2068 
2069 /**
2070  * ucsi_con_mutex_lock - Acquire the connector mutex
2071  * @con: The connector interface to lock
2072  *
2073  * Returns true on success, false if the connector is disconnected
2074  */
2075 bool ucsi_con_mutex_lock(struct ucsi_connector *con)
2076 {
2077 	bool mutex_locked = false;
2078 	bool connected = true;
2079 
2080 	while (connected && !mutex_locked) {
2081 		mutex_locked = mutex_trylock(&con->lock) != 0;
2082 		connected = UCSI_CONSTAT(con, CONNECTED);
2083 		if (connected && !mutex_locked)
2084 			msleep(20);
2085 	}
2086 
2087 	connected = connected && con->partner;
2088 	if (!connected && mutex_locked)
2089 		mutex_unlock(&con->lock);
2090 
2091 	return connected;
2092 }
2093 
2094 /**
2095  * ucsi_con_mutex_unlock - Release the connector mutex
2096  * @con: The connector interface to unlock
2097  */
2098 void ucsi_con_mutex_unlock(struct ucsi_connector *con)
2099 {
2100 	mutex_unlock(&con->lock);
2101 }
2102 
2103 /**
2104  * ucsi_create - Allocate UCSI instance
2105  * @dev: Device interface to the PPM (Platform Policy Manager)
2106  * @ops: I/O routines
2107  */
2108 struct ucsi *ucsi_create(struct device *dev, const struct ucsi_operations *ops)
2109 {
2110 	struct ucsi *ucsi;
2111 
2112 	if (!ops ||
2113 	    !ops->read_version || !ops->read_cci || !ops->poll_cci ||
2114 	    !ops->read_message_in || !ops->sync_control || !ops->async_control)
2115 		return ERR_PTR(-EINVAL);
2116 
2117 	ucsi = kzalloc_obj(*ucsi);
2118 	if (!ucsi)
2119 		return ERR_PTR(-ENOMEM);
2120 
2121 	INIT_WORK(&ucsi->resume_work, ucsi_resume_work);
2122 	INIT_DELAYED_WORK(&ucsi->work, ucsi_init_work);
2123 	mutex_init(&ucsi->ppm_lock);
2124 	init_completion(&ucsi->complete);
2125 	ucsi->dev = dev;
2126 	ucsi->ops = ops;
2127 
2128 	return ucsi;
2129 }
2130 EXPORT_SYMBOL_GPL(ucsi_create);
2131 
2132 /**
2133  * ucsi_destroy - Free UCSI instance
2134  * @ucsi: UCSI instance to be freed
2135  */
2136 void ucsi_destroy(struct ucsi *ucsi)
2137 {
2138 	ucsi_debugfs_unregister(ucsi);
2139 	kfree(ucsi);
2140 }
2141 EXPORT_SYMBOL_GPL(ucsi_destroy);
2142 
2143 /**
2144  * ucsi_register - Register UCSI interface
2145  * @ucsi: UCSI instance
2146  */
2147 int ucsi_register(struct ucsi *ucsi)
2148 {
2149 	int ret;
2150 
2151 	ret = ucsi->ops->read_version(ucsi, &ucsi->version);
2152 	if (ret)
2153 		return ret;
2154 
2155 	if (!ucsi->version)
2156 		return -ENODEV;
2157 
2158 	/*
2159 	 * Version format is JJ.M.N (JJ = Major version, M = Minor version,
2160 	 * N = sub-minor version).
2161 	 */
2162 	dev_dbg(ucsi->dev, "Registered UCSI interface with version %x.%x.%x",
2163 		UCSI_BCD_GET_MAJOR(ucsi->version),
2164 		UCSI_BCD_GET_MINOR(ucsi->version),
2165 		UCSI_BCD_GET_SUBMINOR(ucsi->version));
2166 
2167 	queue_delayed_work(system_long_wq, &ucsi->work, 0);
2168 
2169 	ucsi_debugfs_register(ucsi);
2170 	return 0;
2171 }
2172 EXPORT_SYMBOL_GPL(ucsi_register);
2173 
2174 /**
2175  * ucsi_unregister - Unregister UCSI interface
2176  * @ucsi: UCSI interface to be unregistered
2177  *
2178  * Unregister UCSI interface that was created with ucsi_register().
2179  */
2180 void ucsi_unregister(struct ucsi *ucsi)
2181 {
2182 	u64 cmd = UCSI_SET_NOTIFICATION_ENABLE;
2183 	int i;
2184 
2185 	/* Make sure that we are not in the middle of driver initialization */
2186 	cancel_delayed_work_sync(&ucsi->work);
2187 	cancel_work_sync(&ucsi->resume_work);
2188 
2189 	/* Disable notifications */
2190 	ucsi->ops->async_control(ucsi, cmd);
2191 
2192 	if (!ucsi->connector)
2193 		return;
2194 
2195 	for (i = 0; i < ucsi->cap.num_connectors; i++) {
2196 		cancel_work_sync(&ucsi->connector[i].work);
2197 
2198 		if (ucsi->connector[i].wq) {
2199 			struct ucsi_work *uwork;
2200 
2201 			mutex_lock(&ucsi->connector[i].lock);
2202 			/*
2203 			 * queue delayed items immediately so they can execute
2204 			 * and free themselves before the wq is destroyed
2205 			 */
2206 			list_for_each_entry(uwork, &ucsi->connector[i].partner_tasks, node)
2207 				mod_delayed_work(ucsi->connector[i].wq, &uwork->work, 0);
2208 			mutex_unlock(&ucsi->connector[i].lock);
2209 			destroy_workqueue(ucsi->connector[i].wq);
2210 		}
2211 
2212 		ucsi_unregister_partner(&ucsi->connector[i]);
2213 		ucsi_unregister_altmodes(&ucsi->connector[i],
2214 					 UCSI_RECIPIENT_CON);
2215 		ucsi_unregister_port_psy(&ucsi->connector[i]);
2216 
2217 		usb_power_delivery_unregister_capabilities(ucsi->connector[i].port_sink_caps);
2218 		ucsi->connector[i].port_sink_caps = NULL;
2219 		usb_power_delivery_unregister_capabilities(ucsi->connector[i].port_source_caps);
2220 		ucsi->connector[i].port_source_caps = NULL;
2221 		usb_power_delivery_unregister(ucsi->connector[i].pd);
2222 		ucsi->connector[i].pd = NULL;
2223 		typec_unregister_port(ucsi->connector[i].port);
2224 		lockdep_unregister_key(&ucsi->connector[i].lock_key);
2225 	}
2226 
2227 	kfree(ucsi->connector);
2228 }
2229 EXPORT_SYMBOL_GPL(ucsi_unregister);
2230 
2231 static int __init ucsi_module_init(void)
2232 {
2233 	ucsi_debugfs_init();
2234 	return 0;
2235 }
2236 module_init(ucsi_module_init);
2237 
2238 static void __exit ucsi_module_exit(void)
2239 {
2240 	ucsi_debugfs_exit();
2241 }
2242 module_exit(ucsi_module_exit);
2243 
2244 MODULE_AUTHOR("Heikki Krogerus <heikki.krogerus@linux.intel.com>");
2245 MODULE_LICENSE("GPL v2");
2246 MODULE_DESCRIPTION("USB Type-C Connector System Software Interface driver");
2247