1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Thunderbolt driver - bus logic (NHI independent)
4  *
5  * Copyright (c) 2014 Andreas Noever <andreas.noever@gmail.com>
6  * Copyright (C) 2019, Intel Corporation
7  */
8 
9 #include <linux/slab.h>
10 #include <linux/errno.h>
11 #include <linux/delay.h>
12 #include <linux/pm_runtime.h>
13 #include <linux/platform_data/x86/apple.h>
14 
15 #include "tb.h"
16 #include "tb_regs.h"
17 #include "tunnel.h"
18 
19 #define TB_TIMEOUT		100	/* ms */
20 #define TB_RELEASE_BW_TIMEOUT	10000	/* ms */
21 
22 /*
23  * How many time bandwidth allocation request from graphics driver is
24  * retried if the DP tunnel is still activating.
25  */
26 #define TB_BW_ALLOC_RETRIES	3
27 
28 /*
29  * Minimum bandwidth (in Mb/s) that is needed in the single transmitter/receiver
30  * direction. This is 40G - 10% guard band bandwidth.
31  */
32 #define TB_ASYM_MIN		(40000 * 90 / 100)
33 
34 /*
35  * Threshold bandwidth (in Mb/s) that is used to switch the links to
36  * asymmetric and back. This is selected as 45G which means when the
37  * request is higher than this, we switch the link to asymmetric, and
38  * when it is less than this we switch it back. The 45G is selected so
39  * that we still have 27G (of the total 72G) for bulk PCIe traffic when
40  * switching back to symmetric.
41  */
42 #define TB_ASYM_THRESHOLD	45000
43 
44 #define MAX_GROUPS		7	/* max Group_ID is 7 */
45 
46 static unsigned int asym_threshold = TB_ASYM_THRESHOLD;
47 module_param_named(asym_threshold, asym_threshold, uint, 0444);
48 MODULE_PARM_DESC(asym_threshold,
49 		"threshold (Mb/s) when to Gen 4 switch link symmetry. 0 disables. (default: "
50 		__MODULE_STRING(TB_ASYM_THRESHOLD) ")");
51 
52 /**
53  * struct tb_cm - Simple Thunderbolt connection manager
54  * @tunnel_list: List of active tunnels
55  * @dp_resources: List of available DP resources for DP tunneling
56  * @hotplug_active: tb_handle_hotplug will stop progressing plug
57  *		    events and exit if this is not set (it needs to
58  *		    acquire the lock one more time). Used to drain wq
59  *		    after cfg has been paused.
60  * @remove_work: Work used to remove any unplugged routers after
61  *		 runtime resume
62  * @groups: Bandwidth groups used in this domain.
63  */
64 struct tb_cm {
65 	struct list_head tunnel_list;
66 	struct list_head dp_resources;
67 	bool hotplug_active;
68 	struct delayed_work remove_work;
69 	struct tb_bandwidth_group groups[MAX_GROUPS];
70 };
71 
tcm_to_tb(struct tb_cm * tcm)72 static inline struct tb *tcm_to_tb(struct tb_cm *tcm)
73 {
74 	return ((void *)tcm - sizeof(struct tb));
75 }
76 
77 struct tb_hotplug_event {
78 	struct delayed_work work;
79 	struct tb *tb;
80 	u64 route;
81 	u8 port;
82 	bool unplug;
83 	int retry;
84 };
85 
86 static void tb_scan_port(struct tb_port *port);
87 static void tb_handle_hotplug(struct work_struct *work);
88 static void tb_dp_resource_unavailable(struct tb *tb, struct tb_port *port,
89 				       const char *reason);
90 static void tb_queue_dp_bandwidth_request(struct tb *tb, u64 route, u8 port,
91 					  int retry, unsigned long delay);
92 
tb_queue_hotplug(struct tb * tb,u64 route,u8 port,bool unplug)93 static void tb_queue_hotplug(struct tb *tb, u64 route, u8 port, bool unplug)
94 {
95 	struct tb_hotplug_event *ev;
96 
97 	ev = kmalloc(sizeof(*ev), GFP_KERNEL);
98 	if (!ev)
99 		return;
100 
101 	ev->tb = tb;
102 	ev->route = route;
103 	ev->port = port;
104 	ev->unplug = unplug;
105 	INIT_DELAYED_WORK(&ev->work, tb_handle_hotplug);
106 	queue_delayed_work(tb->wq, &ev->work, 0);
107 }
108 
109 /* enumeration & hot plug handling */
110 
tb_add_dp_resources(struct tb_switch * sw)111 static void tb_add_dp_resources(struct tb_switch *sw)
112 {
113 	struct tb_cm *tcm = tb_priv(sw->tb);
114 	struct tb_port *port;
115 
116 	tb_switch_for_each_port(sw, port) {
117 		if (!tb_port_is_dpin(port))
118 			continue;
119 
120 		if (!tb_switch_query_dp_resource(sw, port))
121 			continue;
122 
123 		/*
124 		 * If DP IN on device router exist, position it at the
125 		 * beginning of the DP resources list, so that it is used
126 		 * before DP IN of the host router. This way external GPU(s)
127 		 * will be prioritized when pairing DP IN to a DP OUT.
128 		 */
129 		if (tb_route(sw))
130 			list_add(&port->list, &tcm->dp_resources);
131 		else
132 			list_add_tail(&port->list, &tcm->dp_resources);
133 
134 		tb_port_dbg(port, "DP IN resource available\n");
135 	}
136 }
137 
tb_remove_dp_resources(struct tb_switch * sw)138 static void tb_remove_dp_resources(struct tb_switch *sw)
139 {
140 	struct tb_cm *tcm = tb_priv(sw->tb);
141 	struct tb_port *port, *tmp;
142 
143 	/* Clear children resources first */
144 	tb_switch_for_each_port(sw, port) {
145 		if (tb_port_has_remote(port))
146 			tb_remove_dp_resources(port->remote->sw);
147 	}
148 
149 	list_for_each_entry_safe(port, tmp, &tcm->dp_resources, list) {
150 		if (port->sw == sw) {
151 			tb_port_dbg(port, "DP OUT resource unavailable\n");
152 			list_del_init(&port->list);
153 		}
154 	}
155 }
156 
tb_discover_dp_resource(struct tb * tb,struct tb_port * port)157 static void tb_discover_dp_resource(struct tb *tb, struct tb_port *port)
158 {
159 	struct tb_cm *tcm = tb_priv(tb);
160 	struct tb_port *p;
161 
162 	list_for_each_entry(p, &tcm->dp_resources, list) {
163 		if (p == port)
164 			return;
165 	}
166 
167 	tb_port_dbg(port, "DP %s resource available discovered\n",
168 		    tb_port_is_dpin(port) ? "IN" : "OUT");
169 	list_add_tail(&port->list, &tcm->dp_resources);
170 }
171 
tb_discover_dp_resources(struct tb * tb)172 static void tb_discover_dp_resources(struct tb *tb)
173 {
174 	struct tb_cm *tcm = tb_priv(tb);
175 	struct tb_tunnel *tunnel;
176 
177 	list_for_each_entry(tunnel, &tcm->tunnel_list, list) {
178 		if (tb_tunnel_is_dp(tunnel))
179 			tb_discover_dp_resource(tb, tunnel->dst_port);
180 	}
181 }
182 
183 /* Enables CL states up to host router */
tb_enable_clx(struct tb_switch * sw)184 static int tb_enable_clx(struct tb_switch *sw)
185 {
186 	struct tb_cm *tcm = tb_priv(sw->tb);
187 	unsigned int clx = TB_CL0S | TB_CL1;
188 	const struct tb_tunnel *tunnel;
189 	int ret;
190 
191 	/*
192 	 * Currently only enable CLx for the first link. This is enough
193 	 * to allow the CPU to save energy at least on Intel hardware
194 	 * and makes it slightly simpler to implement. We may change
195 	 * this in the future to cover the whole topology if it turns
196 	 * out to be beneficial.
197 	 */
198 	while (sw && tb_switch_depth(sw) > 1)
199 		sw = tb_switch_parent(sw);
200 
201 	if (!sw)
202 		return 0;
203 
204 	if (tb_switch_depth(sw) != 1)
205 		return 0;
206 
207 	/*
208 	 * If we are re-enabling then check if there is an active DMA
209 	 * tunnel and in that case bail out.
210 	 */
211 	list_for_each_entry(tunnel, &tcm->tunnel_list, list) {
212 		if (tb_tunnel_is_dma(tunnel)) {
213 			if (tb_tunnel_port_on_path(tunnel, tb_upstream_port(sw)))
214 				return 0;
215 		}
216 	}
217 
218 	/*
219 	 * Initially try with CL2. If that's not supported by the
220 	 * topology try with CL0s and CL1 and then give up.
221 	 */
222 	ret = tb_switch_clx_enable(sw, clx | TB_CL2);
223 	if (ret == -EOPNOTSUPP)
224 		ret = tb_switch_clx_enable(sw, clx);
225 	return ret == -EOPNOTSUPP ? 0 : ret;
226 }
227 
228 /**
229  * tb_disable_clx() - Disable CL states up to host router
230  * @sw: Router to start
231  *
232  * Disables CL states from @sw up to the host router. Returns true if
233  * any CL state were disabled. This can be used to figure out whether
234  * the link was setup by us or the boot firmware so we don't
235  * accidentally enable them if they were not enabled during discovery.
236  */
tb_disable_clx(struct tb_switch * sw)237 static bool tb_disable_clx(struct tb_switch *sw)
238 {
239 	bool disabled = false;
240 
241 	do {
242 		int ret;
243 
244 		ret = tb_switch_clx_disable(sw);
245 		if (ret > 0)
246 			disabled = true;
247 		else if (ret < 0)
248 			tb_sw_warn(sw, "failed to disable CL states\n");
249 
250 		sw = tb_switch_parent(sw);
251 	} while (sw);
252 
253 	return disabled;
254 }
255 
tb_increase_switch_tmu_accuracy(struct device * dev,void * data)256 static int tb_increase_switch_tmu_accuracy(struct device *dev, void *data)
257 {
258 	struct tb_switch *sw;
259 
260 	sw = tb_to_switch(dev);
261 	if (!sw)
262 		return 0;
263 
264 	if (tb_switch_tmu_is_configured(sw, TB_SWITCH_TMU_MODE_LOWRES)) {
265 		enum tb_switch_tmu_mode mode;
266 		int ret;
267 
268 		if (tb_switch_clx_is_enabled(sw, TB_CL1))
269 			mode = TB_SWITCH_TMU_MODE_HIFI_UNI;
270 		else
271 			mode = TB_SWITCH_TMU_MODE_HIFI_BI;
272 
273 		ret = tb_switch_tmu_configure(sw, mode);
274 		if (ret)
275 			return ret;
276 
277 		return tb_switch_tmu_enable(sw);
278 	}
279 
280 	return 0;
281 }
282 
tb_increase_tmu_accuracy(struct tb_tunnel * tunnel)283 static void tb_increase_tmu_accuracy(struct tb_tunnel *tunnel)
284 {
285 	struct tb_switch *sw;
286 
287 	if (!tunnel)
288 		return;
289 
290 	/*
291 	 * Once first DP tunnel is established we change the TMU
292 	 * accuracy of first depth child routers (and the host router)
293 	 * to the highest. This is needed for the DP tunneling to work
294 	 * but also allows CL0s.
295 	 *
296 	 * If both routers are v2 then we don't need to do anything as
297 	 * they are using enhanced TMU mode that allows all CLx.
298 	 */
299 	sw = tunnel->tb->root_switch;
300 	device_for_each_child(&sw->dev, NULL, tb_increase_switch_tmu_accuracy);
301 }
302 
tb_switch_tmu_hifi_uni_required(struct device * dev,void * not_used)303 static int tb_switch_tmu_hifi_uni_required(struct device *dev, void *not_used)
304 {
305 	struct tb_switch *sw = tb_to_switch(dev);
306 
307 	if (sw && tb_switch_tmu_is_enabled(sw) &&
308 	    tb_switch_tmu_is_configured(sw, TB_SWITCH_TMU_MODE_HIFI_UNI))
309 		return 1;
310 
311 	return device_for_each_child(dev, NULL,
312 				     tb_switch_tmu_hifi_uni_required);
313 }
314 
tb_tmu_hifi_uni_required(struct tb * tb)315 static bool tb_tmu_hifi_uni_required(struct tb *tb)
316 {
317 	return device_for_each_child(&tb->dev, NULL,
318 				     tb_switch_tmu_hifi_uni_required) == 1;
319 }
320 
tb_enable_tmu(struct tb_switch * sw)321 static int tb_enable_tmu(struct tb_switch *sw)
322 {
323 	int ret;
324 
325 	/*
326 	 * If both routers at the end of the link are v2 we simply
327 	 * enable the enhanched uni-directional mode. That covers all
328 	 * the CL states. For v1 and before we need to use the normal
329 	 * rate to allow CL1 (when supported). Otherwise we keep the TMU
330 	 * running at the highest accuracy.
331 	 */
332 	ret = tb_switch_tmu_configure(sw,
333 			TB_SWITCH_TMU_MODE_MEDRES_ENHANCED_UNI);
334 	if (ret == -EOPNOTSUPP) {
335 		if (tb_switch_clx_is_enabled(sw, TB_CL1)) {
336 			/*
337 			 * Figure out uni-directional HiFi TMU requirements
338 			 * currently in the domain. If there are no
339 			 * uni-directional HiFi requirements we can put the TMU
340 			 * into LowRes mode.
341 			 *
342 			 * Deliberately skip bi-directional HiFi links
343 			 * as these work independently of other links
344 			 * (and they do not allow any CL states anyway).
345 			 */
346 			if (tb_tmu_hifi_uni_required(sw->tb))
347 				ret = tb_switch_tmu_configure(sw,
348 						TB_SWITCH_TMU_MODE_HIFI_UNI);
349 			else
350 				ret = tb_switch_tmu_configure(sw,
351 						TB_SWITCH_TMU_MODE_LOWRES);
352 		} else {
353 			ret = tb_switch_tmu_configure(sw, TB_SWITCH_TMU_MODE_HIFI_BI);
354 		}
355 
356 		/* If not supported, fallback to bi-directional HiFi */
357 		if (ret == -EOPNOTSUPP)
358 			ret = tb_switch_tmu_configure(sw, TB_SWITCH_TMU_MODE_HIFI_BI);
359 	}
360 	if (ret)
361 		return ret;
362 
363 	/* If it is already enabled in correct mode, don't touch it */
364 	if (tb_switch_tmu_is_enabled(sw))
365 		return 0;
366 
367 	ret = tb_switch_tmu_disable(sw);
368 	if (ret)
369 		return ret;
370 
371 	ret = tb_switch_tmu_post_time(sw);
372 	if (ret)
373 		return ret;
374 
375 	return tb_switch_tmu_enable(sw);
376 }
377 
tb_switch_discover_tunnels(struct tb_switch * sw,struct list_head * list,bool alloc_hopids)378 static void tb_switch_discover_tunnels(struct tb_switch *sw,
379 				       struct list_head *list,
380 				       bool alloc_hopids)
381 {
382 	struct tb *tb = sw->tb;
383 	struct tb_port *port;
384 
385 	tb_switch_for_each_port(sw, port) {
386 		struct tb_tunnel *tunnel = NULL;
387 
388 		switch (port->config.type) {
389 		case TB_TYPE_DP_HDMI_IN:
390 			tunnel = tb_tunnel_discover_dp(tb, port, alloc_hopids);
391 			tb_increase_tmu_accuracy(tunnel);
392 			break;
393 
394 		case TB_TYPE_PCIE_DOWN:
395 			tunnel = tb_tunnel_discover_pci(tb, port, alloc_hopids);
396 			break;
397 
398 		case TB_TYPE_USB3_DOWN:
399 			tunnel = tb_tunnel_discover_usb3(tb, port, alloc_hopids);
400 			break;
401 
402 		default:
403 			break;
404 		}
405 
406 		if (tunnel)
407 			list_add_tail(&tunnel->list, list);
408 	}
409 
410 	tb_switch_for_each_port(sw, port) {
411 		if (tb_port_has_remote(port)) {
412 			tb_switch_discover_tunnels(port->remote->sw, list,
413 						   alloc_hopids);
414 		}
415 	}
416 }
417 
tb_port_configure_xdomain(struct tb_port * port,struct tb_xdomain * xd)418 static int tb_port_configure_xdomain(struct tb_port *port, struct tb_xdomain *xd)
419 {
420 	if (tb_switch_is_usb4(port->sw))
421 		return usb4_port_configure_xdomain(port, xd);
422 	return tb_lc_configure_xdomain(port);
423 }
424 
tb_port_unconfigure_xdomain(struct tb_port * port)425 static void tb_port_unconfigure_xdomain(struct tb_port *port)
426 {
427 	if (tb_switch_is_usb4(port->sw))
428 		usb4_port_unconfigure_xdomain(port);
429 	else
430 		tb_lc_unconfigure_xdomain(port);
431 }
432 
tb_scan_xdomain(struct tb_port * port)433 static void tb_scan_xdomain(struct tb_port *port)
434 {
435 	struct tb_switch *sw = port->sw;
436 	struct tb *tb = sw->tb;
437 	struct tb_xdomain *xd;
438 	u64 route;
439 
440 	if (!tb_is_xdomain_enabled())
441 		return;
442 
443 	route = tb_downstream_route(port);
444 	xd = tb_xdomain_find_by_route(tb, route);
445 	if (xd) {
446 		tb_xdomain_put(xd);
447 		return;
448 	}
449 
450 	xd = tb_xdomain_alloc(tb, &sw->dev, route, tb->root_switch->uuid,
451 			      NULL);
452 	if (xd) {
453 		tb_port_at(route, sw)->xdomain = xd;
454 		tb_port_configure_xdomain(port, xd);
455 		tb_xdomain_add(xd);
456 	}
457 }
458 
459 /**
460  * tb_find_unused_port() - return the first inactive port on @sw
461  * @sw: Switch to find the port on
462  * @type: Port type to look for
463  */
tb_find_unused_port(struct tb_switch * sw,enum tb_port_type type)464 static struct tb_port *tb_find_unused_port(struct tb_switch *sw,
465 					   enum tb_port_type type)
466 {
467 	struct tb_port *port;
468 
469 	tb_switch_for_each_port(sw, port) {
470 		if (tb_is_upstream_port(port))
471 			continue;
472 		if (port->config.type != type)
473 			continue;
474 		if (!port->cap_adap)
475 			continue;
476 		if (tb_port_is_enabled(port))
477 			continue;
478 		return port;
479 	}
480 	return NULL;
481 }
482 
tb_find_usb3_down(struct tb_switch * sw,const struct tb_port * port)483 static struct tb_port *tb_find_usb3_down(struct tb_switch *sw,
484 					 const struct tb_port *port)
485 {
486 	struct tb_port *down;
487 
488 	down = usb4_switch_map_usb3_down(sw, port);
489 	if (down && !tb_usb3_port_is_enabled(down))
490 		return down;
491 	return NULL;
492 }
493 
tb_find_tunnel(struct tb * tb,enum tb_tunnel_type type,struct tb_port * src_port,struct tb_port * dst_port)494 static struct tb_tunnel *tb_find_tunnel(struct tb *tb, enum tb_tunnel_type type,
495 					struct tb_port *src_port,
496 					struct tb_port *dst_port)
497 {
498 	struct tb_cm *tcm = tb_priv(tb);
499 	struct tb_tunnel *tunnel;
500 
501 	list_for_each_entry(tunnel, &tcm->tunnel_list, list) {
502 		if (tunnel->type == type &&
503 		    ((src_port && src_port == tunnel->src_port) ||
504 		     (dst_port && dst_port == tunnel->dst_port))) {
505 			return tunnel;
506 		}
507 	}
508 
509 	return NULL;
510 }
511 
tb_find_first_usb3_tunnel(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port)512 static struct tb_tunnel *tb_find_first_usb3_tunnel(struct tb *tb,
513 						   struct tb_port *src_port,
514 						   struct tb_port *dst_port)
515 {
516 	struct tb_port *port, *usb3_down;
517 	struct tb_switch *sw;
518 
519 	/* Pick the router that is deepest in the topology */
520 	if (tb_port_path_direction_downstream(src_port, dst_port))
521 		sw = dst_port->sw;
522 	else
523 		sw = src_port->sw;
524 
525 	/* Can't be the host router */
526 	if (sw == tb->root_switch)
527 		return NULL;
528 
529 	/* Find the downstream USB4 port that leads to this router */
530 	port = tb_port_at(tb_route(sw), tb->root_switch);
531 	/* Find the corresponding host router USB3 downstream port */
532 	usb3_down = usb4_switch_map_usb3_down(tb->root_switch, port);
533 	if (!usb3_down)
534 		return NULL;
535 
536 	return tb_find_tunnel(tb, TB_TUNNEL_USB3, usb3_down, NULL);
537 }
538 
539 /**
540  * tb_consumed_usb3_pcie_bandwidth() - Consumed USB3/PCIe bandwidth over a single link
541  * @tb: Domain structure
542  * @src_port: Source protocol adapter
543  * @dst_port: Destination protocol adapter
544  * @port: USB4 port the consumed bandwidth is calculated
545  * @consumed_up: Consumed upsream bandwidth (Mb/s)
546  * @consumed_down: Consumed downstream bandwidth (Mb/s)
547  *
548  * Calculates consumed USB3 and PCIe bandwidth at @port between path
549  * from @src_port to @dst_port. Does not take USB3 tunnel starting from
550  * @src_port and ending on @src_port into account because that bandwidth is
551  * already included in as part of the "first hop" USB3 tunnel.
552  */
tb_consumed_usb3_pcie_bandwidth(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port,struct tb_port * port,int * consumed_up,int * consumed_down)553 static int tb_consumed_usb3_pcie_bandwidth(struct tb *tb,
554 					   struct tb_port *src_port,
555 					   struct tb_port *dst_port,
556 					   struct tb_port *port,
557 					   int *consumed_up,
558 					   int *consumed_down)
559 {
560 	int pci_consumed_up, pci_consumed_down;
561 	struct tb_tunnel *tunnel;
562 
563 	*consumed_up = *consumed_down = 0;
564 
565 	tunnel = tb_find_first_usb3_tunnel(tb, src_port, dst_port);
566 	if (tunnel && !tb_port_is_usb3_down(src_port) &&
567 	    !tb_port_is_usb3_up(dst_port)) {
568 		int ret;
569 
570 		ret = tb_tunnel_consumed_bandwidth(tunnel, consumed_up,
571 						   consumed_down);
572 		if (ret)
573 			return ret;
574 	}
575 
576 	/*
577 	 * If there is anything reserved for PCIe bulk traffic take it
578 	 * into account here too.
579 	 */
580 	if (tb_tunnel_reserved_pci(port, &pci_consumed_up, &pci_consumed_down)) {
581 		*consumed_up += pci_consumed_up;
582 		*consumed_down += pci_consumed_down;
583 	}
584 
585 	return 0;
586 }
587 
588 /**
589  * tb_consumed_dp_bandwidth() - Consumed DP bandwidth over a single link
590  * @tb: Domain structure
591  * @src_port: Source protocol adapter
592  * @dst_port: Destination protocol adapter
593  * @port: USB4 port the consumed bandwidth is calculated
594  * @consumed_up: Consumed upsream bandwidth (Mb/s)
595  * @consumed_down: Consumed downstream bandwidth (Mb/s)
596  *
597  * Calculates consumed DP bandwidth at @port between path from @src_port
598  * to @dst_port. Does not take tunnel starting from @src_port and ending
599  * from @src_port into account.
600  *
601  * If there is bandwidth reserved for any of the groups between
602  * @src_port and @dst_port (but not yet used) that is also taken into
603  * account in the returned consumed bandwidth.
604  */
tb_consumed_dp_bandwidth(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port,struct tb_port * port,int * consumed_up,int * consumed_down)605 static int tb_consumed_dp_bandwidth(struct tb *tb,
606 				    struct tb_port *src_port,
607 				    struct tb_port *dst_port,
608 				    struct tb_port *port,
609 				    int *consumed_up,
610 				    int *consumed_down)
611 {
612 	int group_reserved[MAX_GROUPS] = {};
613 	struct tb_cm *tcm = tb_priv(tb);
614 	struct tb_tunnel *tunnel;
615 	bool downstream;
616 	int i, ret;
617 
618 	*consumed_up = *consumed_down = 0;
619 
620 	/*
621 	 * Find all DP tunnels that cross the port and reduce
622 	 * their consumed bandwidth from the available.
623 	 */
624 	list_for_each_entry(tunnel, &tcm->tunnel_list, list) {
625 		const struct tb_bandwidth_group *group;
626 		int dp_consumed_up, dp_consumed_down;
627 
628 		if (tb_tunnel_is_invalid(tunnel))
629 			continue;
630 
631 		if (!tb_tunnel_is_dp(tunnel))
632 			continue;
633 
634 		if (!tb_tunnel_port_on_path(tunnel, port))
635 			continue;
636 
637 		/*
638 		 * Calculate what is reserved for groups crossing the
639 		 * same ports only once (as that is reserved for all the
640 		 * tunnels in the group).
641 		 */
642 		group = tunnel->src_port->group;
643 		if (group && group->reserved && !group_reserved[group->index])
644 			group_reserved[group->index] = group->reserved;
645 
646 		/*
647 		 * Ignore the DP tunnel between src_port and dst_port
648 		 * because it is the same tunnel and we may be
649 		 * re-calculating estimated bandwidth.
650 		 */
651 		if (tunnel->src_port == src_port &&
652 		    tunnel->dst_port == dst_port)
653 			continue;
654 
655 		ret = tb_tunnel_consumed_bandwidth(tunnel, &dp_consumed_up,
656 						   &dp_consumed_down);
657 		if (ret)
658 			return ret;
659 
660 		*consumed_up += dp_consumed_up;
661 		*consumed_down += dp_consumed_down;
662 	}
663 
664 	downstream = tb_port_path_direction_downstream(src_port, dst_port);
665 	for (i = 0; i < ARRAY_SIZE(group_reserved); i++) {
666 		if (downstream)
667 			*consumed_down += group_reserved[i];
668 		else
669 			*consumed_up += group_reserved[i];
670 	}
671 
672 	return 0;
673 }
674 
tb_asym_supported(struct tb_port * src_port,struct tb_port * dst_port,struct tb_port * port)675 static bool tb_asym_supported(struct tb_port *src_port, struct tb_port *dst_port,
676 			      struct tb_port *port)
677 {
678 	bool downstream = tb_port_path_direction_downstream(src_port, dst_port);
679 	enum tb_link_width width;
680 
681 	if (tb_is_upstream_port(port))
682 		width = downstream ? TB_LINK_WIDTH_ASYM_RX : TB_LINK_WIDTH_ASYM_TX;
683 	else
684 		width = downstream ? TB_LINK_WIDTH_ASYM_TX : TB_LINK_WIDTH_ASYM_RX;
685 
686 	return tb_port_width_supported(port, width);
687 }
688 
689 /**
690  * tb_maximum_bandwidth() - Maximum bandwidth over a single link
691  * @tb: Domain structure
692  * @src_port: Source protocol adapter
693  * @dst_port: Destination protocol adapter
694  * @port: USB4 port the total bandwidth is calculated
695  * @max_up: Maximum upstream bandwidth (Mb/s)
696  * @max_down: Maximum downstream bandwidth (Mb/s)
697  * @include_asym: Include bandwidth if the link is switched from
698  *		  symmetric to asymmetric
699  *
700  * Returns maximum possible bandwidth in @max_up and @max_down over a
701  * single link at @port. If @include_asym is set then includes the
702  * additional banwdith if the links are transitioned into asymmetric to
703  * direction from @src_port to @dst_port.
704  */
tb_maximum_bandwidth(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port,struct tb_port * port,int * max_up,int * max_down,bool include_asym)705 static int tb_maximum_bandwidth(struct tb *tb, struct tb_port *src_port,
706 				struct tb_port *dst_port, struct tb_port *port,
707 				int *max_up, int *max_down, bool include_asym)
708 {
709 	bool downstream = tb_port_path_direction_downstream(src_port, dst_port);
710 	int link_speed, link_width, up_bw, down_bw;
711 
712 	/*
713 	 * Can include asymmetric, only if it is actually supported by
714 	 * the lane adapter.
715 	 */
716 	if (!tb_asym_supported(src_port, dst_port, port))
717 		include_asym = false;
718 
719 	if (tb_is_upstream_port(port)) {
720 		link_speed = port->sw->link_speed;
721 		/*
722 		 * sw->link_width is from upstream perspective so we use
723 		 * the opposite for downstream of the host router.
724 		 */
725 		if (port->sw->link_width == TB_LINK_WIDTH_ASYM_TX) {
726 			up_bw = link_speed * 3 * 1000;
727 			down_bw = link_speed * 1 * 1000;
728 		} else if (port->sw->link_width == TB_LINK_WIDTH_ASYM_RX) {
729 			up_bw = link_speed * 1 * 1000;
730 			down_bw = link_speed * 3 * 1000;
731 		} else if (include_asym) {
732 			/*
733 			 * The link is symmetric at the moment but we
734 			 * can switch it to asymmetric as needed. Report
735 			 * this bandwidth as available (even though it
736 			 * is not yet enabled).
737 			 */
738 			if (downstream) {
739 				up_bw = link_speed * 1 * 1000;
740 				down_bw = link_speed * 3 * 1000;
741 			} else {
742 				up_bw = link_speed * 3 * 1000;
743 				down_bw = link_speed * 1 * 1000;
744 			}
745 		} else {
746 			up_bw = link_speed * port->sw->link_width * 1000;
747 			down_bw = up_bw;
748 		}
749 	} else {
750 		link_speed = tb_port_get_link_speed(port);
751 		if (link_speed < 0)
752 			return link_speed;
753 
754 		link_width = tb_port_get_link_width(port);
755 		if (link_width < 0)
756 			return link_width;
757 
758 		if (link_width == TB_LINK_WIDTH_ASYM_TX) {
759 			up_bw = link_speed * 1 * 1000;
760 			down_bw = link_speed * 3 * 1000;
761 		} else if (link_width == TB_LINK_WIDTH_ASYM_RX) {
762 			up_bw = link_speed * 3 * 1000;
763 			down_bw = link_speed * 1 * 1000;
764 		} else if (include_asym) {
765 			/*
766 			 * The link is symmetric at the moment but we
767 			 * can switch it to asymmetric as needed. Report
768 			 * this bandwidth as available (even though it
769 			 * is not yet enabled).
770 			 */
771 			if (downstream) {
772 				up_bw = link_speed * 1 * 1000;
773 				down_bw = link_speed * 3 * 1000;
774 			} else {
775 				up_bw = link_speed * 3 * 1000;
776 				down_bw = link_speed * 1 * 1000;
777 			}
778 		} else {
779 			up_bw = link_speed * link_width * 1000;
780 			down_bw = up_bw;
781 		}
782 	}
783 
784 	/* Leave 10% guard band */
785 	*max_up = up_bw - up_bw / 10;
786 	*max_down = down_bw - down_bw / 10;
787 
788 	tb_port_dbg(port, "link maximum bandwidth %d/%d Mb/s\n", *max_up, *max_down);
789 	return 0;
790 }
791 
792 /**
793  * tb_available_bandwidth() - Available bandwidth for tunneling
794  * @tb: Domain structure
795  * @src_port: Source protocol adapter
796  * @dst_port: Destination protocol adapter
797  * @available_up: Available bandwidth upstream (Mb/s)
798  * @available_down: Available bandwidth downstream (Mb/s)
799  * @include_asym: Include bandwidth if the link is switched from
800  *		  symmetric to asymmetric
801  *
802  * Calculates maximum available bandwidth for protocol tunneling between
803  * @src_port and @dst_port at the moment. This is minimum of maximum
804  * link bandwidth across all links reduced by currently consumed
805  * bandwidth on that link.
806  *
807  * If @include_asym is true then includes also bandwidth that can be
808  * added when the links are transitioned into asymmetric (but does not
809  * transition the links).
810  */
tb_available_bandwidth(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port,int * available_up,int * available_down,bool include_asym)811 static int tb_available_bandwidth(struct tb *tb, struct tb_port *src_port,
812 				 struct tb_port *dst_port, int *available_up,
813 				 int *available_down, bool include_asym)
814 {
815 	struct tb_port *port;
816 	int ret;
817 
818 	/* Maximum possible bandwidth asymmetric Gen 4 link is 120 Gb/s */
819 	*available_up = *available_down = 120000;
820 
821 	/* Find the minimum available bandwidth over all links */
822 	tb_for_each_port_on_path(src_port, dst_port, port) {
823 		int max_up, max_down, consumed_up, consumed_down;
824 
825 		if (!tb_port_is_null(port))
826 			continue;
827 
828 		ret = tb_maximum_bandwidth(tb, src_port, dst_port, port,
829 					   &max_up, &max_down, include_asym);
830 		if (ret)
831 			return ret;
832 
833 		ret = tb_consumed_usb3_pcie_bandwidth(tb, src_port, dst_port,
834 						      port, &consumed_up,
835 						      &consumed_down);
836 		if (ret)
837 			return ret;
838 		max_up -= consumed_up;
839 		max_down -= consumed_down;
840 
841 		ret = tb_consumed_dp_bandwidth(tb, src_port, dst_port, port,
842 					       &consumed_up, &consumed_down);
843 		if (ret)
844 			return ret;
845 		max_up -= consumed_up;
846 		max_down -= consumed_down;
847 
848 		if (max_up < *available_up)
849 			*available_up = max_up;
850 		if (max_down < *available_down)
851 			*available_down = max_down;
852 	}
853 
854 	if (*available_up < 0)
855 		*available_up = 0;
856 	if (*available_down < 0)
857 		*available_down = 0;
858 
859 	return 0;
860 }
861 
tb_release_unused_usb3_bandwidth(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port)862 static int tb_release_unused_usb3_bandwidth(struct tb *tb,
863 					    struct tb_port *src_port,
864 					    struct tb_port *dst_port)
865 {
866 	struct tb_tunnel *tunnel;
867 
868 	tunnel = tb_find_first_usb3_tunnel(tb, src_port, dst_port);
869 	return tunnel ? tb_tunnel_release_unused_bandwidth(tunnel) : 0;
870 }
871 
tb_reclaim_usb3_bandwidth(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port)872 static void tb_reclaim_usb3_bandwidth(struct tb *tb, struct tb_port *src_port,
873 				      struct tb_port *dst_port)
874 {
875 	int ret, available_up, available_down;
876 	struct tb_tunnel *tunnel;
877 
878 	tunnel = tb_find_first_usb3_tunnel(tb, src_port, dst_port);
879 	if (!tunnel)
880 		return;
881 
882 	tb_tunnel_dbg(tunnel, "reclaiming unused bandwidth\n");
883 
884 	/*
885 	 * Calculate available bandwidth for the first hop USB3 tunnel.
886 	 * That determines the whole USB3 bandwidth for this branch.
887 	 */
888 	ret = tb_available_bandwidth(tb, tunnel->src_port, tunnel->dst_port,
889 				     &available_up, &available_down, false);
890 	if (ret) {
891 		tb_tunnel_warn(tunnel, "failed to calculate available bandwidth\n");
892 		return;
893 	}
894 
895 	tb_tunnel_dbg(tunnel, "available bandwidth %d/%d Mb/s\n", available_up,
896 		      available_down);
897 
898 	tb_tunnel_reclaim_available_bandwidth(tunnel, &available_up, &available_down);
899 }
900 
tb_tunnel_usb3(struct tb * tb,struct tb_switch * sw)901 static int tb_tunnel_usb3(struct tb *tb, struct tb_switch *sw)
902 {
903 	struct tb_switch *parent = tb_switch_parent(sw);
904 	int ret, available_up, available_down;
905 	struct tb_port *up, *down, *port;
906 	struct tb_cm *tcm = tb_priv(tb);
907 	struct tb_tunnel *tunnel;
908 
909 	if (!tb_acpi_may_tunnel_usb3()) {
910 		tb_dbg(tb, "USB3 tunneling disabled, not creating tunnel\n");
911 		return 0;
912 	}
913 
914 	up = tb_switch_find_port(sw, TB_TYPE_USB3_UP);
915 	if (!up)
916 		return 0;
917 
918 	if (!sw->link_usb4)
919 		return 0;
920 
921 	/*
922 	 * Look up available down port. Since we are chaining it should
923 	 * be found right above this switch.
924 	 */
925 	port = tb_switch_downstream_port(sw);
926 	down = tb_find_usb3_down(parent, port);
927 	if (!down)
928 		return 0;
929 
930 	if (tb_route(parent)) {
931 		struct tb_port *parent_up;
932 		/*
933 		 * Check first that the parent switch has its upstream USB3
934 		 * port enabled. Otherwise the chain is not complete and
935 		 * there is no point setting up a new tunnel.
936 		 */
937 		parent_up = tb_switch_find_port(parent, TB_TYPE_USB3_UP);
938 		if (!parent_up || !tb_port_is_enabled(parent_up))
939 			return 0;
940 
941 		/* Make all unused bandwidth available for the new tunnel */
942 		ret = tb_release_unused_usb3_bandwidth(tb, down, up);
943 		if (ret)
944 			return ret;
945 	}
946 
947 	ret = tb_available_bandwidth(tb, down, up, &available_up, &available_down,
948 				     false);
949 	if (ret)
950 		goto err_reclaim;
951 
952 	tb_port_dbg(up, "available bandwidth for new USB3 tunnel %d/%d Mb/s\n",
953 		    available_up, available_down);
954 
955 	tunnel = tb_tunnel_alloc_usb3(tb, up, down, available_up,
956 				      available_down);
957 	if (!tunnel) {
958 		ret = -ENOMEM;
959 		goto err_reclaim;
960 	}
961 
962 	if (tb_tunnel_activate(tunnel)) {
963 		tb_port_info(up,
964 			     "USB3 tunnel activation failed, aborting\n");
965 		ret = -EIO;
966 		goto err_free;
967 	}
968 
969 	list_add_tail(&tunnel->list, &tcm->tunnel_list);
970 	if (tb_route(parent))
971 		tb_reclaim_usb3_bandwidth(tb, down, up);
972 
973 	return 0;
974 
975 err_free:
976 	tb_tunnel_put(tunnel);
977 err_reclaim:
978 	if (tb_route(parent))
979 		tb_reclaim_usb3_bandwidth(tb, down, up);
980 
981 	return ret;
982 }
983 
tb_create_usb3_tunnels(struct tb_switch * sw)984 static int tb_create_usb3_tunnels(struct tb_switch *sw)
985 {
986 	struct tb_port *port;
987 	int ret;
988 
989 	if (!tb_acpi_may_tunnel_usb3())
990 		return 0;
991 
992 	if (tb_route(sw)) {
993 		ret = tb_tunnel_usb3(sw->tb, sw);
994 		if (ret)
995 			return ret;
996 	}
997 
998 	tb_switch_for_each_port(sw, port) {
999 		if (!tb_port_has_remote(port))
1000 			continue;
1001 		ret = tb_create_usb3_tunnels(port->remote->sw);
1002 		if (ret)
1003 			return ret;
1004 	}
1005 
1006 	return 0;
1007 }
1008 
1009 /**
1010  * tb_configure_asym() - Transition links to asymmetric if needed
1011  * @tb: Domain structure
1012  * @src_port: Source adapter to start the transition
1013  * @dst_port: Destination adapter
1014  * @requested_up: Additional bandwidth (Mb/s) required upstream
1015  * @requested_down: Additional bandwidth (Mb/s) required downstream
1016  *
1017  * Transition links between @src_port and @dst_port into asymmetric, with
1018  * three lanes in the direction from @src_port towards @dst_port and one lane
1019  * in the opposite direction, if the bandwidth requirements
1020  * (requested + currently consumed) on that link exceed @asym_threshold.
1021  *
1022  * Must be called with available >= requested over all links.
1023  */
tb_configure_asym(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port,int requested_up,int requested_down)1024 static int tb_configure_asym(struct tb *tb, struct tb_port *src_port,
1025 			     struct tb_port *dst_port, int requested_up,
1026 			     int requested_down)
1027 {
1028 	bool clx = false, clx_disabled = false, downstream;
1029 	struct tb_switch *sw;
1030 	struct tb_port *up;
1031 	int ret = 0;
1032 
1033 	if (!asym_threshold)
1034 		return 0;
1035 
1036 	downstream = tb_port_path_direction_downstream(src_port, dst_port);
1037 	/* Pick up router deepest in the hierarchy */
1038 	if (downstream)
1039 		sw = dst_port->sw;
1040 	else
1041 		sw = src_port->sw;
1042 
1043 	tb_for_each_upstream_port_on_path(src_port, dst_port, up) {
1044 		struct tb_port *down = tb_switch_downstream_port(up->sw);
1045 		enum tb_link_width width_up, width_down;
1046 		int consumed_up, consumed_down;
1047 
1048 		ret = tb_consumed_dp_bandwidth(tb, src_port, dst_port, up,
1049 					       &consumed_up, &consumed_down);
1050 		if (ret)
1051 			break;
1052 
1053 		if (downstream) {
1054 			/*
1055 			 * Downstream so make sure upstream is within the 36G
1056 			 * (40G - guard band 10%), and the requested is above
1057 			 * what the threshold is.
1058 			 */
1059 			if (consumed_up + requested_up >= TB_ASYM_MIN) {
1060 				ret = -ENOBUFS;
1061 				break;
1062 			}
1063 			/* Does consumed + requested exceed the threshold */
1064 			if (consumed_down + requested_down < asym_threshold)
1065 				continue;
1066 
1067 			width_up = TB_LINK_WIDTH_ASYM_RX;
1068 			width_down = TB_LINK_WIDTH_ASYM_TX;
1069 		} else {
1070 			/* Upstream, the opposite of above */
1071 			if (consumed_down + requested_down >= TB_ASYM_MIN) {
1072 				ret = -ENOBUFS;
1073 				break;
1074 			}
1075 			if (consumed_up + requested_up < asym_threshold)
1076 				continue;
1077 
1078 			width_up = TB_LINK_WIDTH_ASYM_TX;
1079 			width_down = TB_LINK_WIDTH_ASYM_RX;
1080 		}
1081 
1082 		if (up->sw->link_width == width_up)
1083 			continue;
1084 
1085 		if (!tb_port_width_supported(up, width_up) ||
1086 		    !tb_port_width_supported(down, width_down))
1087 			continue;
1088 
1089 		/*
1090 		 * Disable CL states before doing any transitions. We
1091 		 * delayed it until now that we know there is a real
1092 		 * transition taking place.
1093 		 */
1094 		if (!clx_disabled) {
1095 			clx = tb_disable_clx(sw);
1096 			clx_disabled = true;
1097 		}
1098 
1099 		tb_sw_dbg(up->sw, "configuring asymmetric link\n");
1100 
1101 		/*
1102 		 * Here requested + consumed > threshold so we need to
1103 		 * transtion the link into asymmetric now.
1104 		 */
1105 		ret = tb_switch_set_link_width(up->sw, width_up);
1106 		if (ret) {
1107 			tb_sw_warn(up->sw, "failed to set link width\n");
1108 			break;
1109 		}
1110 	}
1111 
1112 	/* Re-enable CL states if they were previosly enabled */
1113 	if (clx)
1114 		tb_enable_clx(sw);
1115 
1116 	return ret;
1117 }
1118 
1119 /**
1120  * tb_configure_sym() - Transition links to symmetric if possible
1121  * @tb: Domain structure
1122  * @src_port: Source adapter to start the transition
1123  * @dst_port: Destination adapter
1124  * @keep_asym: Keep asymmetric link if preferred
1125  *
1126  * Goes over each link from @src_port to @dst_port and tries to
1127  * transition the link to symmetric if the currently consumed bandwidth
1128  * allows and link asymmetric preference is ignored (if @keep_asym is %false).
1129  */
tb_configure_sym(struct tb * tb,struct tb_port * src_port,struct tb_port * dst_port,bool keep_asym)1130 static int tb_configure_sym(struct tb *tb, struct tb_port *src_port,
1131 			    struct tb_port *dst_port, bool keep_asym)
1132 {
1133 	bool clx = false, clx_disabled = false, downstream;
1134 	struct tb_switch *sw;
1135 	struct tb_port *up;
1136 	int ret = 0;
1137 
1138 	if (!asym_threshold)
1139 		return 0;
1140 
1141 	downstream = tb_port_path_direction_downstream(src_port, dst_port);
1142 	/* Pick up router deepest in the hierarchy */
1143 	if (downstream)
1144 		sw = dst_port->sw;
1145 	else
1146 		sw = src_port->sw;
1147 
1148 	tb_for_each_upstream_port_on_path(src_port, dst_port, up) {
1149 		int consumed_up, consumed_down;
1150 
1151 		/* Already symmetric */
1152 		if (up->sw->link_width <= TB_LINK_WIDTH_DUAL)
1153 			continue;
1154 		/* Unplugged, no need to switch */
1155 		if (up->sw->is_unplugged)
1156 			continue;
1157 
1158 		ret = tb_consumed_dp_bandwidth(tb, src_port, dst_port, up,
1159 					       &consumed_up, &consumed_down);
1160 		if (ret)
1161 			break;
1162 
1163 		if (downstream) {
1164 			/*
1165 			 * Downstream so we want the consumed_down < threshold.
1166 			 * Upstream traffic should be less than 36G (40G
1167 			 * guard band 10%) as the link was configured asymmetric
1168 			 * already.
1169 			 */
1170 			if (consumed_down >= asym_threshold)
1171 				continue;
1172 		} else {
1173 			if (consumed_up >= asym_threshold)
1174 				continue;
1175 		}
1176 
1177 		if (up->sw->link_width == TB_LINK_WIDTH_DUAL)
1178 			continue;
1179 
1180 		/*
1181 		 * Here consumed < threshold so we can transition the
1182 		 * link to symmetric.
1183 		 *
1184 		 * However, if the router prefers asymmetric link we
1185 		 * honor that (unless @keep_asym is %false).
1186 		 */
1187 		if (keep_asym &&
1188 		    up->sw->preferred_link_width > TB_LINK_WIDTH_DUAL) {
1189 			tb_sw_dbg(up->sw, "keeping preferred asymmetric link\n");
1190 			continue;
1191 		}
1192 
1193 		/* Disable CL states before doing any transitions */
1194 		if (!clx_disabled) {
1195 			clx = tb_disable_clx(sw);
1196 			clx_disabled = true;
1197 		}
1198 
1199 		tb_sw_dbg(up->sw, "configuring symmetric link\n");
1200 
1201 		ret = tb_switch_set_link_width(up->sw, TB_LINK_WIDTH_DUAL);
1202 		if (ret) {
1203 			tb_sw_warn(up->sw, "failed to set link width\n");
1204 			break;
1205 		}
1206 	}
1207 
1208 	/* Re-enable CL states if they were previosly enabled */
1209 	if (clx)
1210 		tb_enable_clx(sw);
1211 
1212 	return ret;
1213 }
1214 
tb_configure_link(struct tb_port * down,struct tb_port * up,struct tb_switch * sw)1215 static void tb_configure_link(struct tb_port *down, struct tb_port *up,
1216 			      struct tb_switch *sw)
1217 {
1218 	struct tb *tb = sw->tb;
1219 
1220 	/* Link the routers using both links if available */
1221 	down->remote = up;
1222 	up->remote = down;
1223 	if (down->dual_link_port && up->dual_link_port) {
1224 		down->dual_link_port->remote = up->dual_link_port;
1225 		up->dual_link_port->remote = down->dual_link_port;
1226 	}
1227 
1228 	/*
1229 	 * Enable lane bonding if the link is currently two single lane
1230 	 * links.
1231 	 */
1232 	if (sw->link_width < TB_LINK_WIDTH_DUAL)
1233 		tb_switch_set_link_width(sw, TB_LINK_WIDTH_DUAL);
1234 
1235 	/*
1236 	 * Device router that comes up as symmetric link is
1237 	 * connected deeper in the hierarchy, we transition the links
1238 	 * above into symmetric if bandwidth allows.
1239 	 */
1240 	if (tb_switch_depth(sw) > 1 &&
1241 	    tb_port_get_link_generation(up) >= 4 &&
1242 	    up->sw->link_width == TB_LINK_WIDTH_DUAL) {
1243 		struct tb_port *host_port;
1244 
1245 		host_port = tb_port_at(tb_route(sw), tb->root_switch);
1246 		tb_configure_sym(tb, host_port, up, false);
1247 	}
1248 
1249 	/* Set the link configured */
1250 	tb_switch_configure_link(sw);
1251 }
1252 
1253 /*
1254  * tb_scan_switch() - scan for and initialize downstream switches
1255  */
tb_scan_switch(struct tb_switch * sw)1256 static void tb_scan_switch(struct tb_switch *sw)
1257 {
1258 	struct tb_port *port;
1259 
1260 	pm_runtime_get_sync(&sw->dev);
1261 
1262 	tb_switch_for_each_port(sw, port)
1263 		tb_scan_port(port);
1264 
1265 	pm_runtime_mark_last_busy(&sw->dev);
1266 	pm_runtime_put_autosuspend(&sw->dev);
1267 }
1268 
1269 /*
1270  * tb_scan_port() - check for and initialize switches below port
1271  */
tb_scan_port(struct tb_port * port)1272 static void tb_scan_port(struct tb_port *port)
1273 {
1274 	struct tb_cm *tcm = tb_priv(port->sw->tb);
1275 	struct tb_port *upstream_port;
1276 	bool discovery = false;
1277 	struct tb_switch *sw;
1278 
1279 	if (tb_is_upstream_port(port))
1280 		return;
1281 
1282 	if (tb_port_is_dpout(port) && tb_dp_port_hpd_is_active(port) == 1 &&
1283 	    !tb_dp_port_is_enabled(port)) {
1284 		tb_port_dbg(port, "DP adapter HPD set, queuing hotplug\n");
1285 		tb_queue_hotplug(port->sw->tb, tb_route(port->sw), port->port,
1286 				 false);
1287 		return;
1288 	}
1289 
1290 	if (port->config.type != TB_TYPE_PORT)
1291 		return;
1292 	if (port->dual_link_port && port->link_nr)
1293 		return; /*
1294 			 * Downstream switch is reachable through two ports.
1295 			 * Only scan on the primary port (link_nr == 0).
1296 			 */
1297 
1298 	if (port->usb4)
1299 		pm_runtime_get_sync(&port->usb4->dev);
1300 
1301 	if (tb_wait_for_port(port, false) <= 0)
1302 		goto out_rpm_put;
1303 	if (port->remote) {
1304 		tb_port_dbg(port, "port already has a remote\n");
1305 		goto out_rpm_put;
1306 	}
1307 
1308 	sw = tb_switch_alloc(port->sw->tb, &port->sw->dev,
1309 			     tb_downstream_route(port));
1310 	if (IS_ERR(sw)) {
1311 		/*
1312 		 * Make the downstream retimers available even if there
1313 		 * is no router connected.
1314 		 */
1315 		tb_retimer_scan(port, true);
1316 
1317 		/*
1318 		 * If there is an error accessing the connected switch
1319 		 * it may be connected to another domain. Also we allow
1320 		 * the other domain to be connected to a max depth switch.
1321 		 */
1322 		if (PTR_ERR(sw) == -EIO || PTR_ERR(sw) == -EADDRNOTAVAIL)
1323 			tb_scan_xdomain(port);
1324 		goto out_rpm_put;
1325 	}
1326 
1327 	if (tb_switch_configure(sw)) {
1328 		tb_switch_put(sw);
1329 		goto out_rpm_put;
1330 	}
1331 
1332 	/*
1333 	 * If there was previously another domain connected remove it
1334 	 * first.
1335 	 */
1336 	if (port->xdomain) {
1337 		tb_xdomain_remove(port->xdomain);
1338 		tb_port_unconfigure_xdomain(port);
1339 		port->xdomain = NULL;
1340 	}
1341 
1342 	/*
1343 	 * Do not send uevents until we have discovered all existing
1344 	 * tunnels and know which switches were authorized already by
1345 	 * the boot firmware.
1346 	 */
1347 	if (!tcm->hotplug_active) {
1348 		dev_set_uevent_suppress(&sw->dev, true);
1349 		discovery = true;
1350 	}
1351 
1352 	/*
1353 	 * At the moment Thunderbolt 2 and beyond (devices with LC) we
1354 	 * can support runtime PM.
1355 	 */
1356 	sw->rpm = sw->generation > 1;
1357 
1358 	if (tb_switch_add(sw)) {
1359 		tb_switch_put(sw);
1360 		goto out_rpm_put;
1361 	}
1362 
1363 	upstream_port = tb_upstream_port(sw);
1364 	tb_configure_link(port, upstream_port, sw);
1365 
1366 	/*
1367 	 * Scan for downstream retimers. We only scan them after the
1368 	 * router has been enumerated to avoid issues with certain
1369 	 * Pluggable devices that expect the host to enumerate them
1370 	 * within certain timeout.
1371 	 */
1372 	tb_retimer_scan(port, true);
1373 
1374 	/*
1375 	 * CL0s and CL1 are enabled and supported together.
1376 	 * Silently ignore CLx enabling in case CLx is not supported.
1377 	 */
1378 	if (discovery)
1379 		tb_sw_dbg(sw, "discovery, not touching CL states\n");
1380 	else if (tb_enable_clx(sw))
1381 		tb_sw_warn(sw, "failed to enable CL states\n");
1382 
1383 	if (tb_enable_tmu(sw))
1384 		tb_sw_warn(sw, "failed to enable TMU\n");
1385 
1386 	/*
1387 	 * Configuration valid needs to be set after the TMU has been
1388 	 * enabled for the upstream port of the router so we do it here.
1389 	 */
1390 	tb_switch_configuration_valid(sw);
1391 
1392 	/* Scan upstream retimers */
1393 	tb_retimer_scan(upstream_port, true);
1394 
1395 	/*
1396 	 * Create USB 3.x tunnels only when the switch is plugged to the
1397 	 * domain. This is because we scan the domain also during discovery
1398 	 * and want to discover existing USB 3.x tunnels before we create
1399 	 * any new.
1400 	 */
1401 	if (tcm->hotplug_active && tb_tunnel_usb3(sw->tb, sw))
1402 		tb_sw_warn(sw, "USB3 tunnel creation failed\n");
1403 
1404 	tb_add_dp_resources(sw);
1405 	tb_scan_switch(sw);
1406 
1407 out_rpm_put:
1408 	if (port->usb4) {
1409 		pm_runtime_mark_last_busy(&port->usb4->dev);
1410 		pm_runtime_put_autosuspend(&port->usb4->dev);
1411 	}
1412 }
1413 
1414 static void
tb_recalc_estimated_bandwidth_for_group(struct tb_bandwidth_group * group)1415 tb_recalc_estimated_bandwidth_for_group(struct tb_bandwidth_group *group)
1416 {
1417 	struct tb_tunnel *first_tunnel;
1418 	struct tb *tb = group->tb;
1419 	struct tb_port *in;
1420 	int ret;
1421 
1422 	tb_dbg(tb, "re-calculating bandwidth estimation for group %u\n",
1423 	       group->index);
1424 
1425 	first_tunnel = NULL;
1426 	list_for_each_entry(in, &group->ports, group_list) {
1427 		int estimated_bw, estimated_up, estimated_down;
1428 		struct tb_tunnel *tunnel;
1429 		struct tb_port *out;
1430 
1431 		if (!usb4_dp_port_bandwidth_mode_enabled(in))
1432 			continue;
1433 
1434 		tunnel = tb_find_tunnel(tb, TB_TUNNEL_DP, in, NULL);
1435 		if (WARN_ON(!tunnel))
1436 			break;
1437 
1438 		if (!first_tunnel) {
1439 			/*
1440 			 * Since USB3 bandwidth is shared by all DP
1441 			 * tunnels under the host router USB4 port, even
1442 			 * if they do not begin from the host router, we
1443 			 * can release USB3 bandwidth just once and not
1444 			 * for each tunnel separately.
1445 			 */
1446 			first_tunnel = tunnel;
1447 			ret = tb_release_unused_usb3_bandwidth(tb,
1448 				first_tunnel->src_port, first_tunnel->dst_port);
1449 			if (ret) {
1450 				tb_tunnel_warn(tunnel,
1451 					"failed to release unused bandwidth\n");
1452 				break;
1453 			}
1454 		}
1455 
1456 		out = tunnel->dst_port;
1457 		ret = tb_available_bandwidth(tb, in, out, &estimated_up,
1458 					     &estimated_down, true);
1459 		if (ret) {
1460 			tb_tunnel_warn(tunnel,
1461 				"failed to re-calculate estimated bandwidth\n");
1462 			break;
1463 		}
1464 
1465 		/*
1466 		 * Estimated bandwidth includes:
1467 		 *  - already allocated bandwidth for the DP tunnel
1468 		 *  - available bandwidth along the path
1469 		 *  - bandwidth allocated for USB 3.x but not used.
1470 		 */
1471 		if (tb_tunnel_direction_downstream(tunnel))
1472 			estimated_bw = estimated_down;
1473 		else
1474 			estimated_bw = estimated_up;
1475 
1476 		/*
1477 		 * If there is reserved bandwidth for the group that is
1478 		 * not yet released we report that too.
1479 		 */
1480 		tb_tunnel_dbg(tunnel,
1481 			      "re-calculated estimated bandwidth %u (+ %u reserved) = %u Mb/s\n",
1482 			      estimated_bw, group->reserved,
1483 			      estimated_bw + group->reserved);
1484 
1485 		if (usb4_dp_port_set_estimated_bandwidth(in,
1486 				estimated_bw + group->reserved))
1487 			tb_tunnel_warn(tunnel,
1488 				       "failed to update estimated bandwidth\n");
1489 	}
1490 
1491 	if (first_tunnel)
1492 		tb_reclaim_usb3_bandwidth(tb, first_tunnel->src_port,
1493 					  first_tunnel->dst_port);
1494 
1495 	tb_dbg(tb, "bandwidth estimation for group %u done\n", group->index);
1496 }
1497 
tb_recalc_estimated_bandwidth(struct tb * tb)1498 static void tb_recalc_estimated_bandwidth(struct tb *tb)
1499 {
1500 	struct tb_cm *tcm = tb_priv(tb);
1501 	int i;
1502 
1503 	tb_dbg(tb, "bandwidth consumption changed, re-calculating estimated bandwidth\n");
1504 
1505 	for (i = 0; i < ARRAY_SIZE(tcm->groups); i++) {
1506 		struct tb_bandwidth_group *group = &tcm->groups[i];
1507 
1508 		if (!list_empty(&group->ports))
1509 			tb_recalc_estimated_bandwidth_for_group(group);
1510 	}
1511 
1512 	tb_dbg(tb, "bandwidth re-calculation done\n");
1513 }
1514 
__release_group_bandwidth(struct tb_bandwidth_group * group)1515 static bool __release_group_bandwidth(struct tb_bandwidth_group *group)
1516 {
1517 	if (group->reserved) {
1518 		tb_dbg(group->tb, "group %d released total %d Mb/s\n", group->index,
1519 			group->reserved);
1520 		group->reserved = 0;
1521 		return true;
1522 	}
1523 	return false;
1524 }
1525 
__configure_group_sym(struct tb_bandwidth_group * group)1526 static void __configure_group_sym(struct tb_bandwidth_group *group)
1527 {
1528 	struct tb_tunnel *tunnel;
1529 	struct tb_port *in;
1530 
1531 	if (list_empty(&group->ports))
1532 		return;
1533 
1534 	/*
1535 	 * All the tunnels in the group go through the same USB4 links
1536 	 * so we find the first one here and pass the IN and OUT
1537 	 * adapters to tb_configure_sym() which now transitions the
1538 	 * links back to symmetric if bandwidth requirement < asym_threshold.
1539 	 *
1540 	 * We do this here to avoid unnecessary transitions (for example
1541 	 * if the graphics released bandwidth for other tunnel in the
1542 	 * same group).
1543 	 */
1544 	in = list_first_entry(&group->ports, struct tb_port, group_list);
1545 	tunnel = tb_find_tunnel(group->tb, TB_TUNNEL_DP, in, NULL);
1546 	if (tunnel)
1547 		tb_configure_sym(group->tb, in, tunnel->dst_port, true);
1548 }
1549 
tb_bandwidth_group_release_work(struct work_struct * work)1550 static void tb_bandwidth_group_release_work(struct work_struct *work)
1551 {
1552 	struct tb_bandwidth_group *group =
1553 		container_of(work, typeof(*group), release_work.work);
1554 	struct tb *tb = group->tb;
1555 
1556 	mutex_lock(&tb->lock);
1557 	if (__release_group_bandwidth(group))
1558 		tb_recalc_estimated_bandwidth(tb);
1559 	__configure_group_sym(group);
1560 	mutex_unlock(&tb->lock);
1561 }
1562 
tb_init_bandwidth_groups(struct tb_cm * tcm)1563 static void tb_init_bandwidth_groups(struct tb_cm *tcm)
1564 {
1565 	int i;
1566 
1567 	for (i = 0; i < ARRAY_SIZE(tcm->groups); i++) {
1568 		struct tb_bandwidth_group *group = &tcm->groups[i];
1569 
1570 		group->tb = tcm_to_tb(tcm);
1571 		group->index = i + 1;
1572 		INIT_LIST_HEAD(&group->ports);
1573 		INIT_DELAYED_WORK(&group->release_work,
1574 				  tb_bandwidth_group_release_work);
1575 	}
1576 }
1577 
tb_bandwidth_group_attach_port(struct tb_bandwidth_group * group,struct tb_port * in)1578 static void tb_bandwidth_group_attach_port(struct tb_bandwidth_group *group,
1579 					   struct tb_port *in)
1580 {
1581 	if (!group || WARN_ON(in->group))
1582 		return;
1583 
1584 	in->group = group;
1585 	list_add_tail(&in->group_list, &group->ports);
1586 
1587 	tb_port_dbg(in, "attached to bandwidth group %d\n", group->index);
1588 }
1589 
tb_find_free_bandwidth_group(struct tb_cm * tcm)1590 static struct tb_bandwidth_group *tb_find_free_bandwidth_group(struct tb_cm *tcm)
1591 {
1592 	int i;
1593 
1594 	for (i = 0; i < ARRAY_SIZE(tcm->groups); i++) {
1595 		struct tb_bandwidth_group *group = &tcm->groups[i];
1596 
1597 		if (list_empty(&group->ports))
1598 			return group;
1599 	}
1600 
1601 	return NULL;
1602 }
1603 
1604 static struct tb_bandwidth_group *
tb_attach_bandwidth_group(struct tb_cm * tcm,struct tb_port * in,struct tb_port * out)1605 tb_attach_bandwidth_group(struct tb_cm *tcm, struct tb_port *in,
1606 			  struct tb_port *out)
1607 {
1608 	struct tb_bandwidth_group *group;
1609 	struct tb_tunnel *tunnel;
1610 
1611 	/*
1612 	 * Find all DP tunnels that go through all the same USB4 links
1613 	 * as this one. Because we always setup tunnels the same way we
1614 	 * can just check for the routers at both ends of the tunnels
1615 	 * and if they are the same we have a match.
1616 	 */
1617 	list_for_each_entry(tunnel, &tcm->tunnel_list, list) {
1618 		if (!tb_tunnel_is_dp(tunnel))
1619 			continue;
1620 
1621 		if (tunnel->src_port->sw == in->sw &&
1622 		    tunnel->dst_port->sw == out->sw) {
1623 			group = tunnel->src_port->group;
1624 			if (group) {
1625 				tb_bandwidth_group_attach_port(group, in);
1626 				return group;
1627 			}
1628 		}
1629 	}
1630 
1631 	/* Pick up next available group then */
1632 	group = tb_find_free_bandwidth_group(tcm);
1633 	if (group)
1634 		tb_bandwidth_group_attach_port(group, in);
1635 	else
1636 		tb_port_warn(in, "no available bandwidth groups\n");
1637 
1638 	return group;
1639 }
1640 
tb_discover_bandwidth_group(struct tb_cm * tcm,struct tb_port * in,struct tb_port * out)1641 static void tb_discover_bandwidth_group(struct tb_cm *tcm, struct tb_port *in,
1642 					struct tb_port *out)
1643 {
1644 	if (usb4_dp_port_bandwidth_mode_enabled(in)) {
1645 		int index, i;
1646 
1647 		index = usb4_dp_port_group_id(in);
1648 		for (i = 0; i < ARRAY_SIZE(tcm->groups); i++) {
1649 			if (tcm->groups[i].index == index) {
1650 				tb_bandwidth_group_attach_port(&tcm->groups[i], in);
1651 				return;
1652 			}
1653 		}
1654 	}
1655 
1656 	tb_attach_bandwidth_group(tcm, in, out);
1657 }
1658 
tb_detach_bandwidth_group(struct tb_port * in)1659 static void tb_detach_bandwidth_group(struct tb_port *in)
1660 {
1661 	struct tb_bandwidth_group *group = in->group;
1662 
1663 	if (group) {
1664 		in->group = NULL;
1665 		list_del_init(&in->group_list);
1666 
1667 		tb_port_dbg(in, "detached from bandwidth group %d\n", group->index);
1668 
1669 		/* No more tunnels so release the reserved bandwidth if any */
1670 		if (list_empty(&group->ports)) {
1671 			cancel_delayed_work(&group->release_work);
1672 			__release_group_bandwidth(group);
1673 		}
1674 	}
1675 }
1676 
tb_discover_tunnels(struct tb * tb)1677 static void tb_discover_tunnels(struct tb *tb)
1678 {
1679 	struct tb_cm *tcm = tb_priv(tb);
1680 	struct tb_tunnel *tunnel;
1681 
1682 	tb_switch_discover_tunnels(tb->root_switch, &tcm->tunnel_list, true);
1683 
1684 	list_for_each_entry(tunnel, &tcm->tunnel_list, list) {
1685 		if (tb_tunnel_is_pci(tunnel)) {
1686 			struct tb_switch *parent = tunnel->dst_port->sw;
1687 
1688 			while (parent != tunnel->src_port->sw) {
1689 				parent->boot = true;
1690 				parent = tb_switch_parent(parent);
1691 			}
1692 		} else if (tb_tunnel_is_dp(tunnel)) {
1693 			struct tb_port *in = tunnel->src_port;
1694 			struct tb_port *out = tunnel->dst_port;
1695 
1696 			/* Keep the domain from powering down */
1697 			pm_runtime_get_sync(&in->sw->dev);
1698 			pm_runtime_get_sync(&out->sw->dev);
1699 
1700 			tb_discover_bandwidth_group(tcm, in, out);
1701 		}
1702 	}
1703 }
1704 
tb_deactivate_and_free_tunnel(struct tb_tunnel * tunnel)1705 static void tb_deactivate_and_free_tunnel(struct tb_tunnel *tunnel)
1706 {
1707 	struct tb_port *src_port, *dst_port;
1708 	struct tb *tb;
1709 
1710 	if (!tunnel)
1711 		return;
1712 
1713 	tb_tunnel_deactivate(tunnel);
1714 	list_del(&tunnel->list);
1715 
1716 	tb = tunnel->tb;
1717 	src_port = tunnel->src_port;
1718 	dst_port = tunnel->dst_port;
1719 
1720 	switch (tunnel->type) {
1721 	case TB_TUNNEL_DP:
1722 		tb_detach_bandwidth_group(src_port);
1723 		/*
1724 		 * In case of DP tunnel make sure the DP IN resource is
1725 		 * deallocated properly.
1726 		 */
1727 		tb_switch_dealloc_dp_resource(src_port->sw, src_port);
1728 		/*
1729 		 * If bandwidth on a link is < asym_threshold
1730 		 * transition the link to symmetric.
1731 		 */
1732 		tb_configure_sym(tb, src_port, dst_port, true);
1733 		/* Now we can allow the domain to runtime suspend again */
1734 		pm_runtime_mark_last_busy(&dst_port->sw->dev);
1735 		pm_runtime_put_autosuspend(&dst_port->sw->dev);
1736 		pm_runtime_mark_last_busy(&src_port->sw->dev);
1737 		pm_runtime_put_autosuspend(&src_port->sw->dev);
1738 		fallthrough;
1739 
1740 	case TB_TUNNEL_USB3:
1741 		tb_reclaim_usb3_bandwidth(tb, src_port, dst_port);
1742 		break;
1743 
1744 	default:
1745 		/*
1746 		 * PCIe and DMA tunnels do not consume guaranteed
1747 		 * bandwidth.
1748 		 */
1749 		break;
1750 	}
1751 
1752 	tb_tunnel_put(tunnel);
1753 }
1754 
1755 /*
1756  * tb_free_invalid_tunnels() - destroy tunnels of devices that have gone away
1757  */
tb_free_invalid_tunnels(struct tb * tb)1758 static void tb_free_invalid_tunnels(struct tb *tb)
1759 {
1760 	struct tb_cm *tcm = tb_priv(tb);
1761 	struct tb_tunnel *tunnel;
1762 	struct tb_tunnel *n;
1763 
1764 	list_for_each_entry_safe(tunnel, n, &tcm->tunnel_list, list) {
1765 		if (tb_tunnel_is_invalid(tunnel))
1766 			tb_deactivate_and_free_tunnel(tunnel);
1767 	}
1768 }
1769 
1770 /*
1771  * tb_free_unplugged_children() - traverse hierarchy and free unplugged switches
1772  */
tb_free_unplugged_children(struct tb_switch * sw)1773 static void tb_free_unplugged_children(struct tb_switch *sw)
1774 {
1775 	struct tb_port *port;
1776 
1777 	tb_switch_for_each_port(sw, port) {
1778 		if (!tb_port_has_remote(port))
1779 			continue;
1780 
1781 		if (port->remote->sw->is_unplugged) {
1782 			tb_retimer_remove_all(port);
1783 			tb_remove_dp_resources(port->remote->sw);
1784 			tb_switch_unconfigure_link(port->remote->sw);
1785 			tb_switch_set_link_width(port->remote->sw,
1786 						 TB_LINK_WIDTH_SINGLE);
1787 			tb_switch_remove(port->remote->sw);
1788 			port->remote = NULL;
1789 			if (port->dual_link_port)
1790 				port->dual_link_port->remote = NULL;
1791 		} else {
1792 			tb_free_unplugged_children(port->remote->sw);
1793 		}
1794 	}
1795 }
1796 
tb_find_pcie_down(struct tb_switch * sw,const struct tb_port * port)1797 static struct tb_port *tb_find_pcie_down(struct tb_switch *sw,
1798 					 const struct tb_port *port)
1799 {
1800 	struct tb_port *down = NULL;
1801 
1802 	/*
1803 	 * To keep plugging devices consistently in the same PCIe
1804 	 * hierarchy, do mapping here for switch downstream PCIe ports.
1805 	 */
1806 	if (tb_switch_is_usb4(sw)) {
1807 		down = usb4_switch_map_pcie_down(sw, port);
1808 	} else if (!tb_route(sw)) {
1809 		int phy_port = tb_phy_port_from_link(port->port);
1810 		int index;
1811 
1812 		/*
1813 		 * Hard-coded Thunderbolt port to PCIe down port mapping
1814 		 * per controller.
1815 		 */
1816 		if (tb_switch_is_cactus_ridge(sw) ||
1817 		    tb_switch_is_alpine_ridge(sw))
1818 			index = !phy_port ? 6 : 7;
1819 		else if (tb_switch_is_falcon_ridge(sw))
1820 			index = !phy_port ? 6 : 8;
1821 		else if (tb_switch_is_titan_ridge(sw))
1822 			index = !phy_port ? 8 : 9;
1823 		else
1824 			goto out;
1825 
1826 		/* Validate the hard-coding */
1827 		if (WARN_ON(index > sw->config.max_port_number))
1828 			goto out;
1829 
1830 		down = &sw->ports[index];
1831 	}
1832 
1833 	if (down) {
1834 		if (WARN_ON(!tb_port_is_pcie_down(down)))
1835 			goto out;
1836 		if (tb_pci_port_is_enabled(down))
1837 			goto out;
1838 
1839 		return down;
1840 	}
1841 
1842 out:
1843 	return tb_find_unused_port(sw, TB_TYPE_PCIE_DOWN);
1844 }
1845 
tb_find_dp_out(struct tb * tb,struct tb_port * in)1846 static struct tb_port *tb_find_dp_out(struct tb *tb, struct tb_port *in)
1847 {
1848 	struct tb_port *host_port, *port;
1849 	struct tb_cm *tcm = tb_priv(tb);
1850 
1851 	host_port = tb_route(in->sw) ?
1852 		tb_port_at(tb_route(in->sw), tb->root_switch) : NULL;
1853 
1854 	list_for_each_entry(port, &tcm->dp_resources, list) {
1855 		if (!tb_port_is_dpout(port))
1856 			continue;
1857 
1858 		if (tb_port_is_enabled(port)) {
1859 			tb_port_dbg(port, "DP OUT in use\n");
1860 			continue;
1861 		}
1862 
1863 		/* Needs to be on different routers */
1864 		if (in->sw == port->sw) {
1865 			tb_port_dbg(port, "skipping DP OUT on same router\n");
1866 			continue;
1867 		}
1868 
1869 		tb_port_dbg(port, "DP OUT available\n");
1870 
1871 		/*
1872 		 * Keep the DP tunnel under the topology starting from
1873 		 * the same host router downstream port.
1874 		 */
1875 		if (host_port && tb_route(port->sw)) {
1876 			struct tb_port *p;
1877 
1878 			p = tb_port_at(tb_route(port->sw), tb->root_switch);
1879 			if (p != host_port)
1880 				continue;
1881 		}
1882 
1883 		return port;
1884 	}
1885 
1886 	return NULL;
1887 }
1888 
tb_dp_tunnel_active(struct tb_tunnel * tunnel,void * data)1889 static void tb_dp_tunnel_active(struct tb_tunnel *tunnel, void *data)
1890 {
1891 	struct tb_port *in = tunnel->src_port;
1892 	struct tb_port *out = tunnel->dst_port;
1893 	struct tb *tb = data;
1894 
1895 	mutex_lock(&tb->lock);
1896 	if (tb_tunnel_is_active(tunnel)) {
1897 		int consumed_up, consumed_down, ret;
1898 
1899 		tb_tunnel_dbg(tunnel, "DPRX capabilities read completed\n");
1900 
1901 		/* If fail reading tunnel's consumed bandwidth, tear it down */
1902 		ret = tb_tunnel_consumed_bandwidth(tunnel, &consumed_up,
1903 						   &consumed_down);
1904 		if (ret) {
1905 			tb_tunnel_warn(tunnel,
1906 				       "failed to read consumed bandwidth, tearing down\n");
1907 			tb_deactivate_and_free_tunnel(tunnel);
1908 		} else {
1909 			tb_reclaim_usb3_bandwidth(tb, in, out);
1910 			/*
1911 			 * Transition the links to asymmetric if the
1912 			 * consumption exceeds the threshold.
1913 			 */
1914 			tb_configure_asym(tb, in, out, consumed_up,
1915 					  consumed_down);
1916 			/*
1917 			 * Update the domain with the new bandwidth
1918 			 * estimation.
1919 			 */
1920 			tb_recalc_estimated_bandwidth(tb);
1921 			/*
1922 			 * In case of DP tunnel exists, change host
1923 			 * router's 1st children TMU mode to HiFi for
1924 			 * CL0s to work.
1925 			 */
1926 			tb_increase_tmu_accuracy(tunnel);
1927 		}
1928 	} else {
1929 		struct tb_port *in = tunnel->src_port;
1930 
1931 		/*
1932 		 * This tunnel failed to establish. This means DPRX
1933 		 * negotiation most likely did not complete which
1934 		 * happens either because there is no graphics driver
1935 		 * loaded or not all DP cables where connected to the
1936 		 * discrete router.
1937 		 *
1938 		 * In both cases we remove the DP IN adapter from the
1939 		 * available resources as it is not usable. This will
1940 		 * also tear down the tunnel and try to re-use the
1941 		 * released DP OUT.
1942 		 *
1943 		 * It will be added back only if there is hotplug for
1944 		 * the DP IN again.
1945 		 */
1946 		tb_tunnel_warn(tunnel, "not active, tearing down\n");
1947 		tb_dp_resource_unavailable(tb, in, "DPRX negotiation failed");
1948 	}
1949 	mutex_unlock(&tb->lock);
1950 
1951 	tb_domain_put(tb);
1952 }
1953 
tb_tunnel_one_dp(struct tb * tb,struct tb_port * in,struct tb_port * out)1954 static void tb_tunnel_one_dp(struct tb *tb, struct tb_port *in,
1955 			     struct tb_port *out)
1956 {
1957 	int available_up, available_down, ret, link_nr;
1958 	struct tb_cm *tcm = tb_priv(tb);
1959 	struct tb_tunnel *tunnel;
1960 
1961 	/*
1962 	 * This is only applicable to links that are not bonded (so
1963 	 * when Thunderbolt 1 hardware is involved somewhere in the
1964 	 * topology). For these try to share the DP bandwidth between
1965 	 * the two lanes.
1966 	 */
1967 	link_nr = 1;
1968 	list_for_each_entry(tunnel, &tcm->tunnel_list, list) {
1969 		if (tb_tunnel_is_dp(tunnel)) {
1970 			link_nr = 0;
1971 			break;
1972 		}
1973 	}
1974 
1975 	/*
1976 	 * DP stream needs the domain to be active so runtime resume
1977 	 * both ends of the tunnel.
1978 	 *
1979 	 * This should bring the routers in the middle active as well
1980 	 * and keeps the domain from runtime suspending while the DP
1981 	 * tunnel is active.
1982 	 */
1983 	pm_runtime_get_sync(&in->sw->dev);
1984 	pm_runtime_get_sync(&out->sw->dev);
1985 
1986 	if (tb_switch_alloc_dp_resource(in->sw, in)) {
1987 		tb_port_dbg(in, "no resource available for DP IN, not tunneling\n");
1988 		goto err_rpm_put;
1989 	}
1990 
1991 	if (!tb_attach_bandwidth_group(tcm, in, out))
1992 		goto err_dealloc_dp;
1993 
1994 	/* Make all unused USB3 bandwidth available for the new DP tunnel */
1995 	ret = tb_release_unused_usb3_bandwidth(tb, in, out);
1996 	if (ret) {
1997 		tb_warn(tb, "failed to release unused bandwidth\n");
1998 		goto err_detach_group;
1999 	}
2000 
2001 	ret = tb_available_bandwidth(tb, in, out, &available_up, &available_down,
2002 				     true);
2003 	if (ret)
2004 		goto err_reclaim_usb;
2005 
2006 	tb_dbg(tb, "available bandwidth for new DP tunnel %u/%u Mb/s\n",
2007 	       available_up, available_down);
2008 
2009 	tunnel = tb_tunnel_alloc_dp(tb, in, out, link_nr, available_up,
2010 				    available_down, tb_dp_tunnel_active,
2011 				    tb_domain_get(tb));
2012 	if (!tunnel) {
2013 		tb_port_dbg(out, "could not allocate DP tunnel\n");
2014 		goto err_reclaim_usb;
2015 	}
2016 
2017 	list_add_tail(&tunnel->list, &tcm->tunnel_list);
2018 
2019 	ret = tb_tunnel_activate(tunnel);
2020 	if (ret && ret != -EINPROGRESS) {
2021 		tb_port_info(out, "DP tunnel activation failed, aborting\n");
2022 		list_del(&tunnel->list);
2023 		goto err_free;
2024 	}
2025 
2026 	return;
2027 
2028 err_free:
2029 	tb_tunnel_put(tunnel);
2030 err_reclaim_usb:
2031 	tb_reclaim_usb3_bandwidth(tb, in, out);
2032 	tb_domain_put(tb);
2033 err_detach_group:
2034 	tb_detach_bandwidth_group(in);
2035 err_dealloc_dp:
2036 	tb_switch_dealloc_dp_resource(in->sw, in);
2037 err_rpm_put:
2038 	pm_runtime_mark_last_busy(&out->sw->dev);
2039 	pm_runtime_put_autosuspend(&out->sw->dev);
2040 	pm_runtime_mark_last_busy(&in->sw->dev);
2041 	pm_runtime_put_autosuspend(&in->sw->dev);
2042 }
2043 
tb_tunnel_dp(struct tb * tb)2044 static void tb_tunnel_dp(struct tb *tb)
2045 {
2046 	struct tb_cm *tcm = tb_priv(tb);
2047 	struct tb_port *port, *in, *out;
2048 
2049 	if (!tb_acpi_may_tunnel_dp()) {
2050 		tb_dbg(tb, "DP tunneling disabled, not creating tunnel\n");
2051 		return;
2052 	}
2053 
2054 	/*
2055 	 * Find pair of inactive DP IN and DP OUT adapters and then
2056 	 * establish a DP tunnel between them.
2057 	 */
2058 	tb_dbg(tb, "looking for DP IN <-> DP OUT pairs:\n");
2059 
2060 	in = NULL;
2061 	out = NULL;
2062 	list_for_each_entry(port, &tcm->dp_resources, list) {
2063 		if (!tb_port_is_dpin(port))
2064 			continue;
2065 
2066 		if (tb_port_is_enabled(port)) {
2067 			tb_port_dbg(port, "DP IN in use\n");
2068 			continue;
2069 		}
2070 
2071 		in = port;
2072 		tb_port_dbg(in, "DP IN available\n");
2073 
2074 		out = tb_find_dp_out(tb, port);
2075 		if (out)
2076 			tb_tunnel_one_dp(tb, in, out);
2077 		else
2078 			tb_port_dbg(in, "no suitable DP OUT adapter available, not tunneling\n");
2079 	}
2080 
2081 	if (!in)
2082 		tb_dbg(tb, "no suitable DP IN adapter available, not tunneling\n");
2083 }
2084 
tb_enter_redrive(struct tb_port * port)2085 static void tb_enter_redrive(struct tb_port *port)
2086 {
2087 	struct tb_switch *sw = port->sw;
2088 
2089 	if (!(sw->quirks & QUIRK_KEEP_POWER_IN_DP_REDRIVE))
2090 		return;
2091 
2092 	/*
2093 	 * If we get hot-unplug for the DP IN port of the host router
2094 	 * and the DP resource is not available anymore it means there
2095 	 * is a monitor connected directly to the Type-C port and we are
2096 	 * in "redrive" mode. For this to work we cannot enter RTD3 so
2097 	 * we bump up the runtime PM reference count here.
2098 	 */
2099 	if (!tb_port_is_dpin(port))
2100 		return;
2101 	if (tb_route(sw))
2102 		return;
2103 	if (!tb_switch_query_dp_resource(sw, port)) {
2104 		port->redrive = true;
2105 		pm_runtime_get(&sw->dev);
2106 		tb_port_dbg(port, "enter redrive mode, keeping powered\n");
2107 	}
2108 }
2109 
tb_exit_redrive(struct tb_port * port)2110 static void tb_exit_redrive(struct tb_port *port)
2111 {
2112 	struct tb_switch *sw = port->sw;
2113 
2114 	if (!(sw->quirks & QUIRK_KEEP_POWER_IN_DP_REDRIVE))
2115 		return;
2116 
2117 	if (!tb_port_is_dpin(port))
2118 		return;
2119 	if (tb_route(sw))
2120 		return;
2121 	if (port->redrive && tb_switch_query_dp_resource(sw, port)) {
2122 		port->redrive = false;
2123 		pm_runtime_put(&sw->dev);
2124 		tb_port_dbg(port, "exit redrive mode\n");
2125 	}
2126 }
2127 
tb_switch_enter_redrive(struct tb_switch * sw)2128 static void tb_switch_enter_redrive(struct tb_switch *sw)
2129 {
2130 	struct tb_port *port;
2131 
2132 	tb_switch_for_each_port(sw, port)
2133 		tb_enter_redrive(port);
2134 }
2135 
2136 /*
2137  * Called during system and runtime suspend to forcefully exit redrive
2138  * mode without querying whether the resource is available.
2139  */
tb_switch_exit_redrive(struct tb_switch * sw)2140 static void tb_switch_exit_redrive(struct tb_switch *sw)
2141 {
2142 	struct tb_port *port;
2143 
2144 	if (!(sw->quirks & QUIRK_KEEP_POWER_IN_DP_REDRIVE))
2145 		return;
2146 
2147 	tb_switch_for_each_port(sw, port) {
2148 		if (!tb_port_is_dpin(port))
2149 			continue;
2150 
2151 		if (port->redrive) {
2152 			port->redrive = false;
2153 			pm_runtime_put(&sw->dev);
2154 			tb_port_dbg(port, "exit redrive mode\n");
2155 		}
2156 	}
2157 }
2158 
tb_dp_resource_unavailable(struct tb * tb,struct tb_port * port,const char * reason)2159 static void tb_dp_resource_unavailable(struct tb *tb, struct tb_port *port,
2160 				       const char *reason)
2161 {
2162 	struct tb_port *in, *out;
2163 	struct tb_tunnel *tunnel;
2164 
2165 	if (tb_port_is_dpin(port)) {
2166 		tb_port_dbg(port, "DP IN resource unavailable: %s\n", reason);
2167 		in = port;
2168 		out = NULL;
2169 	} else {
2170 		tb_port_dbg(port, "DP OUT resource unavailable: %s\n", reason);
2171 		in = NULL;
2172 		out = port;
2173 	}
2174 
2175 	tunnel = tb_find_tunnel(tb, TB_TUNNEL_DP, in, out);
2176 	if (tunnel)
2177 		tb_deactivate_and_free_tunnel(tunnel);
2178 	else
2179 		tb_enter_redrive(port);
2180 	list_del_init(&port->list);
2181 
2182 	/*
2183 	 * See if there is another DP OUT port that can be used for
2184 	 * to create another tunnel.
2185 	 */
2186 	tb_recalc_estimated_bandwidth(tb);
2187 	tb_tunnel_dp(tb);
2188 }
2189 
tb_dp_resource_available(struct tb * tb,struct tb_port * port)2190 static void tb_dp_resource_available(struct tb *tb, struct tb_port *port)
2191 {
2192 	struct tb_cm *tcm = tb_priv(tb);
2193 	struct tb_port *p;
2194 
2195 	if (tb_port_is_enabled(port))
2196 		return;
2197 
2198 	list_for_each_entry(p, &tcm->dp_resources, list) {
2199 		if (p == port)
2200 			return;
2201 	}
2202 
2203 	tb_port_dbg(port, "DP %s resource available after hotplug\n",
2204 		    tb_port_is_dpin(port) ? "IN" : "OUT");
2205 	list_add_tail(&port->list, &tcm->dp_resources);
2206 	tb_exit_redrive(port);
2207 
2208 	/* Look for suitable DP IN <-> DP OUT pairs now */
2209 	tb_tunnel_dp(tb);
2210 }
2211 
tb_disconnect_and_release_dp(struct tb * tb)2212 static void tb_disconnect_and_release_dp(struct tb *tb)
2213 {
2214 	struct tb_cm *tcm = tb_priv(tb);
2215 	struct tb_tunnel *tunnel, *n;
2216 
2217 	/*
2218 	 * Tear down all DP tunnels and release their resources. They
2219 	 * will be re-established after resume based on plug events.
2220 	 */
2221 	list_for_each_entry_safe_reverse(tunnel, n, &tcm->tunnel_list, list) {
2222 		if (tb_tunnel_is_dp(tunnel))
2223 			tb_deactivate_and_free_tunnel(tunnel);
2224 	}
2225 
2226 	while (!list_empty(&tcm->dp_resources)) {
2227 		struct tb_port *port;
2228 
2229 		port = list_first_entry(&tcm->dp_resources,
2230 					struct tb_port, list);
2231 		list_del_init(&port->list);
2232 	}
2233 }
2234 
tb_disconnect_pci(struct tb * tb,struct tb_switch * sw)2235 static int tb_disconnect_pci(struct tb *tb, struct tb_switch *sw)
2236 {
2237 	struct tb_tunnel *tunnel;
2238 	struct tb_port *up;
2239 
2240 	up = tb_switch_find_port(sw, TB_TYPE_PCIE_UP);
2241 	if (WARN_ON(!up))
2242 		return -ENODEV;
2243 
2244 	tunnel = tb_find_tunnel(tb, TB_TUNNEL_PCI, NULL, up);
2245 	if (WARN_ON(!tunnel))
2246 		return -ENODEV;
2247 
2248 	tb_switch_xhci_disconnect(sw);
2249 
2250 	tb_tunnel_deactivate(tunnel);
2251 	list_del(&tunnel->list);
2252 	tb_tunnel_put(tunnel);
2253 	return 0;
2254 }
2255 
tb_tunnel_pci(struct tb * tb,struct tb_switch * sw)2256 static int tb_tunnel_pci(struct tb *tb, struct tb_switch *sw)
2257 {
2258 	struct tb_port *up, *down, *port;
2259 	struct tb_cm *tcm = tb_priv(tb);
2260 	struct tb_tunnel *tunnel;
2261 
2262 	up = tb_switch_find_port(sw, TB_TYPE_PCIE_UP);
2263 	if (!up)
2264 		return 0;
2265 
2266 	/*
2267 	 * Look up available down port. Since we are chaining it should
2268 	 * be found right above this switch.
2269 	 */
2270 	port = tb_switch_downstream_port(sw);
2271 	down = tb_find_pcie_down(tb_switch_parent(sw), port);
2272 	if (!down)
2273 		return 0;
2274 
2275 	tunnel = tb_tunnel_alloc_pci(tb, up, down);
2276 	if (!tunnel)
2277 		return -ENOMEM;
2278 
2279 	if (tb_tunnel_activate(tunnel)) {
2280 		tb_port_info(up,
2281 			     "PCIe tunnel activation failed, aborting\n");
2282 		tb_tunnel_put(tunnel);
2283 		return -EIO;
2284 	}
2285 
2286 	/*
2287 	 * PCIe L1 is needed to enable CL0s for Titan Ridge so enable it
2288 	 * here.
2289 	 */
2290 	if (tb_switch_pcie_l1_enable(sw))
2291 		tb_sw_warn(sw, "failed to enable PCIe L1 for Titan Ridge\n");
2292 
2293 	if (tb_switch_xhci_connect(sw))
2294 		tb_sw_warn(sw, "failed to connect xHCI\n");
2295 
2296 	list_add_tail(&tunnel->list, &tcm->tunnel_list);
2297 	return 0;
2298 }
2299 
tb_approve_xdomain_paths(struct tb * tb,struct tb_xdomain * xd,int transmit_path,int transmit_ring,int receive_path,int receive_ring)2300 static int tb_approve_xdomain_paths(struct tb *tb, struct tb_xdomain *xd,
2301 				    int transmit_path, int transmit_ring,
2302 				    int receive_path, int receive_ring)
2303 {
2304 	struct tb_cm *tcm = tb_priv(tb);
2305 	struct tb_port *nhi_port, *dst_port;
2306 	struct tb_tunnel *tunnel;
2307 	struct tb_switch *sw;
2308 	int ret;
2309 
2310 	sw = tb_to_switch(xd->dev.parent);
2311 	dst_port = tb_port_at(xd->route, sw);
2312 	nhi_port = tb_switch_find_port(tb->root_switch, TB_TYPE_NHI);
2313 
2314 	mutex_lock(&tb->lock);
2315 
2316 	/*
2317 	 * When tunneling DMA paths the link should not enter CL states
2318 	 * so disable them now.
2319 	 */
2320 	tb_disable_clx(sw);
2321 
2322 	tunnel = tb_tunnel_alloc_dma(tb, nhi_port, dst_port, transmit_path,
2323 				     transmit_ring, receive_path, receive_ring);
2324 	if (!tunnel) {
2325 		ret = -ENOMEM;
2326 		goto err_clx;
2327 	}
2328 
2329 	if (tb_tunnel_activate(tunnel)) {
2330 		tb_port_info(nhi_port,
2331 			     "DMA tunnel activation failed, aborting\n");
2332 		ret = -EIO;
2333 		goto err_free;
2334 	}
2335 
2336 	list_add_tail(&tunnel->list, &tcm->tunnel_list);
2337 	mutex_unlock(&tb->lock);
2338 	return 0;
2339 
2340 err_free:
2341 	tb_tunnel_put(tunnel);
2342 err_clx:
2343 	tb_enable_clx(sw);
2344 	mutex_unlock(&tb->lock);
2345 
2346 	return ret;
2347 }
2348 
__tb_disconnect_xdomain_paths(struct tb * tb,struct tb_xdomain * xd,int transmit_path,int transmit_ring,int receive_path,int receive_ring)2349 static void __tb_disconnect_xdomain_paths(struct tb *tb, struct tb_xdomain *xd,
2350 					  int transmit_path, int transmit_ring,
2351 					  int receive_path, int receive_ring)
2352 {
2353 	struct tb_cm *tcm = tb_priv(tb);
2354 	struct tb_port *nhi_port, *dst_port;
2355 	struct tb_tunnel *tunnel, *n;
2356 	struct tb_switch *sw;
2357 
2358 	sw = tb_to_switch(xd->dev.parent);
2359 	dst_port = tb_port_at(xd->route, sw);
2360 	nhi_port = tb_switch_find_port(tb->root_switch, TB_TYPE_NHI);
2361 
2362 	list_for_each_entry_safe(tunnel, n, &tcm->tunnel_list, list) {
2363 		if (!tb_tunnel_is_dma(tunnel))
2364 			continue;
2365 		if (tunnel->src_port != nhi_port || tunnel->dst_port != dst_port)
2366 			continue;
2367 
2368 		if (tb_tunnel_match_dma(tunnel, transmit_path, transmit_ring,
2369 					receive_path, receive_ring))
2370 			tb_deactivate_and_free_tunnel(tunnel);
2371 	}
2372 
2373 	/*
2374 	 * Try to re-enable CL states now, it is OK if this fails
2375 	 * because we may still have another DMA tunnel active through
2376 	 * the same host router USB4 downstream port.
2377 	 */
2378 	tb_enable_clx(sw);
2379 }
2380 
tb_disconnect_xdomain_paths(struct tb * tb,struct tb_xdomain * xd,int transmit_path,int transmit_ring,int receive_path,int receive_ring)2381 static int tb_disconnect_xdomain_paths(struct tb *tb, struct tb_xdomain *xd,
2382 				       int transmit_path, int transmit_ring,
2383 				       int receive_path, int receive_ring)
2384 {
2385 	if (!xd->is_unplugged) {
2386 		mutex_lock(&tb->lock);
2387 		__tb_disconnect_xdomain_paths(tb, xd, transmit_path,
2388 					      transmit_ring, receive_path,
2389 					      receive_ring);
2390 		mutex_unlock(&tb->lock);
2391 	}
2392 	return 0;
2393 }
2394 
2395 /* hotplug handling */
2396 
2397 /*
2398  * tb_handle_hotplug() - handle hotplug event
2399  *
2400  * Executes on tb->wq.
2401  */
tb_handle_hotplug(struct work_struct * work)2402 static void tb_handle_hotplug(struct work_struct *work)
2403 {
2404 	struct tb_hotplug_event *ev = container_of(work, typeof(*ev), work.work);
2405 	struct tb *tb = ev->tb;
2406 	struct tb_cm *tcm = tb_priv(tb);
2407 	struct tb_switch *sw;
2408 	struct tb_port *port;
2409 
2410 	/* Bring the domain back from sleep if it was suspended */
2411 	pm_runtime_get_sync(&tb->dev);
2412 
2413 	mutex_lock(&tb->lock);
2414 	if (!tcm->hotplug_active)
2415 		goto out; /* during init, suspend or shutdown */
2416 
2417 	sw = tb_switch_find_by_route(tb, ev->route);
2418 	if (!sw) {
2419 		tb_warn(tb,
2420 			"hotplug event from non existent switch %llx:%x (unplug: %d)\n",
2421 			ev->route, ev->port, ev->unplug);
2422 		goto out;
2423 	}
2424 	if (ev->port > sw->config.max_port_number) {
2425 		tb_warn(tb,
2426 			"hotplug event from non existent port %llx:%x (unplug: %d)\n",
2427 			ev->route, ev->port, ev->unplug);
2428 		goto put_sw;
2429 	}
2430 	port = &sw->ports[ev->port];
2431 	if (tb_is_upstream_port(port)) {
2432 		tb_dbg(tb, "hotplug event for upstream port %llx:%x (unplug: %d)\n",
2433 		       ev->route, ev->port, ev->unplug);
2434 		goto put_sw;
2435 	}
2436 
2437 	pm_runtime_get_sync(&sw->dev);
2438 
2439 	if (ev->unplug) {
2440 		tb_retimer_remove_all(port);
2441 
2442 		if (tb_port_has_remote(port)) {
2443 			tb_port_dbg(port, "switch unplugged\n");
2444 			tb_sw_set_unplugged(port->remote->sw);
2445 			tb_free_invalid_tunnels(tb);
2446 			tb_remove_dp_resources(port->remote->sw);
2447 			tb_switch_tmu_disable(port->remote->sw);
2448 			tb_switch_unconfigure_link(port->remote->sw);
2449 			tb_switch_set_link_width(port->remote->sw,
2450 						 TB_LINK_WIDTH_SINGLE);
2451 			tb_switch_remove(port->remote->sw);
2452 			port->remote = NULL;
2453 			if (port->dual_link_port)
2454 				port->dual_link_port->remote = NULL;
2455 			/* Maybe we can create another DP tunnel */
2456 			tb_recalc_estimated_bandwidth(tb);
2457 			tb_tunnel_dp(tb);
2458 		} else if (port->xdomain) {
2459 			struct tb_xdomain *xd = tb_xdomain_get(port->xdomain);
2460 
2461 			tb_port_dbg(port, "xdomain unplugged\n");
2462 			/*
2463 			 * Service drivers are unbound during
2464 			 * tb_xdomain_remove() so setting XDomain as
2465 			 * unplugged here prevents deadlock if they call
2466 			 * tb_xdomain_disable_paths(). We will tear down
2467 			 * all the tunnels below.
2468 			 */
2469 			xd->is_unplugged = true;
2470 			tb_xdomain_remove(xd);
2471 			port->xdomain = NULL;
2472 			__tb_disconnect_xdomain_paths(tb, xd, -1, -1, -1, -1);
2473 			tb_xdomain_put(xd);
2474 			tb_port_unconfigure_xdomain(port);
2475 		} else if (tb_port_is_dpout(port) || tb_port_is_dpin(port)) {
2476 			tb_dp_resource_unavailable(tb, port, "adapter unplug");
2477 		} else if (!port->port) {
2478 			tb_sw_dbg(sw, "xHCI disconnect request\n");
2479 			tb_switch_xhci_disconnect(sw);
2480 		} else {
2481 			tb_port_dbg(port,
2482 				   "got unplug event for disconnected port, ignoring\n");
2483 		}
2484 	} else if (port->remote) {
2485 		tb_port_dbg(port, "got plug event for connected port, ignoring\n");
2486 	} else if (!port->port && sw->authorized) {
2487 		tb_sw_dbg(sw, "xHCI connect request\n");
2488 		tb_switch_xhci_connect(sw);
2489 	} else {
2490 		if (tb_port_is_null(port)) {
2491 			tb_port_dbg(port, "hotplug: scanning\n");
2492 			tb_scan_port(port);
2493 			if (!port->remote)
2494 				tb_port_dbg(port, "hotplug: no switch found\n");
2495 		} else if (tb_port_is_dpout(port) || tb_port_is_dpin(port)) {
2496 			tb_dp_resource_available(tb, port);
2497 		}
2498 	}
2499 
2500 	pm_runtime_mark_last_busy(&sw->dev);
2501 	pm_runtime_put_autosuspend(&sw->dev);
2502 
2503 put_sw:
2504 	tb_switch_put(sw);
2505 out:
2506 	mutex_unlock(&tb->lock);
2507 
2508 	pm_runtime_mark_last_busy(&tb->dev);
2509 	pm_runtime_put_autosuspend(&tb->dev);
2510 
2511 	kfree(ev);
2512 }
2513 
tb_alloc_dp_bandwidth(struct tb_tunnel * tunnel,int * requested_up,int * requested_down)2514 static int tb_alloc_dp_bandwidth(struct tb_tunnel *tunnel, int *requested_up,
2515 				 int *requested_down)
2516 {
2517 	int allocated_up, allocated_down, available_up, available_down, ret;
2518 	int requested_up_corrected, requested_down_corrected, granularity;
2519 	int max_up, max_down, max_up_rounded, max_down_rounded;
2520 	struct tb_bandwidth_group *group;
2521 	struct tb *tb = tunnel->tb;
2522 	struct tb_port *in, *out;
2523 	bool downstream;
2524 
2525 	ret = tb_tunnel_allocated_bandwidth(tunnel, &allocated_up, &allocated_down);
2526 	if (ret)
2527 		return ret;
2528 
2529 	in = tunnel->src_port;
2530 	out = tunnel->dst_port;
2531 
2532 	tb_tunnel_dbg(tunnel, "bandwidth allocated currently %d/%d Mb/s\n",
2533 		      allocated_up, allocated_down);
2534 
2535 	/*
2536 	 * If we get rounded up request from graphics side, say HBR2 x 4
2537 	 * that is 17500 instead of 17280 (this is because of the
2538 	 * granularity), we allow it too. Here the graphics has already
2539 	 * negotiated with the DPRX the maximum possible rates (which is
2540 	 * 17280 in this case).
2541 	 *
2542 	 * Since the link cannot go higher than 17280 we use that in our
2543 	 * calculations but the DP IN adapter Allocated BW write must be
2544 	 * the same value (17500) otherwise the adapter will mark it as
2545 	 * failed for graphics.
2546 	 */
2547 	ret = tb_tunnel_maximum_bandwidth(tunnel, &max_up, &max_down);
2548 	if (ret)
2549 		goto fail;
2550 
2551 	ret = usb4_dp_port_granularity(in);
2552 	if (ret < 0)
2553 		goto fail;
2554 	granularity = ret;
2555 
2556 	max_up_rounded = roundup(max_up, granularity);
2557 	max_down_rounded = roundup(max_down, granularity);
2558 
2559 	/*
2560 	 * This will "fix" the request down to the maximum supported
2561 	 * rate * lanes if it is at the maximum rounded up level.
2562 	 */
2563 	requested_up_corrected = *requested_up;
2564 	if (requested_up_corrected == max_up_rounded)
2565 		requested_up_corrected = max_up;
2566 	else if (requested_up_corrected < 0)
2567 		requested_up_corrected = 0;
2568 	requested_down_corrected = *requested_down;
2569 	if (requested_down_corrected == max_down_rounded)
2570 		requested_down_corrected = max_down;
2571 	else if (requested_down_corrected < 0)
2572 		requested_down_corrected = 0;
2573 
2574 	tb_tunnel_dbg(tunnel, "corrected bandwidth request %d/%d Mb/s\n",
2575 		      requested_up_corrected, requested_down_corrected);
2576 
2577 	if ((*requested_up >= 0 && requested_up_corrected > max_up_rounded) ||
2578 	    (*requested_down >= 0 && requested_down_corrected > max_down_rounded)) {
2579 		tb_tunnel_dbg(tunnel,
2580 			      "bandwidth request too high (%d/%d Mb/s > %d/%d Mb/s)\n",
2581 			      requested_up_corrected, requested_down_corrected,
2582 			      max_up_rounded, max_down_rounded);
2583 		ret = -ENOBUFS;
2584 		goto fail;
2585 	}
2586 
2587 	downstream = tb_tunnel_direction_downstream(tunnel);
2588 	group = in->group;
2589 
2590 	if ((*requested_up >= 0 && requested_up_corrected <= allocated_up) ||
2591 	    (*requested_down >= 0 && requested_down_corrected <= allocated_down)) {
2592 		if (tunnel->bw_mode) {
2593 			int reserved;
2594 			/*
2595 			 * If requested bandwidth is less or equal than
2596 			 * what is currently allocated to that tunnel we
2597 			 * simply change the reservation of the tunnel
2598 			 * and add the released bandwidth for the group
2599 			 * for the next 10s. Then we release it for
2600 			 * others to use.
2601 			 */
2602 			if (downstream)
2603 				reserved = allocated_down - *requested_down;
2604 			else
2605 				reserved = allocated_up - *requested_up;
2606 
2607 			if (reserved > 0) {
2608 				group->reserved += reserved;
2609 				tb_dbg(tb, "group %d reserved %d total %d Mb/s\n",
2610 				       group->index, reserved, group->reserved);
2611 
2612 				/*
2613 				 * If it was not already pending,
2614 				 * schedule release now. If it is then
2615 				 * postpone it for the next 10s (unless
2616 				 * it is already running in which case
2617 				 * the 10s already expired and we should
2618 				 * give the reserved back to others).
2619 				 */
2620 				mod_delayed_work(system_wq, &group->release_work,
2621 					msecs_to_jiffies(TB_RELEASE_BW_TIMEOUT));
2622 			}
2623 		}
2624 
2625 		return tb_tunnel_alloc_bandwidth(tunnel, requested_up,
2626 						 requested_down);
2627 	}
2628 
2629 	/*
2630 	 * More bandwidth is requested. Release all the potential
2631 	 * bandwidth from USB3 first.
2632 	 */
2633 	ret = tb_release_unused_usb3_bandwidth(tb, in, out);
2634 	if (ret)
2635 		goto fail;
2636 
2637 	/*
2638 	 * Then go over all tunnels that cross the same USB4 ports (they
2639 	 * are also in the same group but we use the same function here
2640 	 * that we use with the normal bandwidth allocation).
2641 	 */
2642 	ret = tb_available_bandwidth(tb, in, out, &available_up, &available_down,
2643 				     true);
2644 	if (ret)
2645 		goto reclaim;
2646 
2647 	tb_tunnel_dbg(tunnel, "bandwidth available for allocation %d/%d (+ %u reserved) Mb/s\n",
2648 		      available_up, available_down, group->reserved);
2649 
2650 	if ((*requested_up >= 0 &&
2651 		available_up + group->reserved >= requested_up_corrected) ||
2652 	    (*requested_down >= 0 &&
2653 		available_down + group->reserved >= requested_down_corrected)) {
2654 		int released = 0;
2655 
2656 		/*
2657 		 * If bandwidth on a link is >= asym_threshold
2658 		 * transition the link to asymmetric.
2659 		 */
2660 		ret = tb_configure_asym(tb, in, out, *requested_up,
2661 					*requested_down);
2662 		if (ret) {
2663 			tb_configure_sym(tb, in, out, true);
2664 			goto fail;
2665 		}
2666 
2667 		ret = tb_tunnel_alloc_bandwidth(tunnel, requested_up,
2668 						requested_down);
2669 		if (ret) {
2670 			tb_tunnel_warn(tunnel, "failed to allocate bandwidth\n");
2671 			tb_configure_sym(tb, in, out, true);
2672 		}
2673 
2674 		if (downstream) {
2675 			if (*requested_down > available_down)
2676 				released = *requested_down - available_down;
2677 		} else {
2678 			if (*requested_up > available_up)
2679 				released = *requested_up - available_up;
2680 		}
2681 		if (released) {
2682 			group->reserved -= released;
2683 			tb_dbg(tb, "group %d released %d total %d Mb/s\n",
2684 			       group->index, released, group->reserved);
2685 		}
2686 	} else {
2687 		ret = -ENOBUFS;
2688 	}
2689 
2690 reclaim:
2691 	tb_reclaim_usb3_bandwidth(tb, in, out);
2692 fail:
2693 	if (ret && ret != -ENODEV) {
2694 		/*
2695 		 * Write back the same allocated (so no change), this
2696 		 * makes the DPTX request fail on graphics side.
2697 		 */
2698 		tb_tunnel_dbg(tunnel,
2699 			      "failing the request by rewriting allocated %d/%d Mb/s\n",
2700 			      allocated_up, allocated_down);
2701 		tb_tunnel_alloc_bandwidth(tunnel, &allocated_up, &allocated_down);
2702 	}
2703 
2704 	return ret;
2705 }
2706 
tb_handle_dp_bandwidth_request(struct work_struct * work)2707 static void tb_handle_dp_bandwidth_request(struct work_struct *work)
2708 {
2709 	struct tb_hotplug_event *ev = container_of(work, typeof(*ev), work.work);
2710 	int requested_bw, requested_up, requested_down, ret;
2711 	struct tb_tunnel *tunnel;
2712 	struct tb *tb = ev->tb;
2713 	struct tb_cm *tcm = tb_priv(tb);
2714 	struct tb_switch *sw;
2715 	struct tb_port *in;
2716 
2717 	pm_runtime_get_sync(&tb->dev);
2718 
2719 	mutex_lock(&tb->lock);
2720 	if (!tcm->hotplug_active)
2721 		goto unlock;
2722 
2723 	sw = tb_switch_find_by_route(tb, ev->route);
2724 	if (!sw) {
2725 		tb_warn(tb, "bandwidth request from non-existent router %llx\n",
2726 			ev->route);
2727 		goto unlock;
2728 	}
2729 
2730 	in = &sw->ports[ev->port];
2731 	if (!tb_port_is_dpin(in)) {
2732 		tb_port_warn(in, "bandwidth request to non-DP IN adapter\n");
2733 		goto put_sw;
2734 	}
2735 
2736 	tb_port_dbg(in, "handling bandwidth allocation request, retry %d\n", ev->retry);
2737 
2738 	tunnel = tb_find_tunnel(tb, TB_TUNNEL_DP, in, NULL);
2739 	if (!tunnel) {
2740 		tb_port_warn(in, "failed to find tunnel\n");
2741 		goto put_sw;
2742 	}
2743 
2744 	if (!usb4_dp_port_bandwidth_mode_enabled(in)) {
2745 		if (tunnel->bw_mode) {
2746 			/*
2747 			 * Reset the tunnel back to use the legacy
2748 			 * allocation.
2749 			 */
2750 			tunnel->bw_mode = false;
2751 			tb_port_dbg(in, "DPTX disabled bandwidth allocation mode\n");
2752 		} else {
2753 			tb_port_warn(in, "bandwidth allocation mode not enabled\n");
2754 		}
2755 		goto put_sw;
2756 	}
2757 
2758 	ret = usb4_dp_port_requested_bandwidth(in);
2759 	if (ret < 0) {
2760 		if (ret == -ENODATA) {
2761 			/*
2762 			 * There is no request active so this means the
2763 			 * BW allocation mode was enabled from graphics
2764 			 * side. At this point we know that the graphics
2765 			 * driver has read the DRPX capabilities so we
2766 			 * can offer an better bandwidth estimatation.
2767 			 */
2768 			tb_port_dbg(in, "DPTX enabled bandwidth allocation mode, updating estimated bandwidth\n");
2769 			tb_recalc_estimated_bandwidth(tb);
2770 		} else {
2771 			tb_port_warn(in, "failed to read requested bandwidth\n");
2772 		}
2773 		goto put_sw;
2774 	}
2775 	requested_bw = ret;
2776 
2777 	tb_port_dbg(in, "requested bandwidth %d Mb/s\n", requested_bw);
2778 
2779 	if (tb_tunnel_direction_downstream(tunnel)) {
2780 		requested_up = -1;
2781 		requested_down = requested_bw;
2782 	} else {
2783 		requested_up = requested_bw;
2784 		requested_down = -1;
2785 	}
2786 
2787 	ret = tb_alloc_dp_bandwidth(tunnel, &requested_up, &requested_down);
2788 	if (ret) {
2789 		if (ret == -ENOBUFS) {
2790 			tb_tunnel_warn(tunnel,
2791 				       "not enough bandwidth available\n");
2792 		} else if (ret == -ENOTCONN) {
2793 			tb_tunnel_dbg(tunnel, "not active yet\n");
2794 			/*
2795 			 * We got bandwidth allocation request but the
2796 			 * tunnel is not yet active. This means that
2797 			 * tb_dp_tunnel_active() is not yet called for
2798 			 * this tunnel. Allow it some time and retry
2799 			 * this request a couple of times.
2800 			 */
2801 			if (ev->retry < TB_BW_ALLOC_RETRIES) {
2802 				tb_tunnel_dbg(tunnel,
2803 					      "retrying bandwidth allocation request\n");
2804 				tb_queue_dp_bandwidth_request(tb, ev->route,
2805 							      ev->port,
2806 							      ev->retry + 1,
2807 							      msecs_to_jiffies(50));
2808 			} else {
2809 				tb_tunnel_dbg(tunnel,
2810 					      "run out of retries, failing the request");
2811 			}
2812 		} else {
2813 			tb_tunnel_warn(tunnel,
2814 				       "failed to change bandwidth allocation\n");
2815 		}
2816 	} else {
2817 		tb_tunnel_dbg(tunnel,
2818 			      "bandwidth allocation changed to %d/%d Mb/s\n",
2819 			      requested_up, requested_down);
2820 
2821 		/* Update other clients about the allocation change */
2822 		tb_recalc_estimated_bandwidth(tb);
2823 	}
2824 
2825 put_sw:
2826 	tb_switch_put(sw);
2827 unlock:
2828 	mutex_unlock(&tb->lock);
2829 
2830 	pm_runtime_mark_last_busy(&tb->dev);
2831 	pm_runtime_put_autosuspend(&tb->dev);
2832 
2833 	kfree(ev);
2834 }
2835 
tb_queue_dp_bandwidth_request(struct tb * tb,u64 route,u8 port,int retry,unsigned long delay)2836 static void tb_queue_dp_bandwidth_request(struct tb *tb, u64 route, u8 port,
2837 					  int retry, unsigned long delay)
2838 {
2839 	struct tb_hotplug_event *ev;
2840 
2841 	ev = kmalloc(sizeof(*ev), GFP_KERNEL);
2842 	if (!ev)
2843 		return;
2844 
2845 	ev->tb = tb;
2846 	ev->route = route;
2847 	ev->port = port;
2848 	ev->retry = retry;
2849 	INIT_DELAYED_WORK(&ev->work, tb_handle_dp_bandwidth_request);
2850 	queue_delayed_work(tb->wq, &ev->work, delay);
2851 }
2852 
tb_handle_notification(struct tb * tb,u64 route,const struct cfg_error_pkg * error)2853 static void tb_handle_notification(struct tb *tb, u64 route,
2854 				   const struct cfg_error_pkg *error)
2855 {
2856 
2857 	switch (error->error) {
2858 	case TB_CFG_ERROR_PCIE_WAKE:
2859 	case TB_CFG_ERROR_DP_CON_CHANGE:
2860 	case TB_CFG_ERROR_DPTX_DISCOVERY:
2861 		if (tb_cfg_ack_notification(tb->ctl, route, error))
2862 			tb_warn(tb, "could not ack notification on %llx\n",
2863 				route);
2864 		break;
2865 
2866 	case TB_CFG_ERROR_DP_BW:
2867 		if (tb_cfg_ack_notification(tb->ctl, route, error))
2868 			tb_warn(tb, "could not ack notification on %llx\n",
2869 				route);
2870 		tb_queue_dp_bandwidth_request(tb, route, error->port, 0, 0);
2871 		break;
2872 
2873 	default:
2874 		/* Ignore for now */
2875 		break;
2876 	}
2877 }
2878 
2879 /*
2880  * tb_schedule_hotplug_handler() - callback function for the control channel
2881  *
2882  * Delegates to tb_handle_hotplug.
2883  */
tb_handle_event(struct tb * tb,enum tb_cfg_pkg_type type,const void * buf,size_t size)2884 static void tb_handle_event(struct tb *tb, enum tb_cfg_pkg_type type,
2885 			    const void *buf, size_t size)
2886 {
2887 	const struct cfg_event_pkg *pkg = buf;
2888 	u64 route = tb_cfg_get_route(&pkg->header);
2889 
2890 	switch (type) {
2891 	case TB_CFG_PKG_ERROR:
2892 		tb_handle_notification(tb, route, (const struct cfg_error_pkg *)buf);
2893 		return;
2894 	case TB_CFG_PKG_EVENT:
2895 		break;
2896 	default:
2897 		tb_warn(tb, "unexpected event %#x, ignoring\n", type);
2898 		return;
2899 	}
2900 
2901 	if (tb_cfg_ack_plug(tb->ctl, route, pkg->port, pkg->unplug)) {
2902 		tb_warn(tb, "could not ack plug event on %llx:%x\n", route,
2903 			pkg->port);
2904 	}
2905 
2906 	tb_queue_hotplug(tb, route, pkg->port, pkg->unplug);
2907 }
2908 
tb_stop(struct tb * tb)2909 static void tb_stop(struct tb *tb)
2910 {
2911 	struct tb_cm *tcm = tb_priv(tb);
2912 	struct tb_tunnel *tunnel;
2913 	struct tb_tunnel *n;
2914 
2915 	cancel_delayed_work(&tcm->remove_work);
2916 	/* tunnels are only present after everything has been initialized */
2917 	list_for_each_entry_safe(tunnel, n, &tcm->tunnel_list, list) {
2918 		/*
2919 		 * DMA tunnels require the driver to be functional so we
2920 		 * tear them down. Other protocol tunnels can be left
2921 		 * intact.
2922 		 */
2923 		if (tb_tunnel_is_dma(tunnel))
2924 			tb_tunnel_deactivate(tunnel);
2925 		tb_tunnel_put(tunnel);
2926 	}
2927 	tb_switch_remove(tb->root_switch);
2928 	tcm->hotplug_active = false; /* signal tb_handle_hotplug to quit */
2929 }
2930 
tb_deinit(struct tb * tb)2931 static void tb_deinit(struct tb *tb)
2932 {
2933 	struct tb_cm *tcm = tb_priv(tb);
2934 	int i;
2935 
2936 	/* Cancel all the release bandwidth workers */
2937 	for (i = 0; i < ARRAY_SIZE(tcm->groups); i++)
2938 		cancel_delayed_work_sync(&tcm->groups[i].release_work);
2939 }
2940 
tb_scan_finalize_switch(struct device * dev,void * data)2941 static int tb_scan_finalize_switch(struct device *dev, void *data)
2942 {
2943 	if (tb_is_switch(dev)) {
2944 		struct tb_switch *sw = tb_to_switch(dev);
2945 
2946 		/*
2947 		 * If we found that the switch was already setup by the
2948 		 * boot firmware, mark it as authorized now before we
2949 		 * send uevent to userspace.
2950 		 */
2951 		if (sw->boot)
2952 			sw->authorized = 1;
2953 
2954 		dev_set_uevent_suppress(dev, false);
2955 		kobject_uevent(&dev->kobj, KOBJ_ADD);
2956 		device_for_each_child(dev, NULL, tb_scan_finalize_switch);
2957 	}
2958 
2959 	return 0;
2960 }
2961 
tb_start(struct tb * tb,bool reset)2962 static int tb_start(struct tb *tb, bool reset)
2963 {
2964 	struct tb_cm *tcm = tb_priv(tb);
2965 	bool discover = true;
2966 	int ret;
2967 
2968 	tb->root_switch = tb_switch_alloc(tb, &tb->dev, 0);
2969 	if (IS_ERR(tb->root_switch))
2970 		return PTR_ERR(tb->root_switch);
2971 
2972 	/*
2973 	 * ICM firmware upgrade needs running firmware and in native
2974 	 * mode that is not available so disable firmware upgrade of the
2975 	 * root switch.
2976 	 *
2977 	 * However, USB4 routers support NVM firmware upgrade if they
2978 	 * implement the necessary router operations.
2979 	 */
2980 	tb->root_switch->no_nvm_upgrade = !tb_switch_is_usb4(tb->root_switch);
2981 	/* All USB4 routers support runtime PM */
2982 	tb->root_switch->rpm = tb_switch_is_usb4(tb->root_switch);
2983 
2984 	ret = tb_switch_configure(tb->root_switch);
2985 	if (ret) {
2986 		tb_switch_put(tb->root_switch);
2987 		return ret;
2988 	}
2989 
2990 	/* Announce the switch to the world */
2991 	ret = tb_switch_add(tb->root_switch);
2992 	if (ret) {
2993 		tb_switch_put(tb->root_switch);
2994 		return ret;
2995 	}
2996 
2997 	/*
2998 	 * To support highest CLx state, we set host router's TMU to
2999 	 * Normal mode.
3000 	 */
3001 	tb_switch_tmu_configure(tb->root_switch, TB_SWITCH_TMU_MODE_LOWRES);
3002 	/* Enable TMU if it is off */
3003 	tb_switch_tmu_enable(tb->root_switch);
3004 
3005 	/*
3006 	 * Boot firmware might have created tunnels of its own. Since we
3007 	 * cannot be sure they are usable for us, tear them down and
3008 	 * reset the ports to handle it as new hotplug for USB4 v1
3009 	 * routers (for USB4 v2 and beyond we already do host reset).
3010 	 */
3011 	if (reset && tb_switch_is_usb4(tb->root_switch)) {
3012 		discover = false;
3013 		if (usb4_switch_version(tb->root_switch) == 1)
3014 			tb_switch_reset(tb->root_switch);
3015 	}
3016 
3017 	if (discover) {
3018 		/* Full scan to discover devices added before the driver was loaded. */
3019 		tb_scan_switch(tb->root_switch);
3020 		/* Find out tunnels created by the boot firmware */
3021 		tb_discover_tunnels(tb);
3022 		/* Add DP resources from the DP tunnels created by the boot firmware */
3023 		tb_discover_dp_resources(tb);
3024 	}
3025 
3026 	/*
3027 	 * If the boot firmware did not create USB 3.x tunnels create them
3028 	 * now for the whole topology.
3029 	 */
3030 	tb_create_usb3_tunnels(tb->root_switch);
3031 	/* Add DP IN resources for the root switch */
3032 	tb_add_dp_resources(tb->root_switch);
3033 	tb_switch_enter_redrive(tb->root_switch);
3034 	/* Make the discovered switches available to the userspace */
3035 	device_for_each_child(&tb->root_switch->dev, NULL,
3036 			      tb_scan_finalize_switch);
3037 
3038 	/* Allow tb_handle_hotplug to progress events */
3039 	tcm->hotplug_active = true;
3040 	return 0;
3041 }
3042 
tb_suspend_noirq(struct tb * tb)3043 static int tb_suspend_noirq(struct tb *tb)
3044 {
3045 	struct tb_cm *tcm = tb_priv(tb);
3046 
3047 	tb_dbg(tb, "suspending...\n");
3048 	tb_disconnect_and_release_dp(tb);
3049 	tb_switch_exit_redrive(tb->root_switch);
3050 	tb_switch_suspend(tb->root_switch, false);
3051 	tcm->hotplug_active = false; /* signal tb_handle_hotplug to quit */
3052 	tb_dbg(tb, "suspend finished\n");
3053 
3054 	return 0;
3055 }
3056 
tb_restore_children(struct tb_switch * sw)3057 static void tb_restore_children(struct tb_switch *sw)
3058 {
3059 	struct tb_port *port;
3060 
3061 	/* No need to restore if the router is already unplugged */
3062 	if (sw->is_unplugged)
3063 		return;
3064 
3065 	if (tb_enable_clx(sw))
3066 		tb_sw_warn(sw, "failed to re-enable CL states\n");
3067 
3068 	if (tb_enable_tmu(sw))
3069 		tb_sw_warn(sw, "failed to restore TMU configuration\n");
3070 
3071 	tb_switch_configuration_valid(sw);
3072 
3073 	tb_switch_for_each_port(sw, port) {
3074 		if (!tb_port_has_remote(port) && !port->xdomain)
3075 			continue;
3076 
3077 		if (port->remote) {
3078 			tb_switch_set_link_width(port->remote->sw,
3079 						 port->remote->sw->link_width);
3080 			tb_switch_configure_link(port->remote->sw);
3081 
3082 			tb_restore_children(port->remote->sw);
3083 		} else if (port->xdomain) {
3084 			tb_port_configure_xdomain(port, port->xdomain);
3085 		}
3086 	}
3087 }
3088 
tb_resume_noirq(struct tb * tb)3089 static int tb_resume_noirq(struct tb *tb)
3090 {
3091 	struct tb_cm *tcm = tb_priv(tb);
3092 	struct tb_tunnel *tunnel, *n;
3093 	unsigned int usb3_delay = 0;
3094 	LIST_HEAD(tunnels);
3095 
3096 	tb_dbg(tb, "resuming...\n");
3097 
3098 	/*
3099 	 * For non-USB4 hosts (Apple systems) remove any PCIe devices
3100 	 * the firmware might have setup.
3101 	 */
3102 	if (!tb_switch_is_usb4(tb->root_switch))
3103 		tb_switch_reset(tb->root_switch);
3104 
3105 	tb_switch_resume(tb->root_switch, false);
3106 	tb_free_invalid_tunnels(tb);
3107 	tb_free_unplugged_children(tb->root_switch);
3108 	tb_restore_children(tb->root_switch);
3109 
3110 	/*
3111 	 * If we get here from suspend to disk the boot firmware or the
3112 	 * restore kernel might have created tunnels of its own. Since
3113 	 * we cannot be sure they are usable for us we find and tear
3114 	 * them down.
3115 	 */
3116 	tb_switch_discover_tunnels(tb->root_switch, &tunnels, false);
3117 	list_for_each_entry_safe_reverse(tunnel, n, &tunnels, list) {
3118 		if (tb_tunnel_is_usb3(tunnel))
3119 			usb3_delay = 500;
3120 		tb_tunnel_deactivate(tunnel);
3121 		tb_tunnel_put(tunnel);
3122 	}
3123 
3124 	/* Re-create our tunnels now */
3125 	list_for_each_entry_safe(tunnel, n, &tcm->tunnel_list, list) {
3126 		/* USB3 requires delay before it can be re-activated */
3127 		if (tb_tunnel_is_usb3(tunnel)) {
3128 			msleep(usb3_delay);
3129 			/* Only need to do it once */
3130 			usb3_delay = 0;
3131 		}
3132 		tb_tunnel_activate(tunnel);
3133 	}
3134 	if (!list_empty(&tcm->tunnel_list)) {
3135 		/*
3136 		 * the pcie links need some time to get going.
3137 		 * 100ms works for me...
3138 		 */
3139 		tb_dbg(tb, "tunnels restarted, sleeping for 100ms\n");
3140 		msleep(100);
3141 	}
3142 	tb_switch_enter_redrive(tb->root_switch);
3143 	 /* Allow tb_handle_hotplug to progress events */
3144 	tcm->hotplug_active = true;
3145 	tb_dbg(tb, "resume finished\n");
3146 
3147 	return 0;
3148 }
3149 
tb_free_unplugged_xdomains(struct tb_switch * sw)3150 static int tb_free_unplugged_xdomains(struct tb_switch *sw)
3151 {
3152 	struct tb_port *port;
3153 	int ret = 0;
3154 
3155 	tb_switch_for_each_port(sw, port) {
3156 		if (tb_is_upstream_port(port))
3157 			continue;
3158 		if (port->xdomain && port->xdomain->is_unplugged) {
3159 			tb_retimer_remove_all(port);
3160 			tb_xdomain_remove(port->xdomain);
3161 			tb_port_unconfigure_xdomain(port);
3162 			port->xdomain = NULL;
3163 			ret++;
3164 		} else if (port->remote) {
3165 			ret += tb_free_unplugged_xdomains(port->remote->sw);
3166 		}
3167 	}
3168 
3169 	return ret;
3170 }
3171 
tb_freeze_noirq(struct tb * tb)3172 static int tb_freeze_noirq(struct tb *tb)
3173 {
3174 	struct tb_cm *tcm = tb_priv(tb);
3175 
3176 	tcm->hotplug_active = false;
3177 	return 0;
3178 }
3179 
tb_thaw_noirq(struct tb * tb)3180 static int tb_thaw_noirq(struct tb *tb)
3181 {
3182 	struct tb_cm *tcm = tb_priv(tb);
3183 
3184 	tcm->hotplug_active = true;
3185 	return 0;
3186 }
3187 
tb_complete(struct tb * tb)3188 static void tb_complete(struct tb *tb)
3189 {
3190 	/*
3191 	 * Release any unplugged XDomains and if there is a case where
3192 	 * another domain is swapped in place of unplugged XDomain we
3193 	 * need to run another rescan.
3194 	 */
3195 	mutex_lock(&tb->lock);
3196 	if (tb_free_unplugged_xdomains(tb->root_switch))
3197 		tb_scan_switch(tb->root_switch);
3198 	mutex_unlock(&tb->lock);
3199 }
3200 
tb_runtime_suspend(struct tb * tb)3201 static int tb_runtime_suspend(struct tb *tb)
3202 {
3203 	struct tb_cm *tcm = tb_priv(tb);
3204 
3205 	mutex_lock(&tb->lock);
3206 	/*
3207 	 * The below call only releases DP resources to allow exiting and
3208 	 * re-entering redrive mode.
3209 	 */
3210 	tb_disconnect_and_release_dp(tb);
3211 	tb_switch_exit_redrive(tb->root_switch);
3212 	tb_switch_suspend(tb->root_switch, true);
3213 	tcm->hotplug_active = false;
3214 	mutex_unlock(&tb->lock);
3215 
3216 	return 0;
3217 }
3218 
tb_remove_work(struct work_struct * work)3219 static void tb_remove_work(struct work_struct *work)
3220 {
3221 	struct tb_cm *tcm = container_of(work, struct tb_cm, remove_work.work);
3222 	struct tb *tb = tcm_to_tb(tcm);
3223 
3224 	mutex_lock(&tb->lock);
3225 	if (tb->root_switch) {
3226 		tb_free_unplugged_children(tb->root_switch);
3227 		tb_free_unplugged_xdomains(tb->root_switch);
3228 	}
3229 	mutex_unlock(&tb->lock);
3230 }
3231 
tb_runtime_resume(struct tb * tb)3232 static int tb_runtime_resume(struct tb *tb)
3233 {
3234 	struct tb_cm *tcm = tb_priv(tb);
3235 	struct tb_tunnel *tunnel, *n;
3236 
3237 	mutex_lock(&tb->lock);
3238 	tb_switch_resume(tb->root_switch, true);
3239 	tb_free_invalid_tunnels(tb);
3240 	tb_restore_children(tb->root_switch);
3241 	list_for_each_entry_safe(tunnel, n, &tcm->tunnel_list, list)
3242 		tb_tunnel_activate(tunnel);
3243 	tb_switch_enter_redrive(tb->root_switch);
3244 	tcm->hotplug_active = true;
3245 	mutex_unlock(&tb->lock);
3246 
3247 	/*
3248 	 * Schedule cleanup of any unplugged devices. Run this in a
3249 	 * separate thread to avoid possible deadlock if the device
3250 	 * removal runtime resumes the unplugged device.
3251 	 */
3252 	queue_delayed_work(tb->wq, &tcm->remove_work, msecs_to_jiffies(50));
3253 	return 0;
3254 }
3255 
3256 static const struct tb_cm_ops tb_cm_ops = {
3257 	.start = tb_start,
3258 	.stop = tb_stop,
3259 	.deinit = tb_deinit,
3260 	.suspend_noirq = tb_suspend_noirq,
3261 	.resume_noirq = tb_resume_noirq,
3262 	.freeze_noirq = tb_freeze_noirq,
3263 	.thaw_noirq = tb_thaw_noirq,
3264 	.complete = tb_complete,
3265 	.runtime_suspend = tb_runtime_suspend,
3266 	.runtime_resume = tb_runtime_resume,
3267 	.handle_event = tb_handle_event,
3268 	.disapprove_switch = tb_disconnect_pci,
3269 	.approve_switch = tb_tunnel_pci,
3270 	.approve_xdomain_paths = tb_approve_xdomain_paths,
3271 	.disconnect_xdomain_paths = tb_disconnect_xdomain_paths,
3272 };
3273 
3274 /*
3275  * During suspend the Thunderbolt controller is reset and all PCIe
3276  * tunnels are lost. The NHI driver will try to reestablish all tunnels
3277  * during resume. This adds device links between the tunneled PCIe
3278  * downstream ports and the NHI so that the device core will make sure
3279  * NHI is resumed first before the rest.
3280  */
tb_apple_add_links(struct tb_nhi * nhi)3281 static bool tb_apple_add_links(struct tb_nhi *nhi)
3282 {
3283 	struct pci_dev *upstream, *pdev;
3284 	bool ret;
3285 
3286 	if (!x86_apple_machine)
3287 		return false;
3288 
3289 	switch (nhi->pdev->device) {
3290 	case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
3291 	case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C:
3292 	case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_NHI:
3293 	case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_NHI:
3294 		break;
3295 	default:
3296 		return false;
3297 	}
3298 
3299 	upstream = pci_upstream_bridge(nhi->pdev);
3300 	while (upstream) {
3301 		if (!pci_is_pcie(upstream))
3302 			return false;
3303 		if (pci_pcie_type(upstream) == PCI_EXP_TYPE_UPSTREAM)
3304 			break;
3305 		upstream = pci_upstream_bridge(upstream);
3306 	}
3307 
3308 	if (!upstream)
3309 		return false;
3310 
3311 	/*
3312 	 * For each hotplug downstream port, create add device link
3313 	 * back to NHI so that PCIe tunnels can be re-established after
3314 	 * sleep.
3315 	 */
3316 	ret = false;
3317 	for_each_pci_bridge(pdev, upstream->subordinate) {
3318 		const struct device_link *link;
3319 
3320 		if (!pci_is_pcie(pdev))
3321 			continue;
3322 		if (pci_pcie_type(pdev) != PCI_EXP_TYPE_DOWNSTREAM ||
3323 		    !pdev->is_hotplug_bridge)
3324 			continue;
3325 
3326 		link = device_link_add(&pdev->dev, &nhi->pdev->dev,
3327 				       DL_FLAG_AUTOREMOVE_SUPPLIER |
3328 				       DL_FLAG_PM_RUNTIME);
3329 		if (link) {
3330 			dev_dbg(&nhi->pdev->dev, "created link from %s\n",
3331 				dev_name(&pdev->dev));
3332 			ret = true;
3333 		} else {
3334 			dev_warn(&nhi->pdev->dev, "device link creation from %s failed\n",
3335 				 dev_name(&pdev->dev));
3336 		}
3337 	}
3338 
3339 	return ret;
3340 }
3341 
tb_probe(struct tb_nhi * nhi)3342 struct tb *tb_probe(struct tb_nhi *nhi)
3343 {
3344 	struct tb_cm *tcm;
3345 	struct tb *tb;
3346 
3347 	tb = tb_domain_alloc(nhi, TB_TIMEOUT, sizeof(*tcm));
3348 	if (!tb)
3349 		return NULL;
3350 
3351 	if (tb_acpi_may_tunnel_pcie())
3352 		tb->security_level = TB_SECURITY_USER;
3353 	else
3354 		tb->security_level = TB_SECURITY_NOPCIE;
3355 
3356 	tb->cm_ops = &tb_cm_ops;
3357 
3358 	tcm = tb_priv(tb);
3359 	INIT_LIST_HEAD(&tcm->tunnel_list);
3360 	INIT_LIST_HEAD(&tcm->dp_resources);
3361 	INIT_DELAYED_WORK(&tcm->remove_work, tb_remove_work);
3362 	tb_init_bandwidth_groups(tcm);
3363 
3364 	tb_dbg(tb, "using software connection manager\n");
3365 
3366 	/*
3367 	 * Device links are needed to make sure we establish tunnels
3368 	 * before the PCIe/USB stack is resumed so complain here if we
3369 	 * found them missing.
3370 	 */
3371 	if (!tb_apple_add_links(nhi) && !tb_acpi_add_links(nhi))
3372 		tb_warn(tb, "device links to tunneled native ports are missing!\n");
3373 
3374 	return tb;
3375 }
3376