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