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