xref: /openbmc/linux/drivers/thunderbolt/tunnel.c (revision 1e70d57e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Thunderbolt driver - Tunneling support
4  *
5  * Copyright (c) 2014 Andreas Noever <andreas.noever@gmail.com>
6  * Copyright (C) 2019, Intel Corporation
7  */
8 
9 #include <linux/delay.h>
10 #include <linux/slab.h>
11 #include <linux/list.h>
12 
13 #include "tunnel.h"
14 #include "tb.h"
15 
16 /* PCIe adapters use always HopID of 8 for both directions */
17 #define TB_PCI_HOPID			8
18 
19 #define TB_PCI_PATH_DOWN		0
20 #define TB_PCI_PATH_UP			1
21 
22 /* USB3 adapters use always HopID of 8 for both directions */
23 #define TB_USB3_HOPID			8
24 
25 #define TB_USB3_PATH_DOWN		0
26 #define TB_USB3_PATH_UP			1
27 
28 /* DP adapters use HopID 8 for AUX and 9 for Video */
29 #define TB_DP_AUX_TX_HOPID		8
30 #define TB_DP_AUX_RX_HOPID		8
31 #define TB_DP_VIDEO_HOPID		9
32 
33 #define TB_DP_VIDEO_PATH_OUT		0
34 #define TB_DP_AUX_PATH_OUT		1
35 #define TB_DP_AUX_PATH_IN		2
36 
37 /* Minimum number of credits needed for PCIe path */
38 #define TB_MIN_PCIE_CREDITS		6U
39 /*
40  * Number of credits we try to allocate for each DMA path if not limited
41  * by the host router baMaxHI.
42  */
43 #define TB_DMA_CREDITS			14U
44 /* Minimum number of credits for DMA path */
45 #define TB_MIN_DMA_CREDITS		1U
46 
47 static const char * const tb_tunnel_names[] = { "PCI", "DP", "DMA", "USB3" };
48 
49 #define __TB_TUNNEL_PRINT(level, tunnel, fmt, arg...)                   \
50 	do {                                                            \
51 		struct tb_tunnel *__tunnel = (tunnel);                  \
52 		level(__tunnel->tb, "%llx:%x <-> %llx:%x (%s): " fmt,   \
53 		      tb_route(__tunnel->src_port->sw),                 \
54 		      __tunnel->src_port->port,                         \
55 		      tb_route(__tunnel->dst_port->sw),                 \
56 		      __tunnel->dst_port->port,                         \
57 		      tb_tunnel_names[__tunnel->type],			\
58 		      ## arg);                                          \
59 	} while (0)
60 
61 #define tb_tunnel_WARN(tunnel, fmt, arg...) \
62 	__TB_TUNNEL_PRINT(tb_WARN, tunnel, fmt, ##arg)
63 #define tb_tunnel_warn(tunnel, fmt, arg...) \
64 	__TB_TUNNEL_PRINT(tb_warn, tunnel, fmt, ##arg)
65 #define tb_tunnel_info(tunnel, fmt, arg...) \
66 	__TB_TUNNEL_PRINT(tb_info, tunnel, fmt, ##arg)
67 #define tb_tunnel_dbg(tunnel, fmt, arg...) \
68 	__TB_TUNNEL_PRINT(tb_dbg, tunnel, fmt, ##arg)
69 
70 static inline unsigned int tb_usable_credits(const struct tb_port *port)
71 {
72 	return port->total_credits - port->ctl_credits;
73 }
74 
75 /**
76  * tb_available_credits() - Available credits for PCIe and DMA
77  * @port: Lane adapter to check
78  * @max_dp_streams: If non-%NULL stores maximum number of simultaneous DP
79  *		    streams possible through this lane adapter
80  */
81 static unsigned int tb_available_credits(const struct tb_port *port,
82 					 size_t *max_dp_streams)
83 {
84 	const struct tb_switch *sw = port->sw;
85 	int credits, usb3, pcie, spare;
86 	size_t ndp;
87 
88 	usb3 = tb_acpi_may_tunnel_usb3() ? sw->max_usb3_credits : 0;
89 	pcie = tb_acpi_may_tunnel_pcie() ? sw->max_pcie_credits : 0;
90 
91 	if (tb_acpi_is_xdomain_allowed()) {
92 		spare = min_not_zero(sw->max_dma_credits, TB_DMA_CREDITS);
93 		/* Add some credits for potential second DMA tunnel */
94 		spare += TB_MIN_DMA_CREDITS;
95 	} else {
96 		spare = 0;
97 	}
98 
99 	credits = tb_usable_credits(port);
100 	if (tb_acpi_may_tunnel_dp()) {
101 		/*
102 		 * Maximum number of DP streams possible through the
103 		 * lane adapter.
104 		 */
105 		ndp = (credits - (usb3 + pcie + spare)) /
106 		      (sw->min_dp_aux_credits + sw->min_dp_main_credits);
107 	} else {
108 		ndp = 0;
109 	}
110 	credits -= ndp * (sw->min_dp_aux_credits + sw->min_dp_main_credits);
111 	credits -= usb3;
112 
113 	if (max_dp_streams)
114 		*max_dp_streams = ndp;
115 
116 	return credits > 0 ? credits : 0;
117 }
118 
119 static struct tb_tunnel *tb_tunnel_alloc(struct tb *tb, size_t npaths,
120 					 enum tb_tunnel_type type)
121 {
122 	struct tb_tunnel *tunnel;
123 
124 	tunnel = kzalloc(sizeof(*tunnel), GFP_KERNEL);
125 	if (!tunnel)
126 		return NULL;
127 
128 	tunnel->paths = kcalloc(npaths, sizeof(tunnel->paths[0]), GFP_KERNEL);
129 	if (!tunnel->paths) {
130 		tb_tunnel_free(tunnel);
131 		return NULL;
132 	}
133 
134 	INIT_LIST_HEAD(&tunnel->list);
135 	tunnel->tb = tb;
136 	tunnel->npaths = npaths;
137 	tunnel->type = type;
138 
139 	return tunnel;
140 }
141 
142 static int tb_pci_activate(struct tb_tunnel *tunnel, bool activate)
143 {
144 	int res;
145 
146 	res = tb_pci_port_enable(tunnel->src_port, activate);
147 	if (res)
148 		return res;
149 
150 	if (tb_port_is_pcie_up(tunnel->dst_port))
151 		return tb_pci_port_enable(tunnel->dst_port, activate);
152 
153 	return 0;
154 }
155 
156 static int tb_pci_init_credits(struct tb_path_hop *hop)
157 {
158 	struct tb_port *port = hop->in_port;
159 	struct tb_switch *sw = port->sw;
160 	unsigned int credits;
161 
162 	if (tb_port_use_credit_allocation(port)) {
163 		unsigned int available;
164 
165 		available = tb_available_credits(port, NULL);
166 		credits = min(sw->max_pcie_credits, available);
167 
168 		if (credits < TB_MIN_PCIE_CREDITS)
169 			return -ENOSPC;
170 
171 		credits = max(TB_MIN_PCIE_CREDITS, credits);
172 	} else {
173 		if (tb_port_is_null(port))
174 			credits = port->bonded ? 32 : 16;
175 		else
176 			credits = 7;
177 	}
178 
179 	hop->initial_credits = credits;
180 	return 0;
181 }
182 
183 static int tb_pci_init_path(struct tb_path *path)
184 {
185 	struct tb_path_hop *hop;
186 
187 	path->egress_fc_enable = TB_PATH_SOURCE | TB_PATH_INTERNAL;
188 	path->egress_shared_buffer = TB_PATH_NONE;
189 	path->ingress_fc_enable = TB_PATH_ALL;
190 	path->ingress_shared_buffer = TB_PATH_NONE;
191 	path->priority = 3;
192 	path->weight = 1;
193 	path->drop_packages = 0;
194 
195 	tb_path_for_each_hop(path, hop) {
196 		int ret;
197 
198 		ret = tb_pci_init_credits(hop);
199 		if (ret)
200 			return ret;
201 	}
202 
203 	return 0;
204 }
205 
206 /**
207  * tb_tunnel_discover_pci() - Discover existing PCIe tunnels
208  * @tb: Pointer to the domain structure
209  * @down: PCIe downstream adapter
210  * @alloc_hopid: Allocate HopIDs from visited ports
211  *
212  * If @down adapter is active, follows the tunnel to the PCIe upstream
213  * adapter and back. Returns the discovered tunnel or %NULL if there was
214  * no tunnel.
215  */
216 struct tb_tunnel *tb_tunnel_discover_pci(struct tb *tb, struct tb_port *down,
217 					 bool alloc_hopid)
218 {
219 	struct tb_tunnel *tunnel;
220 	struct tb_path *path;
221 
222 	if (!tb_pci_port_is_enabled(down))
223 		return NULL;
224 
225 	tunnel = tb_tunnel_alloc(tb, 2, TB_TUNNEL_PCI);
226 	if (!tunnel)
227 		return NULL;
228 
229 	tunnel->activate = tb_pci_activate;
230 	tunnel->src_port = down;
231 
232 	/*
233 	 * Discover both paths even if they are not complete. We will
234 	 * clean them up by calling tb_tunnel_deactivate() below in that
235 	 * case.
236 	 */
237 	path = tb_path_discover(down, TB_PCI_HOPID, NULL, -1,
238 				&tunnel->dst_port, "PCIe Up", alloc_hopid);
239 	if (!path) {
240 		/* Just disable the downstream port */
241 		tb_pci_port_enable(down, false);
242 		goto err_free;
243 	}
244 	tunnel->paths[TB_PCI_PATH_UP] = path;
245 	if (tb_pci_init_path(tunnel->paths[TB_PCI_PATH_UP]))
246 		goto err_free;
247 
248 	path = tb_path_discover(tunnel->dst_port, -1, down, TB_PCI_HOPID, NULL,
249 				"PCIe Down", alloc_hopid);
250 	if (!path)
251 		goto err_deactivate;
252 	tunnel->paths[TB_PCI_PATH_DOWN] = path;
253 	if (tb_pci_init_path(tunnel->paths[TB_PCI_PATH_DOWN]))
254 		goto err_deactivate;
255 
256 	/* Validate that the tunnel is complete */
257 	if (!tb_port_is_pcie_up(tunnel->dst_port)) {
258 		tb_port_warn(tunnel->dst_port,
259 			     "path does not end on a PCIe adapter, cleaning up\n");
260 		goto err_deactivate;
261 	}
262 
263 	if (down != tunnel->src_port) {
264 		tb_tunnel_warn(tunnel, "path is not complete, cleaning up\n");
265 		goto err_deactivate;
266 	}
267 
268 	if (!tb_pci_port_is_enabled(tunnel->dst_port)) {
269 		tb_tunnel_warn(tunnel,
270 			       "tunnel is not fully activated, cleaning up\n");
271 		goto err_deactivate;
272 	}
273 
274 	tb_tunnel_dbg(tunnel, "discovered\n");
275 	return tunnel;
276 
277 err_deactivate:
278 	tb_tunnel_deactivate(tunnel);
279 err_free:
280 	tb_tunnel_free(tunnel);
281 
282 	return NULL;
283 }
284 
285 /**
286  * tb_tunnel_alloc_pci() - allocate a pci tunnel
287  * @tb: Pointer to the domain structure
288  * @up: PCIe upstream adapter port
289  * @down: PCIe downstream adapter port
290  *
291  * Allocate a PCI tunnel. The ports must be of type TB_TYPE_PCIE_UP and
292  * TB_TYPE_PCIE_DOWN.
293  *
294  * Return: Returns a tb_tunnel on success or NULL on failure.
295  */
296 struct tb_tunnel *tb_tunnel_alloc_pci(struct tb *tb, struct tb_port *up,
297 				      struct tb_port *down)
298 {
299 	struct tb_tunnel *tunnel;
300 	struct tb_path *path;
301 
302 	tunnel = tb_tunnel_alloc(tb, 2, TB_TUNNEL_PCI);
303 	if (!tunnel)
304 		return NULL;
305 
306 	tunnel->activate = tb_pci_activate;
307 	tunnel->src_port = down;
308 	tunnel->dst_port = up;
309 
310 	path = tb_path_alloc(tb, down, TB_PCI_HOPID, up, TB_PCI_HOPID, 0,
311 			     "PCIe Down");
312 	if (!path)
313 		goto err_free;
314 	tunnel->paths[TB_PCI_PATH_DOWN] = path;
315 	if (tb_pci_init_path(path))
316 		goto err_free;
317 
318 	path = tb_path_alloc(tb, up, TB_PCI_HOPID, down, TB_PCI_HOPID, 0,
319 			     "PCIe Up");
320 	if (!path)
321 		goto err_free;
322 	tunnel->paths[TB_PCI_PATH_UP] = path;
323 	if (tb_pci_init_path(path))
324 		goto err_free;
325 
326 	return tunnel;
327 
328 err_free:
329 	tb_tunnel_free(tunnel);
330 	return NULL;
331 }
332 
333 static bool tb_dp_is_usb4(const struct tb_switch *sw)
334 {
335 	/* Titan Ridge DP adapters need the same treatment as USB4 */
336 	return tb_switch_is_usb4(sw) || tb_switch_is_titan_ridge(sw);
337 }
338 
339 static int tb_dp_cm_handshake(struct tb_port *in, struct tb_port *out)
340 {
341 	int timeout = 10;
342 	u32 val;
343 	int ret;
344 
345 	/* Both ends need to support this */
346 	if (!tb_dp_is_usb4(in->sw) || !tb_dp_is_usb4(out->sw))
347 		return 0;
348 
349 	ret = tb_port_read(out, &val, TB_CFG_PORT,
350 			   out->cap_adap + DP_STATUS_CTRL, 1);
351 	if (ret)
352 		return ret;
353 
354 	val |= DP_STATUS_CTRL_UF | DP_STATUS_CTRL_CMHS;
355 
356 	ret = tb_port_write(out, &val, TB_CFG_PORT,
357 			    out->cap_adap + DP_STATUS_CTRL, 1);
358 	if (ret)
359 		return ret;
360 
361 	do {
362 		ret = tb_port_read(out, &val, TB_CFG_PORT,
363 				   out->cap_adap + DP_STATUS_CTRL, 1);
364 		if (ret)
365 			return ret;
366 		if (!(val & DP_STATUS_CTRL_CMHS))
367 			return 0;
368 		usleep_range(10, 100);
369 	} while (timeout--);
370 
371 	return -ETIMEDOUT;
372 }
373 
374 static inline u32 tb_dp_cap_get_rate(u32 val)
375 {
376 	u32 rate = (val & DP_COMMON_CAP_RATE_MASK) >> DP_COMMON_CAP_RATE_SHIFT;
377 
378 	switch (rate) {
379 	case DP_COMMON_CAP_RATE_RBR:
380 		return 1620;
381 	case DP_COMMON_CAP_RATE_HBR:
382 		return 2700;
383 	case DP_COMMON_CAP_RATE_HBR2:
384 		return 5400;
385 	case DP_COMMON_CAP_RATE_HBR3:
386 		return 8100;
387 	default:
388 		return 0;
389 	}
390 }
391 
392 static inline u32 tb_dp_cap_set_rate(u32 val, u32 rate)
393 {
394 	val &= ~DP_COMMON_CAP_RATE_MASK;
395 	switch (rate) {
396 	default:
397 		WARN(1, "invalid rate %u passed, defaulting to 1620 MB/s\n", rate);
398 		fallthrough;
399 	case 1620:
400 		val |= DP_COMMON_CAP_RATE_RBR << DP_COMMON_CAP_RATE_SHIFT;
401 		break;
402 	case 2700:
403 		val |= DP_COMMON_CAP_RATE_HBR << DP_COMMON_CAP_RATE_SHIFT;
404 		break;
405 	case 5400:
406 		val |= DP_COMMON_CAP_RATE_HBR2 << DP_COMMON_CAP_RATE_SHIFT;
407 		break;
408 	case 8100:
409 		val |= DP_COMMON_CAP_RATE_HBR3 << DP_COMMON_CAP_RATE_SHIFT;
410 		break;
411 	}
412 	return val;
413 }
414 
415 static inline u32 tb_dp_cap_get_lanes(u32 val)
416 {
417 	u32 lanes = (val & DP_COMMON_CAP_LANES_MASK) >> DP_COMMON_CAP_LANES_SHIFT;
418 
419 	switch (lanes) {
420 	case DP_COMMON_CAP_1_LANE:
421 		return 1;
422 	case DP_COMMON_CAP_2_LANES:
423 		return 2;
424 	case DP_COMMON_CAP_4_LANES:
425 		return 4;
426 	default:
427 		return 0;
428 	}
429 }
430 
431 static inline u32 tb_dp_cap_set_lanes(u32 val, u32 lanes)
432 {
433 	val &= ~DP_COMMON_CAP_LANES_MASK;
434 	switch (lanes) {
435 	default:
436 		WARN(1, "invalid number of lanes %u passed, defaulting to 1\n",
437 		     lanes);
438 		fallthrough;
439 	case 1:
440 		val |= DP_COMMON_CAP_1_LANE << DP_COMMON_CAP_LANES_SHIFT;
441 		break;
442 	case 2:
443 		val |= DP_COMMON_CAP_2_LANES << DP_COMMON_CAP_LANES_SHIFT;
444 		break;
445 	case 4:
446 		val |= DP_COMMON_CAP_4_LANES << DP_COMMON_CAP_LANES_SHIFT;
447 		break;
448 	}
449 	return val;
450 }
451 
452 static unsigned int tb_dp_bandwidth(unsigned int rate, unsigned int lanes)
453 {
454 	/* Tunneling removes the DP 8b/10b encoding */
455 	return rate * lanes * 8 / 10;
456 }
457 
458 static int tb_dp_reduce_bandwidth(int max_bw, u32 in_rate, u32 in_lanes,
459 				  u32 out_rate, u32 out_lanes, u32 *new_rate,
460 				  u32 *new_lanes)
461 {
462 	static const u32 dp_bw[][2] = {
463 		/* Mb/s, lanes */
464 		{ 8100, 4 }, /* 25920 Mb/s */
465 		{ 5400, 4 }, /* 17280 Mb/s */
466 		{ 8100, 2 }, /* 12960 Mb/s */
467 		{ 2700, 4 }, /* 8640 Mb/s */
468 		{ 5400, 2 }, /* 8640 Mb/s */
469 		{ 8100, 1 }, /* 6480 Mb/s */
470 		{ 1620, 4 }, /* 5184 Mb/s */
471 		{ 5400, 1 }, /* 4320 Mb/s */
472 		{ 2700, 2 }, /* 4320 Mb/s */
473 		{ 1620, 2 }, /* 2592 Mb/s */
474 		{ 2700, 1 }, /* 2160 Mb/s */
475 		{ 1620, 1 }, /* 1296 Mb/s */
476 	};
477 	unsigned int i;
478 
479 	/*
480 	 * Find a combination that can fit into max_bw and does not
481 	 * exceed the maximum rate and lanes supported by the DP OUT and
482 	 * DP IN adapters.
483 	 */
484 	for (i = 0; i < ARRAY_SIZE(dp_bw); i++) {
485 		if (dp_bw[i][0] > out_rate || dp_bw[i][1] > out_lanes)
486 			continue;
487 
488 		if (dp_bw[i][0] > in_rate || dp_bw[i][1] > in_lanes)
489 			continue;
490 
491 		if (tb_dp_bandwidth(dp_bw[i][0], dp_bw[i][1]) <= max_bw) {
492 			*new_rate = dp_bw[i][0];
493 			*new_lanes = dp_bw[i][1];
494 			return 0;
495 		}
496 	}
497 
498 	return -ENOSR;
499 }
500 
501 static int tb_dp_xchg_caps(struct tb_tunnel *tunnel)
502 {
503 	u32 out_dp_cap, out_rate, out_lanes, in_dp_cap, in_rate, in_lanes, bw;
504 	struct tb_port *out = tunnel->dst_port;
505 	struct tb_port *in = tunnel->src_port;
506 	int ret, max_bw;
507 
508 	/*
509 	 * Copy DP_LOCAL_CAP register to DP_REMOTE_CAP register for
510 	 * newer generation hardware.
511 	 */
512 	if (in->sw->generation < 2 || out->sw->generation < 2)
513 		return 0;
514 
515 	/*
516 	 * Perform connection manager handshake between IN and OUT ports
517 	 * before capabilities exchange can take place.
518 	 */
519 	ret = tb_dp_cm_handshake(in, out);
520 	if (ret)
521 		return ret;
522 
523 	/* Read both DP_LOCAL_CAP registers */
524 	ret = tb_port_read(in, &in_dp_cap, TB_CFG_PORT,
525 			   in->cap_adap + DP_LOCAL_CAP, 1);
526 	if (ret)
527 		return ret;
528 
529 	ret = tb_port_read(out, &out_dp_cap, TB_CFG_PORT,
530 			   out->cap_adap + DP_LOCAL_CAP, 1);
531 	if (ret)
532 		return ret;
533 
534 	/* Write IN local caps to OUT remote caps */
535 	ret = tb_port_write(out, &in_dp_cap, TB_CFG_PORT,
536 			    out->cap_adap + DP_REMOTE_CAP, 1);
537 	if (ret)
538 		return ret;
539 
540 	in_rate = tb_dp_cap_get_rate(in_dp_cap);
541 	in_lanes = tb_dp_cap_get_lanes(in_dp_cap);
542 	tb_port_dbg(in, "maximum supported bandwidth %u Mb/s x%u = %u Mb/s\n",
543 		    in_rate, in_lanes, tb_dp_bandwidth(in_rate, in_lanes));
544 
545 	/*
546 	 * If the tunnel bandwidth is limited (max_bw is set) then see
547 	 * if we need to reduce bandwidth to fit there.
548 	 */
549 	out_rate = tb_dp_cap_get_rate(out_dp_cap);
550 	out_lanes = tb_dp_cap_get_lanes(out_dp_cap);
551 	bw = tb_dp_bandwidth(out_rate, out_lanes);
552 	tb_port_dbg(out, "maximum supported bandwidth %u Mb/s x%u = %u Mb/s\n",
553 		    out_rate, out_lanes, bw);
554 
555 	if (in->sw->config.depth < out->sw->config.depth)
556 		max_bw = tunnel->max_down;
557 	else
558 		max_bw = tunnel->max_up;
559 
560 	if (max_bw && bw > max_bw) {
561 		u32 new_rate, new_lanes, new_bw;
562 
563 		ret = tb_dp_reduce_bandwidth(max_bw, in_rate, in_lanes,
564 					     out_rate, out_lanes, &new_rate,
565 					     &new_lanes);
566 		if (ret) {
567 			tb_port_info(out, "not enough bandwidth for DP tunnel\n");
568 			return ret;
569 		}
570 
571 		new_bw = tb_dp_bandwidth(new_rate, new_lanes);
572 		tb_port_dbg(out, "bandwidth reduced to %u Mb/s x%u = %u Mb/s\n",
573 			    new_rate, new_lanes, new_bw);
574 
575 		/*
576 		 * Set new rate and number of lanes before writing it to
577 		 * the IN port remote caps.
578 		 */
579 		out_dp_cap = tb_dp_cap_set_rate(out_dp_cap, new_rate);
580 		out_dp_cap = tb_dp_cap_set_lanes(out_dp_cap, new_lanes);
581 	}
582 
583 	/*
584 	 * Titan Ridge does not disable AUX timers when it gets
585 	 * SET_CONFIG with SET_LTTPR_MODE set. This causes problems with
586 	 * DP tunneling.
587 	 */
588 	if (tb_route(out->sw) && tb_switch_is_titan_ridge(out->sw)) {
589 		out_dp_cap |= DP_COMMON_CAP_LTTPR_NS;
590 		tb_port_dbg(out, "disabling LTTPR\n");
591 	}
592 
593 	return tb_port_write(in, &out_dp_cap, TB_CFG_PORT,
594 			     in->cap_adap + DP_REMOTE_CAP, 1);
595 }
596 
597 static int tb_dp_activate(struct tb_tunnel *tunnel, bool active)
598 {
599 	int ret;
600 
601 	if (active) {
602 		struct tb_path **paths;
603 		int last;
604 
605 		paths = tunnel->paths;
606 		last = paths[TB_DP_VIDEO_PATH_OUT]->path_length - 1;
607 
608 		tb_dp_port_set_hops(tunnel->src_port,
609 			paths[TB_DP_VIDEO_PATH_OUT]->hops[0].in_hop_index,
610 			paths[TB_DP_AUX_PATH_OUT]->hops[0].in_hop_index,
611 			paths[TB_DP_AUX_PATH_IN]->hops[last].next_hop_index);
612 
613 		tb_dp_port_set_hops(tunnel->dst_port,
614 			paths[TB_DP_VIDEO_PATH_OUT]->hops[last].next_hop_index,
615 			paths[TB_DP_AUX_PATH_IN]->hops[0].in_hop_index,
616 			paths[TB_DP_AUX_PATH_OUT]->hops[last].next_hop_index);
617 	} else {
618 		tb_dp_port_hpd_clear(tunnel->src_port);
619 		tb_dp_port_set_hops(tunnel->src_port, 0, 0, 0);
620 		if (tb_port_is_dpout(tunnel->dst_port))
621 			tb_dp_port_set_hops(tunnel->dst_port, 0, 0, 0);
622 	}
623 
624 	ret = tb_dp_port_enable(tunnel->src_port, active);
625 	if (ret)
626 		return ret;
627 
628 	if (tb_port_is_dpout(tunnel->dst_port))
629 		return tb_dp_port_enable(tunnel->dst_port, active);
630 
631 	return 0;
632 }
633 
634 static int tb_dp_consumed_bandwidth(struct tb_tunnel *tunnel, int *consumed_up,
635 				    int *consumed_down)
636 {
637 	struct tb_port *in = tunnel->src_port;
638 	const struct tb_switch *sw = in->sw;
639 	u32 val, rate = 0, lanes = 0;
640 	int ret;
641 
642 	if (tb_dp_is_usb4(sw)) {
643 		int timeout = 20;
644 
645 		/*
646 		 * Wait for DPRX done. Normally it should be already set
647 		 * for active tunnel.
648 		 */
649 		do {
650 			ret = tb_port_read(in, &val, TB_CFG_PORT,
651 					   in->cap_adap + DP_COMMON_CAP, 1);
652 			if (ret)
653 				return ret;
654 
655 			if (val & DP_COMMON_CAP_DPRX_DONE) {
656 				rate = tb_dp_cap_get_rate(val);
657 				lanes = tb_dp_cap_get_lanes(val);
658 				break;
659 			}
660 			msleep(250);
661 		} while (timeout--);
662 
663 		if (!timeout)
664 			return -ETIMEDOUT;
665 	} else if (sw->generation >= 2) {
666 		/*
667 		 * Read from the copied remote cap so that we take into
668 		 * account if capabilities were reduced during exchange.
669 		 */
670 		ret = tb_port_read(in, &val, TB_CFG_PORT,
671 				   in->cap_adap + DP_REMOTE_CAP, 1);
672 		if (ret)
673 			return ret;
674 
675 		rate = tb_dp_cap_get_rate(val);
676 		lanes = tb_dp_cap_get_lanes(val);
677 	} else {
678 		/* No bandwidth management for legacy devices  */
679 		*consumed_up = 0;
680 		*consumed_down = 0;
681 		return 0;
682 	}
683 
684 	if (in->sw->config.depth < tunnel->dst_port->sw->config.depth) {
685 		*consumed_up = 0;
686 		*consumed_down = tb_dp_bandwidth(rate, lanes);
687 	} else {
688 		*consumed_up = tb_dp_bandwidth(rate, lanes);
689 		*consumed_down = 0;
690 	}
691 
692 	return 0;
693 }
694 
695 static void tb_dp_init_aux_credits(struct tb_path_hop *hop)
696 {
697 	struct tb_port *port = hop->in_port;
698 	struct tb_switch *sw = port->sw;
699 
700 	if (tb_port_use_credit_allocation(port))
701 		hop->initial_credits = sw->min_dp_aux_credits;
702 	else
703 		hop->initial_credits = 1;
704 }
705 
706 static void tb_dp_init_aux_path(struct tb_path *path)
707 {
708 	struct tb_path_hop *hop;
709 
710 	path->egress_fc_enable = TB_PATH_SOURCE | TB_PATH_INTERNAL;
711 	path->egress_shared_buffer = TB_PATH_NONE;
712 	path->ingress_fc_enable = TB_PATH_ALL;
713 	path->ingress_shared_buffer = TB_PATH_NONE;
714 	path->priority = 2;
715 	path->weight = 1;
716 
717 	tb_path_for_each_hop(path, hop)
718 		tb_dp_init_aux_credits(hop);
719 }
720 
721 static int tb_dp_init_video_credits(struct tb_path_hop *hop)
722 {
723 	struct tb_port *port = hop->in_port;
724 	struct tb_switch *sw = port->sw;
725 
726 	if (tb_port_use_credit_allocation(port)) {
727 		unsigned int nfc_credits;
728 		size_t max_dp_streams;
729 
730 		tb_available_credits(port, &max_dp_streams);
731 		/*
732 		 * Read the number of currently allocated NFC credits
733 		 * from the lane adapter. Since we only use them for DP
734 		 * tunneling we can use that to figure out how many DP
735 		 * tunnels already go through the lane adapter.
736 		 */
737 		nfc_credits = port->config.nfc_credits &
738 				ADP_CS_4_NFC_BUFFERS_MASK;
739 		if (nfc_credits / sw->min_dp_main_credits > max_dp_streams)
740 			return -ENOSPC;
741 
742 		hop->nfc_credits = sw->min_dp_main_credits;
743 	} else {
744 		hop->nfc_credits = min(port->total_credits - 2, 12U);
745 	}
746 
747 	return 0;
748 }
749 
750 static int tb_dp_init_video_path(struct tb_path *path)
751 {
752 	struct tb_path_hop *hop;
753 
754 	path->egress_fc_enable = TB_PATH_NONE;
755 	path->egress_shared_buffer = TB_PATH_NONE;
756 	path->ingress_fc_enable = TB_PATH_NONE;
757 	path->ingress_shared_buffer = TB_PATH_NONE;
758 	path->priority = 1;
759 	path->weight = 1;
760 
761 	tb_path_for_each_hop(path, hop) {
762 		int ret;
763 
764 		ret = tb_dp_init_video_credits(hop);
765 		if (ret)
766 			return ret;
767 	}
768 
769 	return 0;
770 }
771 
772 /**
773  * tb_tunnel_discover_dp() - Discover existing Display Port tunnels
774  * @tb: Pointer to the domain structure
775  * @in: DP in adapter
776  * @alloc_hopid: Allocate HopIDs from visited ports
777  *
778  * If @in adapter is active, follows the tunnel to the DP out adapter
779  * and back. Returns the discovered tunnel or %NULL if there was no
780  * tunnel.
781  *
782  * Return: DP tunnel or %NULL if no tunnel found.
783  */
784 struct tb_tunnel *tb_tunnel_discover_dp(struct tb *tb, struct tb_port *in,
785 					bool alloc_hopid)
786 {
787 	struct tb_tunnel *tunnel;
788 	struct tb_port *port;
789 	struct tb_path *path;
790 
791 	if (!tb_dp_port_is_enabled(in))
792 		return NULL;
793 
794 	tunnel = tb_tunnel_alloc(tb, 3, TB_TUNNEL_DP);
795 	if (!tunnel)
796 		return NULL;
797 
798 	tunnel->init = tb_dp_xchg_caps;
799 	tunnel->activate = tb_dp_activate;
800 	tunnel->consumed_bandwidth = tb_dp_consumed_bandwidth;
801 	tunnel->src_port = in;
802 
803 	path = tb_path_discover(in, TB_DP_VIDEO_HOPID, NULL, -1,
804 				&tunnel->dst_port, "Video", alloc_hopid);
805 	if (!path) {
806 		/* Just disable the DP IN port */
807 		tb_dp_port_enable(in, false);
808 		goto err_free;
809 	}
810 	tunnel->paths[TB_DP_VIDEO_PATH_OUT] = path;
811 	if (tb_dp_init_video_path(tunnel->paths[TB_DP_VIDEO_PATH_OUT]))
812 		goto err_free;
813 
814 	path = tb_path_discover(in, TB_DP_AUX_TX_HOPID, NULL, -1, NULL, "AUX TX",
815 				alloc_hopid);
816 	if (!path)
817 		goto err_deactivate;
818 	tunnel->paths[TB_DP_AUX_PATH_OUT] = path;
819 	tb_dp_init_aux_path(tunnel->paths[TB_DP_AUX_PATH_OUT]);
820 
821 	path = tb_path_discover(tunnel->dst_port, -1, in, TB_DP_AUX_RX_HOPID,
822 				&port, "AUX RX", alloc_hopid);
823 	if (!path)
824 		goto err_deactivate;
825 	tunnel->paths[TB_DP_AUX_PATH_IN] = path;
826 	tb_dp_init_aux_path(tunnel->paths[TB_DP_AUX_PATH_IN]);
827 
828 	/* Validate that the tunnel is complete */
829 	if (!tb_port_is_dpout(tunnel->dst_port)) {
830 		tb_port_warn(in, "path does not end on a DP adapter, cleaning up\n");
831 		goto err_deactivate;
832 	}
833 
834 	if (!tb_dp_port_is_enabled(tunnel->dst_port))
835 		goto err_deactivate;
836 
837 	if (!tb_dp_port_hpd_is_active(tunnel->dst_port))
838 		goto err_deactivate;
839 
840 	if (port != tunnel->src_port) {
841 		tb_tunnel_warn(tunnel, "path is not complete, cleaning up\n");
842 		goto err_deactivate;
843 	}
844 
845 	tb_tunnel_dbg(tunnel, "discovered\n");
846 	return tunnel;
847 
848 err_deactivate:
849 	tb_tunnel_deactivate(tunnel);
850 err_free:
851 	tb_tunnel_free(tunnel);
852 
853 	return NULL;
854 }
855 
856 /**
857  * tb_tunnel_alloc_dp() - allocate a Display Port tunnel
858  * @tb: Pointer to the domain structure
859  * @in: DP in adapter port
860  * @out: DP out adapter port
861  * @max_up: Maximum available upstream bandwidth for the DP tunnel (%0
862  *	    if not limited)
863  * @max_down: Maximum available downstream bandwidth for the DP tunnel
864  *	      (%0 if not limited)
865  *
866  * Allocates a tunnel between @in and @out that is capable of tunneling
867  * Display Port traffic.
868  *
869  * Return: Returns a tb_tunnel on success or NULL on failure.
870  */
871 struct tb_tunnel *tb_tunnel_alloc_dp(struct tb *tb, struct tb_port *in,
872 				     struct tb_port *out, int max_up,
873 				     int max_down)
874 {
875 	struct tb_tunnel *tunnel;
876 	struct tb_path **paths;
877 	struct tb_path *path;
878 
879 	if (WARN_ON(!in->cap_adap || !out->cap_adap))
880 		return NULL;
881 
882 	tunnel = tb_tunnel_alloc(tb, 3, TB_TUNNEL_DP);
883 	if (!tunnel)
884 		return NULL;
885 
886 	tunnel->init = tb_dp_xchg_caps;
887 	tunnel->activate = tb_dp_activate;
888 	tunnel->consumed_bandwidth = tb_dp_consumed_bandwidth;
889 	tunnel->src_port = in;
890 	tunnel->dst_port = out;
891 	tunnel->max_up = max_up;
892 	tunnel->max_down = max_down;
893 
894 	paths = tunnel->paths;
895 
896 	path = tb_path_alloc(tb, in, TB_DP_VIDEO_HOPID, out, TB_DP_VIDEO_HOPID,
897 			     1, "Video");
898 	if (!path)
899 		goto err_free;
900 	tb_dp_init_video_path(path);
901 	paths[TB_DP_VIDEO_PATH_OUT] = path;
902 
903 	path = tb_path_alloc(tb, in, TB_DP_AUX_TX_HOPID, out,
904 			     TB_DP_AUX_TX_HOPID, 1, "AUX TX");
905 	if (!path)
906 		goto err_free;
907 	tb_dp_init_aux_path(path);
908 	paths[TB_DP_AUX_PATH_OUT] = path;
909 
910 	path = tb_path_alloc(tb, out, TB_DP_AUX_RX_HOPID, in,
911 			     TB_DP_AUX_RX_HOPID, 1, "AUX RX");
912 	if (!path)
913 		goto err_free;
914 	tb_dp_init_aux_path(path);
915 	paths[TB_DP_AUX_PATH_IN] = path;
916 
917 	return tunnel;
918 
919 err_free:
920 	tb_tunnel_free(tunnel);
921 	return NULL;
922 }
923 
924 static unsigned int tb_dma_available_credits(const struct tb_port *port)
925 {
926 	const struct tb_switch *sw = port->sw;
927 	int credits;
928 
929 	credits = tb_available_credits(port, NULL);
930 	if (tb_acpi_may_tunnel_pcie())
931 		credits -= sw->max_pcie_credits;
932 	credits -= port->dma_credits;
933 
934 	return credits > 0 ? credits : 0;
935 }
936 
937 static int tb_dma_reserve_credits(struct tb_path_hop *hop, unsigned int credits)
938 {
939 	struct tb_port *port = hop->in_port;
940 
941 	if (tb_port_use_credit_allocation(port)) {
942 		unsigned int available = tb_dma_available_credits(port);
943 
944 		/*
945 		 * Need to have at least TB_MIN_DMA_CREDITS, otherwise
946 		 * DMA path cannot be established.
947 		 */
948 		if (available < TB_MIN_DMA_CREDITS)
949 			return -ENOSPC;
950 
951 		while (credits > available)
952 			credits--;
953 
954 		tb_port_dbg(port, "reserving %u credits for DMA path\n",
955 			    credits);
956 
957 		port->dma_credits += credits;
958 	} else {
959 		if (tb_port_is_null(port))
960 			credits = port->bonded ? 14 : 6;
961 		else
962 			credits = min(port->total_credits, credits);
963 	}
964 
965 	hop->initial_credits = credits;
966 	return 0;
967 }
968 
969 /* Path from lane adapter to NHI */
970 static int tb_dma_init_rx_path(struct tb_path *path, unsigned int credits)
971 {
972 	struct tb_path_hop *hop;
973 	unsigned int i, tmp;
974 
975 	path->egress_fc_enable = TB_PATH_SOURCE | TB_PATH_INTERNAL;
976 	path->ingress_fc_enable = TB_PATH_ALL;
977 	path->egress_shared_buffer = TB_PATH_NONE;
978 	path->ingress_shared_buffer = TB_PATH_NONE;
979 	path->priority = 5;
980 	path->weight = 1;
981 	path->clear_fc = true;
982 
983 	/*
984 	 * First lane adapter is the one connected to the remote host.
985 	 * We don't tunnel other traffic over this link so can use all
986 	 * the credits (except the ones reserved for control traffic).
987 	 */
988 	hop = &path->hops[0];
989 	tmp = min(tb_usable_credits(hop->in_port), credits);
990 	hop->initial_credits = tmp;
991 	hop->in_port->dma_credits += tmp;
992 
993 	for (i = 1; i < path->path_length; i++) {
994 		int ret;
995 
996 		ret = tb_dma_reserve_credits(&path->hops[i], credits);
997 		if (ret)
998 			return ret;
999 	}
1000 
1001 	return 0;
1002 }
1003 
1004 /* Path from NHI to lane adapter */
1005 static int tb_dma_init_tx_path(struct tb_path *path, unsigned int credits)
1006 {
1007 	struct tb_path_hop *hop;
1008 
1009 	path->egress_fc_enable = TB_PATH_ALL;
1010 	path->ingress_fc_enable = TB_PATH_ALL;
1011 	path->egress_shared_buffer = TB_PATH_NONE;
1012 	path->ingress_shared_buffer = TB_PATH_NONE;
1013 	path->priority = 5;
1014 	path->weight = 1;
1015 	path->clear_fc = true;
1016 
1017 	tb_path_for_each_hop(path, hop) {
1018 		int ret;
1019 
1020 		ret = tb_dma_reserve_credits(hop, credits);
1021 		if (ret)
1022 			return ret;
1023 	}
1024 
1025 	return 0;
1026 }
1027 
1028 static void tb_dma_release_credits(struct tb_path_hop *hop)
1029 {
1030 	struct tb_port *port = hop->in_port;
1031 
1032 	if (tb_port_use_credit_allocation(port)) {
1033 		port->dma_credits -= hop->initial_credits;
1034 
1035 		tb_port_dbg(port, "released %u DMA path credits\n",
1036 			    hop->initial_credits);
1037 	}
1038 }
1039 
1040 static void tb_dma_deinit_path(struct tb_path *path)
1041 {
1042 	struct tb_path_hop *hop;
1043 
1044 	tb_path_for_each_hop(path, hop)
1045 		tb_dma_release_credits(hop);
1046 }
1047 
1048 static void tb_dma_deinit(struct tb_tunnel *tunnel)
1049 {
1050 	int i;
1051 
1052 	for (i = 0; i < tunnel->npaths; i++) {
1053 		if (!tunnel->paths[i])
1054 			continue;
1055 		tb_dma_deinit_path(tunnel->paths[i]);
1056 	}
1057 }
1058 
1059 /**
1060  * tb_tunnel_alloc_dma() - allocate a DMA tunnel
1061  * @tb: Pointer to the domain structure
1062  * @nhi: Host controller port
1063  * @dst: Destination null port which the other domain is connected to
1064  * @transmit_path: HopID used for transmitting packets
1065  * @transmit_ring: NHI ring number used to send packets towards the
1066  *		   other domain. Set to %-1 if TX path is not needed.
1067  * @receive_path: HopID used for receiving packets
1068  * @receive_ring: NHI ring number used to receive packets from the
1069  *		  other domain. Set to %-1 if RX path is not needed.
1070  *
1071  * Return: Returns a tb_tunnel on success or NULL on failure.
1072  */
1073 struct tb_tunnel *tb_tunnel_alloc_dma(struct tb *tb, struct tb_port *nhi,
1074 				      struct tb_port *dst, int transmit_path,
1075 				      int transmit_ring, int receive_path,
1076 				      int receive_ring)
1077 {
1078 	struct tb_tunnel *tunnel;
1079 	size_t npaths = 0, i = 0;
1080 	struct tb_path *path;
1081 	int credits;
1082 
1083 	if (receive_ring > 0)
1084 		npaths++;
1085 	if (transmit_ring > 0)
1086 		npaths++;
1087 
1088 	if (WARN_ON(!npaths))
1089 		return NULL;
1090 
1091 	tunnel = tb_tunnel_alloc(tb, npaths, TB_TUNNEL_DMA);
1092 	if (!tunnel)
1093 		return NULL;
1094 
1095 	tunnel->src_port = nhi;
1096 	tunnel->dst_port = dst;
1097 	tunnel->deinit = tb_dma_deinit;
1098 
1099 	credits = min_not_zero(TB_DMA_CREDITS, nhi->sw->max_dma_credits);
1100 
1101 	if (receive_ring > 0) {
1102 		path = tb_path_alloc(tb, dst, receive_path, nhi, receive_ring, 0,
1103 				     "DMA RX");
1104 		if (!path)
1105 			goto err_free;
1106 		tunnel->paths[i++] = path;
1107 		if (tb_dma_init_rx_path(path, credits)) {
1108 			tb_tunnel_dbg(tunnel, "not enough buffers for RX path\n");
1109 			goto err_free;
1110 		}
1111 	}
1112 
1113 	if (transmit_ring > 0) {
1114 		path = tb_path_alloc(tb, nhi, transmit_ring, dst, transmit_path, 0,
1115 				     "DMA TX");
1116 		if (!path)
1117 			goto err_free;
1118 		tunnel->paths[i++] = path;
1119 		if (tb_dma_init_tx_path(path, credits)) {
1120 			tb_tunnel_dbg(tunnel, "not enough buffers for TX path\n");
1121 			goto err_free;
1122 		}
1123 	}
1124 
1125 	return tunnel;
1126 
1127 err_free:
1128 	tb_tunnel_free(tunnel);
1129 	return NULL;
1130 }
1131 
1132 /**
1133  * tb_tunnel_match_dma() - Match DMA tunnel
1134  * @tunnel: Tunnel to match
1135  * @transmit_path: HopID used for transmitting packets. Pass %-1 to ignore.
1136  * @transmit_ring: NHI ring number used to send packets towards the
1137  *		   other domain. Pass %-1 to ignore.
1138  * @receive_path: HopID used for receiving packets. Pass %-1 to ignore.
1139  * @receive_ring: NHI ring number used to receive packets from the
1140  *		  other domain. Pass %-1 to ignore.
1141  *
1142  * This function can be used to match specific DMA tunnel, if there are
1143  * multiple DMA tunnels going through the same XDomain connection.
1144  * Returns true if there is match and false otherwise.
1145  */
1146 bool tb_tunnel_match_dma(const struct tb_tunnel *tunnel, int transmit_path,
1147 			 int transmit_ring, int receive_path, int receive_ring)
1148 {
1149 	const struct tb_path *tx_path = NULL, *rx_path = NULL;
1150 	int i;
1151 
1152 	if (!receive_ring || !transmit_ring)
1153 		return false;
1154 
1155 	for (i = 0; i < tunnel->npaths; i++) {
1156 		const struct tb_path *path = tunnel->paths[i];
1157 
1158 		if (!path)
1159 			continue;
1160 
1161 		if (tb_port_is_nhi(path->hops[0].in_port))
1162 			tx_path = path;
1163 		else if (tb_port_is_nhi(path->hops[path->path_length - 1].out_port))
1164 			rx_path = path;
1165 	}
1166 
1167 	if (transmit_ring > 0 || transmit_path > 0) {
1168 		if (!tx_path)
1169 			return false;
1170 		if (transmit_ring > 0 &&
1171 		    (tx_path->hops[0].in_hop_index != transmit_ring))
1172 			return false;
1173 		if (transmit_path > 0 &&
1174 		    (tx_path->hops[tx_path->path_length - 1].next_hop_index != transmit_path))
1175 			return false;
1176 	}
1177 
1178 	if (receive_ring > 0 || receive_path > 0) {
1179 		if (!rx_path)
1180 			return false;
1181 		if (receive_path > 0 &&
1182 		    (rx_path->hops[0].in_hop_index != receive_path))
1183 			return false;
1184 		if (receive_ring > 0 &&
1185 		    (rx_path->hops[rx_path->path_length - 1].next_hop_index != receive_ring))
1186 			return false;
1187 	}
1188 
1189 	return true;
1190 }
1191 
1192 static int tb_usb3_max_link_rate(struct tb_port *up, struct tb_port *down)
1193 {
1194 	int ret, up_max_rate, down_max_rate;
1195 
1196 	ret = usb4_usb3_port_max_link_rate(up);
1197 	if (ret < 0)
1198 		return ret;
1199 	up_max_rate = ret;
1200 
1201 	ret = usb4_usb3_port_max_link_rate(down);
1202 	if (ret < 0)
1203 		return ret;
1204 	down_max_rate = ret;
1205 
1206 	return min(up_max_rate, down_max_rate);
1207 }
1208 
1209 static int tb_usb3_init(struct tb_tunnel *tunnel)
1210 {
1211 	tb_tunnel_dbg(tunnel, "allocating initial bandwidth %d/%d Mb/s\n",
1212 		      tunnel->allocated_up, tunnel->allocated_down);
1213 
1214 	return usb4_usb3_port_allocate_bandwidth(tunnel->src_port,
1215 						 &tunnel->allocated_up,
1216 						 &tunnel->allocated_down);
1217 }
1218 
1219 static int tb_usb3_activate(struct tb_tunnel *tunnel, bool activate)
1220 {
1221 	int res;
1222 
1223 	res = tb_usb3_port_enable(tunnel->src_port, activate);
1224 	if (res)
1225 		return res;
1226 
1227 	if (tb_port_is_usb3_up(tunnel->dst_port))
1228 		return tb_usb3_port_enable(tunnel->dst_port, activate);
1229 
1230 	return 0;
1231 }
1232 
1233 static int tb_usb3_consumed_bandwidth(struct tb_tunnel *tunnel,
1234 		int *consumed_up, int *consumed_down)
1235 {
1236 	int pcie_enabled = tb_acpi_may_tunnel_pcie();
1237 
1238 	/*
1239 	 * PCIe tunneling, if enabled, affects the USB3 bandwidth so
1240 	 * take that it into account here.
1241 	 */
1242 	*consumed_up = tunnel->allocated_up * (3 + pcie_enabled) / 3;
1243 	*consumed_down = tunnel->allocated_down * (3 + pcie_enabled) / 3;
1244 	return 0;
1245 }
1246 
1247 static int tb_usb3_release_unused_bandwidth(struct tb_tunnel *tunnel)
1248 {
1249 	int ret;
1250 
1251 	ret = usb4_usb3_port_release_bandwidth(tunnel->src_port,
1252 					       &tunnel->allocated_up,
1253 					       &tunnel->allocated_down);
1254 	if (ret)
1255 		return ret;
1256 
1257 	tb_tunnel_dbg(tunnel, "decreased bandwidth allocation to %d/%d Mb/s\n",
1258 		      tunnel->allocated_up, tunnel->allocated_down);
1259 	return 0;
1260 }
1261 
1262 static void tb_usb3_reclaim_available_bandwidth(struct tb_tunnel *tunnel,
1263 						int *available_up,
1264 						int *available_down)
1265 {
1266 	int ret, max_rate, allocate_up, allocate_down;
1267 
1268 	ret = usb4_usb3_port_actual_link_rate(tunnel->src_port);
1269 	if (ret < 0) {
1270 		tb_tunnel_warn(tunnel, "failed to read actual link rate\n");
1271 		return;
1272 	} else if (!ret) {
1273 		/* Use maximum link rate if the link valid is not set */
1274 		ret = usb4_usb3_port_max_link_rate(tunnel->src_port);
1275 		if (ret < 0) {
1276 			tb_tunnel_warn(tunnel, "failed to read maximum link rate\n");
1277 			return;
1278 		}
1279 	}
1280 
1281 	/*
1282 	 * 90% of the max rate can be allocated for isochronous
1283 	 * transfers.
1284 	 */
1285 	max_rate = ret * 90 / 100;
1286 
1287 	/* No need to reclaim if already at maximum */
1288 	if (tunnel->allocated_up >= max_rate &&
1289 	    tunnel->allocated_down >= max_rate)
1290 		return;
1291 
1292 	/* Don't go lower than what is already allocated */
1293 	allocate_up = min(max_rate, *available_up);
1294 	if (allocate_up < tunnel->allocated_up)
1295 		allocate_up = tunnel->allocated_up;
1296 
1297 	allocate_down = min(max_rate, *available_down);
1298 	if (allocate_down < tunnel->allocated_down)
1299 		allocate_down = tunnel->allocated_down;
1300 
1301 	/* If no changes no need to do more */
1302 	if (allocate_up == tunnel->allocated_up &&
1303 	    allocate_down == tunnel->allocated_down)
1304 		return;
1305 
1306 	ret = usb4_usb3_port_allocate_bandwidth(tunnel->src_port, &allocate_up,
1307 						&allocate_down);
1308 	if (ret) {
1309 		tb_tunnel_info(tunnel, "failed to allocate bandwidth\n");
1310 		return;
1311 	}
1312 
1313 	tunnel->allocated_up = allocate_up;
1314 	*available_up -= tunnel->allocated_up;
1315 
1316 	tunnel->allocated_down = allocate_down;
1317 	*available_down -= tunnel->allocated_down;
1318 
1319 	tb_tunnel_dbg(tunnel, "increased bandwidth allocation to %d/%d Mb/s\n",
1320 		      tunnel->allocated_up, tunnel->allocated_down);
1321 }
1322 
1323 static void tb_usb3_init_credits(struct tb_path_hop *hop)
1324 {
1325 	struct tb_port *port = hop->in_port;
1326 	struct tb_switch *sw = port->sw;
1327 	unsigned int credits;
1328 
1329 	if (tb_port_use_credit_allocation(port)) {
1330 		credits = sw->max_usb3_credits;
1331 	} else {
1332 		if (tb_port_is_null(port))
1333 			credits = port->bonded ? 32 : 16;
1334 		else
1335 			credits = 7;
1336 	}
1337 
1338 	hop->initial_credits = credits;
1339 }
1340 
1341 static void tb_usb3_init_path(struct tb_path *path)
1342 {
1343 	struct tb_path_hop *hop;
1344 
1345 	path->egress_fc_enable = TB_PATH_SOURCE | TB_PATH_INTERNAL;
1346 	path->egress_shared_buffer = TB_PATH_NONE;
1347 	path->ingress_fc_enable = TB_PATH_ALL;
1348 	path->ingress_shared_buffer = TB_PATH_NONE;
1349 	path->priority = 3;
1350 	path->weight = 3;
1351 	path->drop_packages = 0;
1352 
1353 	tb_path_for_each_hop(path, hop)
1354 		tb_usb3_init_credits(hop);
1355 }
1356 
1357 /**
1358  * tb_tunnel_discover_usb3() - Discover existing USB3 tunnels
1359  * @tb: Pointer to the domain structure
1360  * @down: USB3 downstream adapter
1361  * @alloc_hopid: Allocate HopIDs from visited ports
1362  *
1363  * If @down adapter is active, follows the tunnel to the USB3 upstream
1364  * adapter and back. Returns the discovered tunnel or %NULL if there was
1365  * no tunnel.
1366  */
1367 struct tb_tunnel *tb_tunnel_discover_usb3(struct tb *tb, struct tb_port *down,
1368 					  bool alloc_hopid)
1369 {
1370 	struct tb_tunnel *tunnel;
1371 	struct tb_path *path;
1372 
1373 	if (!tb_usb3_port_is_enabled(down))
1374 		return NULL;
1375 
1376 	tunnel = tb_tunnel_alloc(tb, 2, TB_TUNNEL_USB3);
1377 	if (!tunnel)
1378 		return NULL;
1379 
1380 	tunnel->activate = tb_usb3_activate;
1381 	tunnel->src_port = down;
1382 
1383 	/*
1384 	 * Discover both paths even if they are not complete. We will
1385 	 * clean them up by calling tb_tunnel_deactivate() below in that
1386 	 * case.
1387 	 */
1388 	path = tb_path_discover(down, TB_USB3_HOPID, NULL, -1,
1389 				&tunnel->dst_port, "USB3 Down", alloc_hopid);
1390 	if (!path) {
1391 		/* Just disable the downstream port */
1392 		tb_usb3_port_enable(down, false);
1393 		goto err_free;
1394 	}
1395 	tunnel->paths[TB_USB3_PATH_DOWN] = path;
1396 	tb_usb3_init_path(tunnel->paths[TB_USB3_PATH_DOWN]);
1397 
1398 	path = tb_path_discover(tunnel->dst_port, -1, down, TB_USB3_HOPID, NULL,
1399 				"USB3 Up", alloc_hopid);
1400 	if (!path)
1401 		goto err_deactivate;
1402 	tunnel->paths[TB_USB3_PATH_UP] = path;
1403 	tb_usb3_init_path(tunnel->paths[TB_USB3_PATH_UP]);
1404 
1405 	/* Validate that the tunnel is complete */
1406 	if (!tb_port_is_usb3_up(tunnel->dst_port)) {
1407 		tb_port_warn(tunnel->dst_port,
1408 			     "path does not end on an USB3 adapter, cleaning up\n");
1409 		goto err_deactivate;
1410 	}
1411 
1412 	if (down != tunnel->src_port) {
1413 		tb_tunnel_warn(tunnel, "path is not complete, cleaning up\n");
1414 		goto err_deactivate;
1415 	}
1416 
1417 	if (!tb_usb3_port_is_enabled(tunnel->dst_port)) {
1418 		tb_tunnel_warn(tunnel,
1419 			       "tunnel is not fully activated, cleaning up\n");
1420 		goto err_deactivate;
1421 	}
1422 
1423 	if (!tb_route(down->sw)) {
1424 		int ret;
1425 
1426 		/*
1427 		 * Read the initial bandwidth allocation for the first
1428 		 * hop tunnel.
1429 		 */
1430 		ret = usb4_usb3_port_allocated_bandwidth(down,
1431 			&tunnel->allocated_up, &tunnel->allocated_down);
1432 		if (ret)
1433 			goto err_deactivate;
1434 
1435 		tb_tunnel_dbg(tunnel, "currently allocated bandwidth %d/%d Mb/s\n",
1436 			      tunnel->allocated_up, tunnel->allocated_down);
1437 
1438 		tunnel->init = tb_usb3_init;
1439 		tunnel->consumed_bandwidth = tb_usb3_consumed_bandwidth;
1440 		tunnel->release_unused_bandwidth =
1441 			tb_usb3_release_unused_bandwidth;
1442 		tunnel->reclaim_available_bandwidth =
1443 			tb_usb3_reclaim_available_bandwidth;
1444 	}
1445 
1446 	tb_tunnel_dbg(tunnel, "discovered\n");
1447 	return tunnel;
1448 
1449 err_deactivate:
1450 	tb_tunnel_deactivate(tunnel);
1451 err_free:
1452 	tb_tunnel_free(tunnel);
1453 
1454 	return NULL;
1455 }
1456 
1457 /**
1458  * tb_tunnel_alloc_usb3() - allocate a USB3 tunnel
1459  * @tb: Pointer to the domain structure
1460  * @up: USB3 upstream adapter port
1461  * @down: USB3 downstream adapter port
1462  * @max_up: Maximum available upstream bandwidth for the USB3 tunnel (%0
1463  *	    if not limited).
1464  * @max_down: Maximum available downstream bandwidth for the USB3 tunnel
1465  *	      (%0 if not limited).
1466  *
1467  * Allocate an USB3 tunnel. The ports must be of type @TB_TYPE_USB3_UP and
1468  * @TB_TYPE_USB3_DOWN.
1469  *
1470  * Return: Returns a tb_tunnel on success or %NULL on failure.
1471  */
1472 struct tb_tunnel *tb_tunnel_alloc_usb3(struct tb *tb, struct tb_port *up,
1473 				       struct tb_port *down, int max_up,
1474 				       int max_down)
1475 {
1476 	struct tb_tunnel *tunnel;
1477 	struct tb_path *path;
1478 	int max_rate = 0;
1479 
1480 	/*
1481 	 * Check that we have enough bandwidth available for the new
1482 	 * USB3 tunnel.
1483 	 */
1484 	if (max_up > 0 || max_down > 0) {
1485 		max_rate = tb_usb3_max_link_rate(down, up);
1486 		if (max_rate < 0)
1487 			return NULL;
1488 
1489 		/* Only 90% can be allocated for USB3 isochronous transfers */
1490 		max_rate = max_rate * 90 / 100;
1491 		tb_port_dbg(up, "required bandwidth for USB3 tunnel %d Mb/s\n",
1492 			    max_rate);
1493 
1494 		if (max_rate > max_up || max_rate > max_down) {
1495 			tb_port_warn(up, "not enough bandwidth for USB3 tunnel\n");
1496 			return NULL;
1497 		}
1498 	}
1499 
1500 	tunnel = tb_tunnel_alloc(tb, 2, TB_TUNNEL_USB3);
1501 	if (!tunnel)
1502 		return NULL;
1503 
1504 	tunnel->activate = tb_usb3_activate;
1505 	tunnel->src_port = down;
1506 	tunnel->dst_port = up;
1507 	tunnel->max_up = max_up;
1508 	tunnel->max_down = max_down;
1509 
1510 	path = tb_path_alloc(tb, down, TB_USB3_HOPID, up, TB_USB3_HOPID, 0,
1511 			     "USB3 Down");
1512 	if (!path) {
1513 		tb_tunnel_free(tunnel);
1514 		return NULL;
1515 	}
1516 	tb_usb3_init_path(path);
1517 	tunnel->paths[TB_USB3_PATH_DOWN] = path;
1518 
1519 	path = tb_path_alloc(tb, up, TB_USB3_HOPID, down, TB_USB3_HOPID, 0,
1520 			     "USB3 Up");
1521 	if (!path) {
1522 		tb_tunnel_free(tunnel);
1523 		return NULL;
1524 	}
1525 	tb_usb3_init_path(path);
1526 	tunnel->paths[TB_USB3_PATH_UP] = path;
1527 
1528 	if (!tb_route(down->sw)) {
1529 		tunnel->allocated_up = max_rate;
1530 		tunnel->allocated_down = max_rate;
1531 
1532 		tunnel->init = tb_usb3_init;
1533 		tunnel->consumed_bandwidth = tb_usb3_consumed_bandwidth;
1534 		tunnel->release_unused_bandwidth =
1535 			tb_usb3_release_unused_bandwidth;
1536 		tunnel->reclaim_available_bandwidth =
1537 			tb_usb3_reclaim_available_bandwidth;
1538 	}
1539 
1540 	return tunnel;
1541 }
1542 
1543 /**
1544  * tb_tunnel_free() - free a tunnel
1545  * @tunnel: Tunnel to be freed
1546  *
1547  * Frees a tunnel. The tunnel does not need to be deactivated.
1548  */
1549 void tb_tunnel_free(struct tb_tunnel *tunnel)
1550 {
1551 	int i;
1552 
1553 	if (!tunnel)
1554 		return;
1555 
1556 	if (tunnel->deinit)
1557 		tunnel->deinit(tunnel);
1558 
1559 	for (i = 0; i < tunnel->npaths; i++) {
1560 		if (tunnel->paths[i])
1561 			tb_path_free(tunnel->paths[i]);
1562 	}
1563 
1564 	kfree(tunnel->paths);
1565 	kfree(tunnel);
1566 }
1567 
1568 /**
1569  * tb_tunnel_is_invalid - check whether an activated path is still valid
1570  * @tunnel: Tunnel to check
1571  */
1572 bool tb_tunnel_is_invalid(struct tb_tunnel *tunnel)
1573 {
1574 	int i;
1575 
1576 	for (i = 0; i < tunnel->npaths; i++) {
1577 		WARN_ON(!tunnel->paths[i]->activated);
1578 		if (tb_path_is_invalid(tunnel->paths[i]))
1579 			return true;
1580 	}
1581 
1582 	return false;
1583 }
1584 
1585 /**
1586  * tb_tunnel_restart() - activate a tunnel after a hardware reset
1587  * @tunnel: Tunnel to restart
1588  *
1589  * Return: 0 on success and negative errno in case if failure
1590  */
1591 int tb_tunnel_restart(struct tb_tunnel *tunnel)
1592 {
1593 	int res, i;
1594 
1595 	tb_tunnel_dbg(tunnel, "activating\n");
1596 
1597 	/*
1598 	 * Make sure all paths are properly disabled before enabling
1599 	 * them again.
1600 	 */
1601 	for (i = 0; i < tunnel->npaths; i++) {
1602 		if (tunnel->paths[i]->activated) {
1603 			tb_path_deactivate(tunnel->paths[i]);
1604 			tunnel->paths[i]->activated = false;
1605 		}
1606 	}
1607 
1608 	if (tunnel->init) {
1609 		res = tunnel->init(tunnel);
1610 		if (res)
1611 			return res;
1612 	}
1613 
1614 	for (i = 0; i < tunnel->npaths; i++) {
1615 		res = tb_path_activate(tunnel->paths[i]);
1616 		if (res)
1617 			goto err;
1618 	}
1619 
1620 	if (tunnel->activate) {
1621 		res = tunnel->activate(tunnel, true);
1622 		if (res)
1623 			goto err;
1624 	}
1625 
1626 	return 0;
1627 
1628 err:
1629 	tb_tunnel_warn(tunnel, "activation failed\n");
1630 	tb_tunnel_deactivate(tunnel);
1631 	return res;
1632 }
1633 
1634 /**
1635  * tb_tunnel_activate() - activate a tunnel
1636  * @tunnel: Tunnel to activate
1637  *
1638  * Return: Returns 0 on success or an error code on failure.
1639  */
1640 int tb_tunnel_activate(struct tb_tunnel *tunnel)
1641 {
1642 	int i;
1643 
1644 	for (i = 0; i < tunnel->npaths; i++) {
1645 		if (tunnel->paths[i]->activated) {
1646 			tb_tunnel_WARN(tunnel,
1647 				       "trying to activate an already activated tunnel\n");
1648 			return -EINVAL;
1649 		}
1650 	}
1651 
1652 	return tb_tunnel_restart(tunnel);
1653 }
1654 
1655 /**
1656  * tb_tunnel_deactivate() - deactivate a tunnel
1657  * @tunnel: Tunnel to deactivate
1658  */
1659 void tb_tunnel_deactivate(struct tb_tunnel *tunnel)
1660 {
1661 	int i;
1662 
1663 	tb_tunnel_dbg(tunnel, "deactivating\n");
1664 
1665 	if (tunnel->activate)
1666 		tunnel->activate(tunnel, false);
1667 
1668 	for (i = 0; i < tunnel->npaths; i++) {
1669 		if (tunnel->paths[i] && tunnel->paths[i]->activated)
1670 			tb_path_deactivate(tunnel->paths[i]);
1671 	}
1672 }
1673 
1674 /**
1675  * tb_tunnel_port_on_path() - Does the tunnel go through port
1676  * @tunnel: Tunnel to check
1677  * @port: Port to check
1678  *
1679  * Returns true if @tunnel goes through @port (direction does not matter),
1680  * false otherwise.
1681  */
1682 bool tb_tunnel_port_on_path(const struct tb_tunnel *tunnel,
1683 			    const struct tb_port *port)
1684 {
1685 	int i;
1686 
1687 	for (i = 0; i < tunnel->npaths; i++) {
1688 		if (!tunnel->paths[i])
1689 			continue;
1690 
1691 		if (tb_path_port_on_path(tunnel->paths[i], port))
1692 			return true;
1693 	}
1694 
1695 	return false;
1696 }
1697 
1698 static bool tb_tunnel_is_active(const struct tb_tunnel *tunnel)
1699 {
1700 	int i;
1701 
1702 	for (i = 0; i < tunnel->npaths; i++) {
1703 		if (!tunnel->paths[i])
1704 			return false;
1705 		if (!tunnel->paths[i]->activated)
1706 			return false;
1707 	}
1708 
1709 	return true;
1710 }
1711 
1712 /**
1713  * tb_tunnel_consumed_bandwidth() - Return bandwidth consumed by the tunnel
1714  * @tunnel: Tunnel to check
1715  * @consumed_up: Consumed bandwidth in Mb/s from @dst_port to @src_port.
1716  *		 Can be %NULL.
1717  * @consumed_down: Consumed bandwidth in Mb/s from @src_port to @dst_port.
1718  *		   Can be %NULL.
1719  *
1720  * Stores the amount of isochronous bandwidth @tunnel consumes in
1721  * @consumed_up and @consumed_down. In case of success returns %0,
1722  * negative errno otherwise.
1723  */
1724 int tb_tunnel_consumed_bandwidth(struct tb_tunnel *tunnel, int *consumed_up,
1725 				 int *consumed_down)
1726 {
1727 	int up_bw = 0, down_bw = 0;
1728 
1729 	if (!tb_tunnel_is_active(tunnel))
1730 		goto out;
1731 
1732 	if (tunnel->consumed_bandwidth) {
1733 		int ret;
1734 
1735 		ret = tunnel->consumed_bandwidth(tunnel, &up_bw, &down_bw);
1736 		if (ret)
1737 			return ret;
1738 
1739 		tb_tunnel_dbg(tunnel, "consumed bandwidth %d/%d Mb/s\n", up_bw,
1740 			      down_bw);
1741 	}
1742 
1743 out:
1744 	if (consumed_up)
1745 		*consumed_up = up_bw;
1746 	if (consumed_down)
1747 		*consumed_down = down_bw;
1748 
1749 	return 0;
1750 }
1751 
1752 /**
1753  * tb_tunnel_release_unused_bandwidth() - Release unused bandwidth
1754  * @tunnel: Tunnel whose unused bandwidth to release
1755  *
1756  * If tunnel supports dynamic bandwidth management (USB3 tunnels at the
1757  * moment) this function makes it to release all the unused bandwidth.
1758  *
1759  * Returns %0 in case of success and negative errno otherwise.
1760  */
1761 int tb_tunnel_release_unused_bandwidth(struct tb_tunnel *tunnel)
1762 {
1763 	if (!tb_tunnel_is_active(tunnel))
1764 		return 0;
1765 
1766 	if (tunnel->release_unused_bandwidth) {
1767 		int ret;
1768 
1769 		ret = tunnel->release_unused_bandwidth(tunnel);
1770 		if (ret)
1771 			return ret;
1772 	}
1773 
1774 	return 0;
1775 }
1776 
1777 /**
1778  * tb_tunnel_reclaim_available_bandwidth() - Reclaim available bandwidth
1779  * @tunnel: Tunnel reclaiming available bandwidth
1780  * @available_up: Available upstream bandwidth (in Mb/s)
1781  * @available_down: Available downstream bandwidth (in Mb/s)
1782  *
1783  * Reclaims bandwidth from @available_up and @available_down and updates
1784  * the variables accordingly (e.g decreases both according to what was
1785  * reclaimed by the tunnel). If nothing was reclaimed the values are
1786  * kept as is.
1787  */
1788 void tb_tunnel_reclaim_available_bandwidth(struct tb_tunnel *tunnel,
1789 					   int *available_up,
1790 					   int *available_down)
1791 {
1792 	if (!tb_tunnel_is_active(tunnel))
1793 		return;
1794 
1795 	if (tunnel->reclaim_available_bandwidth)
1796 		tunnel->reclaim_available_bandwidth(tunnel, available_up,
1797 						    available_down);
1798 }
1799