Merge remote-tracking branch 'stable/linux-5.15.y' into rpi-5.15.y
[platform/kernel/linux-rpi.git] / drivers / thunderbolt / tunnel.c
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         return tb_port_write(in, &out_dp_cap, TB_CFG_PORT,
584                              in->cap_adap + DP_REMOTE_CAP, 1);
585 }
586
587 static int tb_dp_activate(struct tb_tunnel *tunnel, bool active)
588 {
589         int ret;
590
591         if (active) {
592                 struct tb_path **paths;
593                 int last;
594
595                 paths = tunnel->paths;
596                 last = paths[TB_DP_VIDEO_PATH_OUT]->path_length - 1;
597
598                 tb_dp_port_set_hops(tunnel->src_port,
599                         paths[TB_DP_VIDEO_PATH_OUT]->hops[0].in_hop_index,
600                         paths[TB_DP_AUX_PATH_OUT]->hops[0].in_hop_index,
601                         paths[TB_DP_AUX_PATH_IN]->hops[last].next_hop_index);
602
603                 tb_dp_port_set_hops(tunnel->dst_port,
604                         paths[TB_DP_VIDEO_PATH_OUT]->hops[last].next_hop_index,
605                         paths[TB_DP_AUX_PATH_IN]->hops[0].in_hop_index,
606                         paths[TB_DP_AUX_PATH_OUT]->hops[last].next_hop_index);
607         } else {
608                 tb_dp_port_hpd_clear(tunnel->src_port);
609                 tb_dp_port_set_hops(tunnel->src_port, 0, 0, 0);
610                 if (tb_port_is_dpout(tunnel->dst_port))
611                         tb_dp_port_set_hops(tunnel->dst_port, 0, 0, 0);
612         }
613
614         ret = tb_dp_port_enable(tunnel->src_port, active);
615         if (ret)
616                 return ret;
617
618         if (tb_port_is_dpout(tunnel->dst_port))
619                 return tb_dp_port_enable(tunnel->dst_port, active);
620
621         return 0;
622 }
623
624 static int tb_dp_consumed_bandwidth(struct tb_tunnel *tunnel, int *consumed_up,
625                                     int *consumed_down)
626 {
627         struct tb_port *in = tunnel->src_port;
628         const struct tb_switch *sw = in->sw;
629         u32 val, rate = 0, lanes = 0;
630         int ret;
631
632         if (tb_dp_is_usb4(sw)) {
633                 int timeout = 20;
634
635                 /*
636                  * Wait for DPRX done. Normally it should be already set
637                  * for active tunnel.
638                  */
639                 do {
640                         ret = tb_port_read(in, &val, TB_CFG_PORT,
641                                            in->cap_adap + DP_COMMON_CAP, 1);
642                         if (ret)
643                                 return ret;
644
645                         if (val & DP_COMMON_CAP_DPRX_DONE) {
646                                 rate = tb_dp_cap_get_rate(val);
647                                 lanes = tb_dp_cap_get_lanes(val);
648                                 break;
649                         }
650                         msleep(250);
651                 } while (timeout--);
652
653                 if (!timeout)
654                         return -ETIMEDOUT;
655         } else if (sw->generation >= 2) {
656                 /*
657                  * Read from the copied remote cap so that we take into
658                  * account if capabilities were reduced during exchange.
659                  */
660                 ret = tb_port_read(in, &val, TB_CFG_PORT,
661                                    in->cap_adap + DP_REMOTE_CAP, 1);
662                 if (ret)
663                         return ret;
664
665                 rate = tb_dp_cap_get_rate(val);
666                 lanes = tb_dp_cap_get_lanes(val);
667         } else {
668                 /* No bandwidth management for legacy devices  */
669                 *consumed_up = 0;
670                 *consumed_down = 0;
671                 return 0;
672         }
673
674         if (in->sw->config.depth < tunnel->dst_port->sw->config.depth) {
675                 *consumed_up = 0;
676                 *consumed_down = tb_dp_bandwidth(rate, lanes);
677         } else {
678                 *consumed_up = tb_dp_bandwidth(rate, lanes);
679                 *consumed_down = 0;
680         }
681
682         return 0;
683 }
684
685 static void tb_dp_init_aux_credits(struct tb_path_hop *hop)
686 {
687         struct tb_port *port = hop->in_port;
688         struct tb_switch *sw = port->sw;
689
690         if (tb_port_use_credit_allocation(port))
691                 hop->initial_credits = sw->min_dp_aux_credits;
692         else
693                 hop->initial_credits = 1;
694 }
695
696 static void tb_dp_init_aux_path(struct tb_path *path)
697 {
698         struct tb_path_hop *hop;
699
700         path->egress_fc_enable = TB_PATH_SOURCE | TB_PATH_INTERNAL;
701         path->egress_shared_buffer = TB_PATH_NONE;
702         path->ingress_fc_enable = TB_PATH_ALL;
703         path->ingress_shared_buffer = TB_PATH_NONE;
704         path->priority = 2;
705         path->weight = 1;
706
707         tb_path_for_each_hop(path, hop)
708                 tb_dp_init_aux_credits(hop);
709 }
710
711 static int tb_dp_init_video_credits(struct tb_path_hop *hop)
712 {
713         struct tb_port *port = hop->in_port;
714         struct tb_switch *sw = port->sw;
715
716         if (tb_port_use_credit_allocation(port)) {
717                 unsigned int nfc_credits;
718                 size_t max_dp_streams;
719
720                 tb_available_credits(port, &max_dp_streams);
721                 /*
722                  * Read the number of currently allocated NFC credits
723                  * from the lane adapter. Since we only use them for DP
724                  * tunneling we can use that to figure out how many DP
725                  * tunnels already go through the lane adapter.
726                  */
727                 nfc_credits = port->config.nfc_credits &
728                                 ADP_CS_4_NFC_BUFFERS_MASK;
729                 if (nfc_credits / sw->min_dp_main_credits > max_dp_streams)
730                         return -ENOSPC;
731
732                 hop->nfc_credits = sw->min_dp_main_credits;
733         } else {
734                 hop->nfc_credits = min(port->total_credits - 2, 12U);
735         }
736
737         return 0;
738 }
739
740 static int tb_dp_init_video_path(struct tb_path *path)
741 {
742         struct tb_path_hop *hop;
743
744         path->egress_fc_enable = TB_PATH_NONE;
745         path->egress_shared_buffer = TB_PATH_NONE;
746         path->ingress_fc_enable = TB_PATH_NONE;
747         path->ingress_shared_buffer = TB_PATH_NONE;
748         path->priority = 1;
749         path->weight = 1;
750
751         tb_path_for_each_hop(path, hop) {
752                 int ret;
753
754                 ret = tb_dp_init_video_credits(hop);
755                 if (ret)
756                         return ret;
757         }
758
759         return 0;
760 }
761
762 /**
763  * tb_tunnel_discover_dp() - Discover existing Display Port tunnels
764  * @tb: Pointer to the domain structure
765  * @in: DP in adapter
766  * @alloc_hopid: Allocate HopIDs from visited ports
767  *
768  * If @in adapter is active, follows the tunnel to the DP out adapter
769  * and back. Returns the discovered tunnel or %NULL if there was no
770  * tunnel.
771  *
772  * Return: DP tunnel or %NULL if no tunnel found.
773  */
774 struct tb_tunnel *tb_tunnel_discover_dp(struct tb *tb, struct tb_port *in,
775                                         bool alloc_hopid)
776 {
777         struct tb_tunnel *tunnel;
778         struct tb_port *port;
779         struct tb_path *path;
780
781         if (!tb_dp_port_is_enabled(in))
782                 return NULL;
783
784         tunnel = tb_tunnel_alloc(tb, 3, TB_TUNNEL_DP);
785         if (!tunnel)
786                 return NULL;
787
788         tunnel->init = tb_dp_xchg_caps;
789         tunnel->activate = tb_dp_activate;
790         tunnel->consumed_bandwidth = tb_dp_consumed_bandwidth;
791         tunnel->src_port = in;
792
793         path = tb_path_discover(in, TB_DP_VIDEO_HOPID, NULL, -1,
794                                 &tunnel->dst_port, "Video", alloc_hopid);
795         if (!path) {
796                 /* Just disable the DP IN port */
797                 tb_dp_port_enable(in, false);
798                 goto err_free;
799         }
800         tunnel->paths[TB_DP_VIDEO_PATH_OUT] = path;
801         if (tb_dp_init_video_path(tunnel->paths[TB_DP_VIDEO_PATH_OUT]))
802                 goto err_free;
803
804         path = tb_path_discover(in, TB_DP_AUX_TX_HOPID, NULL, -1, NULL, "AUX TX",
805                                 alloc_hopid);
806         if (!path)
807                 goto err_deactivate;
808         tunnel->paths[TB_DP_AUX_PATH_OUT] = path;
809         tb_dp_init_aux_path(tunnel->paths[TB_DP_AUX_PATH_OUT]);
810
811         path = tb_path_discover(tunnel->dst_port, -1, in, TB_DP_AUX_RX_HOPID,
812                                 &port, "AUX RX", alloc_hopid);
813         if (!path)
814                 goto err_deactivate;
815         tunnel->paths[TB_DP_AUX_PATH_IN] = path;
816         tb_dp_init_aux_path(tunnel->paths[TB_DP_AUX_PATH_IN]);
817
818         /* Validate that the tunnel is complete */
819         if (!tb_port_is_dpout(tunnel->dst_port)) {
820                 tb_port_warn(in, "path does not end on a DP adapter, cleaning up\n");
821                 goto err_deactivate;
822         }
823
824         if (!tb_dp_port_is_enabled(tunnel->dst_port))
825                 goto err_deactivate;
826
827         if (!tb_dp_port_hpd_is_active(tunnel->dst_port))
828                 goto err_deactivate;
829
830         if (port != tunnel->src_port) {
831                 tb_tunnel_warn(tunnel, "path is not complete, cleaning up\n");
832                 goto err_deactivate;
833         }
834
835         tb_tunnel_dbg(tunnel, "discovered\n");
836         return tunnel;
837
838 err_deactivate:
839         tb_tunnel_deactivate(tunnel);
840 err_free:
841         tb_tunnel_free(tunnel);
842
843         return NULL;
844 }
845
846 /**
847  * tb_tunnel_alloc_dp() - allocate a Display Port tunnel
848  * @tb: Pointer to the domain structure
849  * @in: DP in adapter port
850  * @out: DP out adapter port
851  * @link_nr: Preferred lane adapter when the link is not bonded
852  * @max_up: Maximum available upstream bandwidth for the DP tunnel (%0
853  *          if not limited)
854  * @max_down: Maximum available downstream bandwidth for the DP tunnel
855  *            (%0 if not limited)
856  *
857  * Allocates a tunnel between @in and @out that is capable of tunneling
858  * Display Port traffic.
859  *
860  * Return: Returns a tb_tunnel on success or NULL on failure.
861  */
862 struct tb_tunnel *tb_tunnel_alloc_dp(struct tb *tb, struct tb_port *in,
863                                      struct tb_port *out, int link_nr,
864                                      int max_up, int max_down)
865 {
866         struct tb_tunnel *tunnel;
867         struct tb_path **paths;
868         struct tb_path *path;
869
870         if (WARN_ON(!in->cap_adap || !out->cap_adap))
871                 return NULL;
872
873         tunnel = tb_tunnel_alloc(tb, 3, TB_TUNNEL_DP);
874         if (!tunnel)
875                 return NULL;
876
877         tunnel->init = tb_dp_xchg_caps;
878         tunnel->activate = tb_dp_activate;
879         tunnel->consumed_bandwidth = tb_dp_consumed_bandwidth;
880         tunnel->src_port = in;
881         tunnel->dst_port = out;
882         tunnel->max_up = max_up;
883         tunnel->max_down = max_down;
884
885         paths = tunnel->paths;
886
887         path = tb_path_alloc(tb, in, TB_DP_VIDEO_HOPID, out, TB_DP_VIDEO_HOPID,
888                              link_nr, "Video");
889         if (!path)
890                 goto err_free;
891         tb_dp_init_video_path(path);
892         paths[TB_DP_VIDEO_PATH_OUT] = path;
893
894         path = tb_path_alloc(tb, in, TB_DP_AUX_TX_HOPID, out,
895                              TB_DP_AUX_TX_HOPID, link_nr, "AUX TX");
896         if (!path)
897                 goto err_free;
898         tb_dp_init_aux_path(path);
899         paths[TB_DP_AUX_PATH_OUT] = path;
900
901         path = tb_path_alloc(tb, out, TB_DP_AUX_RX_HOPID, in,
902                              TB_DP_AUX_RX_HOPID, link_nr, "AUX RX");
903         if (!path)
904                 goto err_free;
905         tb_dp_init_aux_path(path);
906         paths[TB_DP_AUX_PATH_IN] = path;
907
908         return tunnel;
909
910 err_free:
911         tb_tunnel_free(tunnel);
912         return NULL;
913 }
914
915 static unsigned int tb_dma_available_credits(const struct tb_port *port)
916 {
917         const struct tb_switch *sw = port->sw;
918         int credits;
919
920         credits = tb_available_credits(port, NULL);
921         if (tb_acpi_may_tunnel_pcie())
922                 credits -= sw->max_pcie_credits;
923         credits -= port->dma_credits;
924
925         return credits > 0 ? credits : 0;
926 }
927
928 static int tb_dma_reserve_credits(struct tb_path_hop *hop, unsigned int credits)
929 {
930         struct tb_port *port = hop->in_port;
931
932         if (tb_port_use_credit_allocation(port)) {
933                 unsigned int available = tb_dma_available_credits(port);
934
935                 /*
936                  * Need to have at least TB_MIN_DMA_CREDITS, otherwise
937                  * DMA path cannot be established.
938                  */
939                 if (available < TB_MIN_DMA_CREDITS)
940                         return -ENOSPC;
941
942                 while (credits > available)
943                         credits--;
944
945                 tb_port_dbg(port, "reserving %u credits for DMA path\n",
946                             credits);
947
948                 port->dma_credits += credits;
949         } else {
950                 if (tb_port_is_null(port))
951                         credits = port->bonded ? 14 : 6;
952                 else
953                         credits = min(port->total_credits, credits);
954         }
955
956         hop->initial_credits = credits;
957         return 0;
958 }
959
960 /* Path from lane adapter to NHI */
961 static int tb_dma_init_rx_path(struct tb_path *path, unsigned int credits)
962 {
963         struct tb_path_hop *hop;
964         unsigned int i, tmp;
965
966         path->egress_fc_enable = TB_PATH_SOURCE | TB_PATH_INTERNAL;
967         path->ingress_fc_enable = TB_PATH_ALL;
968         path->egress_shared_buffer = TB_PATH_NONE;
969         path->ingress_shared_buffer = TB_PATH_NONE;
970         path->priority = 5;
971         path->weight = 1;
972         path->clear_fc = true;
973
974         /*
975          * First lane adapter is the one connected to the remote host.
976          * We don't tunnel other traffic over this link so can use all
977          * the credits (except the ones reserved for control traffic).
978          */
979         hop = &path->hops[0];
980         tmp = min(tb_usable_credits(hop->in_port), credits);
981         hop->initial_credits = tmp;
982         hop->in_port->dma_credits += tmp;
983
984         for (i = 1; i < path->path_length; i++) {
985                 int ret;
986
987                 ret = tb_dma_reserve_credits(&path->hops[i], credits);
988                 if (ret)
989                         return ret;
990         }
991
992         return 0;
993 }
994
995 /* Path from NHI to lane adapter */
996 static int tb_dma_init_tx_path(struct tb_path *path, unsigned int credits)
997 {
998         struct tb_path_hop *hop;
999
1000         path->egress_fc_enable = TB_PATH_ALL;
1001         path->ingress_fc_enable = TB_PATH_ALL;
1002         path->egress_shared_buffer = TB_PATH_NONE;
1003         path->ingress_shared_buffer = TB_PATH_NONE;
1004         path->priority = 5;
1005         path->weight = 1;
1006         path->clear_fc = true;
1007
1008         tb_path_for_each_hop(path, hop) {
1009                 int ret;
1010
1011                 ret = tb_dma_reserve_credits(hop, credits);
1012                 if (ret)
1013                         return ret;
1014         }
1015
1016         return 0;
1017 }
1018
1019 static void tb_dma_release_credits(struct tb_path_hop *hop)
1020 {
1021         struct tb_port *port = hop->in_port;
1022
1023         if (tb_port_use_credit_allocation(port)) {
1024                 port->dma_credits -= hop->initial_credits;
1025
1026                 tb_port_dbg(port, "released %u DMA path credits\n",
1027                             hop->initial_credits);
1028         }
1029 }
1030
1031 static void tb_dma_deinit_path(struct tb_path *path)
1032 {
1033         struct tb_path_hop *hop;
1034
1035         tb_path_for_each_hop(path, hop)
1036                 tb_dma_release_credits(hop);
1037 }
1038
1039 static void tb_dma_deinit(struct tb_tunnel *tunnel)
1040 {
1041         int i;
1042
1043         for (i = 0; i < tunnel->npaths; i++) {
1044                 if (!tunnel->paths[i])
1045                         continue;
1046                 tb_dma_deinit_path(tunnel->paths[i]);
1047         }
1048 }
1049
1050 /**
1051  * tb_tunnel_alloc_dma() - allocate a DMA tunnel
1052  * @tb: Pointer to the domain structure
1053  * @nhi: Host controller port
1054  * @dst: Destination null port which the other domain is connected to
1055  * @transmit_path: HopID used for transmitting packets
1056  * @transmit_ring: NHI ring number used to send packets towards the
1057  *                 other domain. Set to %-1 if TX path is not needed.
1058  * @receive_path: HopID used for receiving packets
1059  * @receive_ring: NHI ring number used to receive packets from the
1060  *                other domain. Set to %-1 if RX path is not needed.
1061  *
1062  * Return: Returns a tb_tunnel on success or NULL on failure.
1063  */
1064 struct tb_tunnel *tb_tunnel_alloc_dma(struct tb *tb, struct tb_port *nhi,
1065                                       struct tb_port *dst, int transmit_path,
1066                                       int transmit_ring, int receive_path,
1067                                       int receive_ring)
1068 {
1069         struct tb_tunnel *tunnel;
1070         size_t npaths = 0, i = 0;
1071         struct tb_path *path;
1072         int credits;
1073
1074         if (receive_ring > 0)
1075                 npaths++;
1076         if (transmit_ring > 0)
1077                 npaths++;
1078
1079         if (WARN_ON(!npaths))
1080                 return NULL;
1081
1082         tunnel = tb_tunnel_alloc(tb, npaths, TB_TUNNEL_DMA);
1083         if (!tunnel)
1084                 return NULL;
1085
1086         tunnel->src_port = nhi;
1087         tunnel->dst_port = dst;
1088         tunnel->deinit = tb_dma_deinit;
1089
1090         credits = min_not_zero(TB_DMA_CREDITS, nhi->sw->max_dma_credits);
1091
1092         if (receive_ring > 0) {
1093                 path = tb_path_alloc(tb, dst, receive_path, nhi, receive_ring, 0,
1094                                      "DMA RX");
1095                 if (!path)
1096                         goto err_free;
1097                 tunnel->paths[i++] = path;
1098                 if (tb_dma_init_rx_path(path, credits)) {
1099                         tb_tunnel_dbg(tunnel, "not enough buffers for RX path\n");
1100                         goto err_free;
1101                 }
1102         }
1103
1104         if (transmit_ring > 0) {
1105                 path = tb_path_alloc(tb, nhi, transmit_ring, dst, transmit_path, 0,
1106                                      "DMA TX");
1107                 if (!path)
1108                         goto err_free;
1109                 tunnel->paths[i++] = path;
1110                 if (tb_dma_init_tx_path(path, credits)) {
1111                         tb_tunnel_dbg(tunnel, "not enough buffers for TX path\n");
1112                         goto err_free;
1113                 }
1114         }
1115
1116         return tunnel;
1117
1118 err_free:
1119         tb_tunnel_free(tunnel);
1120         return NULL;
1121 }
1122
1123 /**
1124  * tb_tunnel_match_dma() - Match DMA tunnel
1125  * @tunnel: Tunnel to match
1126  * @transmit_path: HopID used for transmitting packets. Pass %-1 to ignore.
1127  * @transmit_ring: NHI ring number used to send packets towards the
1128  *                 other domain. Pass %-1 to ignore.
1129  * @receive_path: HopID used for receiving packets. Pass %-1 to ignore.
1130  * @receive_ring: NHI ring number used to receive packets from the
1131  *                other domain. Pass %-1 to ignore.
1132  *
1133  * This function can be used to match specific DMA tunnel, if there are
1134  * multiple DMA tunnels going through the same XDomain connection.
1135  * Returns true if there is match and false otherwise.
1136  */
1137 bool tb_tunnel_match_dma(const struct tb_tunnel *tunnel, int transmit_path,
1138                          int transmit_ring, int receive_path, int receive_ring)
1139 {
1140         const struct tb_path *tx_path = NULL, *rx_path = NULL;
1141         int i;
1142
1143         if (!receive_ring || !transmit_ring)
1144                 return false;
1145
1146         for (i = 0; i < tunnel->npaths; i++) {
1147                 const struct tb_path *path = tunnel->paths[i];
1148
1149                 if (!path)
1150                         continue;
1151
1152                 if (tb_port_is_nhi(path->hops[0].in_port))
1153                         tx_path = path;
1154                 else if (tb_port_is_nhi(path->hops[path->path_length - 1].out_port))
1155                         rx_path = path;
1156         }
1157
1158         if (transmit_ring > 0 || transmit_path > 0) {
1159                 if (!tx_path)
1160                         return false;
1161                 if (transmit_ring > 0 &&
1162                     (tx_path->hops[0].in_hop_index != transmit_ring))
1163                         return false;
1164                 if (transmit_path > 0 &&
1165                     (tx_path->hops[tx_path->path_length - 1].next_hop_index != transmit_path))
1166                         return false;
1167         }
1168
1169         if (receive_ring > 0 || receive_path > 0) {
1170                 if (!rx_path)
1171                         return false;
1172                 if (receive_path > 0 &&
1173                     (rx_path->hops[0].in_hop_index != receive_path))
1174                         return false;
1175                 if (receive_ring > 0 &&
1176                     (rx_path->hops[rx_path->path_length - 1].next_hop_index != receive_ring))
1177                         return false;
1178         }
1179
1180         return true;
1181 }
1182
1183 static int tb_usb3_max_link_rate(struct tb_port *up, struct tb_port *down)
1184 {
1185         int ret, up_max_rate, down_max_rate;
1186
1187         ret = usb4_usb3_port_max_link_rate(up);
1188         if (ret < 0)
1189                 return ret;
1190         up_max_rate = ret;
1191
1192         ret = usb4_usb3_port_max_link_rate(down);
1193         if (ret < 0)
1194                 return ret;
1195         down_max_rate = ret;
1196
1197         return min(up_max_rate, down_max_rate);
1198 }
1199
1200 static int tb_usb3_init(struct tb_tunnel *tunnel)
1201 {
1202         tb_tunnel_dbg(tunnel, "allocating initial bandwidth %d/%d Mb/s\n",
1203                       tunnel->allocated_up, tunnel->allocated_down);
1204
1205         return usb4_usb3_port_allocate_bandwidth(tunnel->src_port,
1206                                                  &tunnel->allocated_up,
1207                                                  &tunnel->allocated_down);
1208 }
1209
1210 static int tb_usb3_activate(struct tb_tunnel *tunnel, bool activate)
1211 {
1212         int res;
1213
1214         res = tb_usb3_port_enable(tunnel->src_port, activate);
1215         if (res)
1216                 return res;
1217
1218         if (tb_port_is_usb3_up(tunnel->dst_port))
1219                 return tb_usb3_port_enable(tunnel->dst_port, activate);
1220
1221         return 0;
1222 }
1223
1224 static int tb_usb3_consumed_bandwidth(struct tb_tunnel *tunnel,
1225                 int *consumed_up, int *consumed_down)
1226 {
1227         int pcie_enabled = tb_acpi_may_tunnel_pcie();
1228
1229         /*
1230          * PCIe tunneling, if enabled, affects the USB3 bandwidth so
1231          * take that it into account here.
1232          */
1233         *consumed_up = tunnel->allocated_up * (3 + pcie_enabled) / 3;
1234         *consumed_down = tunnel->allocated_down * (3 + pcie_enabled) / 3;
1235         return 0;
1236 }
1237
1238 static int tb_usb3_release_unused_bandwidth(struct tb_tunnel *tunnel)
1239 {
1240         int ret;
1241
1242         ret = usb4_usb3_port_release_bandwidth(tunnel->src_port,
1243                                                &tunnel->allocated_up,
1244                                                &tunnel->allocated_down);
1245         if (ret)
1246                 return ret;
1247
1248         tb_tunnel_dbg(tunnel, "decreased bandwidth allocation to %d/%d Mb/s\n",
1249                       tunnel->allocated_up, tunnel->allocated_down);
1250         return 0;
1251 }
1252
1253 static void tb_usb3_reclaim_available_bandwidth(struct tb_tunnel *tunnel,
1254                                                 int *available_up,
1255                                                 int *available_down)
1256 {
1257         int ret, max_rate, allocate_up, allocate_down;
1258
1259         ret = usb4_usb3_port_actual_link_rate(tunnel->src_port);
1260         if (ret < 0) {
1261                 tb_tunnel_warn(tunnel, "failed to read actual link rate\n");
1262                 return;
1263         } else if (!ret) {
1264                 /* Use maximum link rate if the link valid is not set */
1265                 ret = tb_usb3_max_link_rate(tunnel->dst_port, tunnel->src_port);
1266                 if (ret < 0) {
1267                         tb_tunnel_warn(tunnel, "failed to read maximum link rate\n");
1268                         return;
1269                 }
1270         }
1271
1272         /*
1273          * 90% of the max rate can be allocated for isochronous
1274          * transfers.
1275          */
1276         max_rate = ret * 90 / 100;
1277
1278         /* No need to reclaim if already at maximum */
1279         if (tunnel->allocated_up >= max_rate &&
1280             tunnel->allocated_down >= max_rate)
1281                 return;
1282
1283         /* Don't go lower than what is already allocated */
1284         allocate_up = min(max_rate, *available_up);
1285         if (allocate_up < tunnel->allocated_up)
1286                 allocate_up = tunnel->allocated_up;
1287
1288         allocate_down = min(max_rate, *available_down);
1289         if (allocate_down < tunnel->allocated_down)
1290                 allocate_down = tunnel->allocated_down;
1291
1292         /* If no changes no need to do more */
1293         if (allocate_up == tunnel->allocated_up &&
1294             allocate_down == tunnel->allocated_down)
1295                 return;
1296
1297         ret = usb4_usb3_port_allocate_bandwidth(tunnel->src_port, &allocate_up,
1298                                                 &allocate_down);
1299         if (ret) {
1300                 tb_tunnel_info(tunnel, "failed to allocate bandwidth\n");
1301                 return;
1302         }
1303
1304         tunnel->allocated_up = allocate_up;
1305         *available_up -= tunnel->allocated_up;
1306
1307         tunnel->allocated_down = allocate_down;
1308         *available_down -= tunnel->allocated_down;
1309
1310         tb_tunnel_dbg(tunnel, "increased bandwidth allocation to %d/%d Mb/s\n",
1311                       tunnel->allocated_up, tunnel->allocated_down);
1312 }
1313
1314 static void tb_usb3_init_credits(struct tb_path_hop *hop)
1315 {
1316         struct tb_port *port = hop->in_port;
1317         struct tb_switch *sw = port->sw;
1318         unsigned int credits;
1319
1320         if (tb_port_use_credit_allocation(port)) {
1321                 credits = sw->max_usb3_credits;
1322         } else {
1323                 if (tb_port_is_null(port))
1324                         credits = port->bonded ? 32 : 16;
1325                 else
1326                         credits = 7;
1327         }
1328
1329         hop->initial_credits = credits;
1330 }
1331
1332 static void tb_usb3_init_path(struct tb_path *path)
1333 {
1334         struct tb_path_hop *hop;
1335
1336         path->egress_fc_enable = TB_PATH_SOURCE | TB_PATH_INTERNAL;
1337         path->egress_shared_buffer = TB_PATH_NONE;
1338         path->ingress_fc_enable = TB_PATH_ALL;
1339         path->ingress_shared_buffer = TB_PATH_NONE;
1340         path->priority = 3;
1341         path->weight = 3;
1342         path->drop_packages = 0;
1343
1344         tb_path_for_each_hop(path, hop)
1345                 tb_usb3_init_credits(hop);
1346 }
1347
1348 /**
1349  * tb_tunnel_discover_usb3() - Discover existing USB3 tunnels
1350  * @tb: Pointer to the domain structure
1351  * @down: USB3 downstream adapter
1352  * @alloc_hopid: Allocate HopIDs from visited ports
1353  *
1354  * If @down adapter is active, follows the tunnel to the USB3 upstream
1355  * adapter and back. Returns the discovered tunnel or %NULL if there was
1356  * no tunnel.
1357  */
1358 struct tb_tunnel *tb_tunnel_discover_usb3(struct tb *tb, struct tb_port *down,
1359                                           bool alloc_hopid)
1360 {
1361         struct tb_tunnel *tunnel;
1362         struct tb_path *path;
1363
1364         if (!tb_usb3_port_is_enabled(down))
1365                 return NULL;
1366
1367         tunnel = tb_tunnel_alloc(tb, 2, TB_TUNNEL_USB3);
1368         if (!tunnel)
1369                 return NULL;
1370
1371         tunnel->activate = tb_usb3_activate;
1372         tunnel->src_port = down;
1373
1374         /*
1375          * Discover both paths even if they are not complete. We will
1376          * clean them up by calling tb_tunnel_deactivate() below in that
1377          * case.
1378          */
1379         path = tb_path_discover(down, TB_USB3_HOPID, NULL, -1,
1380                                 &tunnel->dst_port, "USB3 Down", alloc_hopid);
1381         if (!path) {
1382                 /* Just disable the downstream port */
1383                 tb_usb3_port_enable(down, false);
1384                 goto err_free;
1385         }
1386         tunnel->paths[TB_USB3_PATH_DOWN] = path;
1387         tb_usb3_init_path(tunnel->paths[TB_USB3_PATH_DOWN]);
1388
1389         path = tb_path_discover(tunnel->dst_port, -1, down, TB_USB3_HOPID, NULL,
1390                                 "USB3 Up", alloc_hopid);
1391         if (!path)
1392                 goto err_deactivate;
1393         tunnel->paths[TB_USB3_PATH_UP] = path;
1394         tb_usb3_init_path(tunnel->paths[TB_USB3_PATH_UP]);
1395
1396         /* Validate that the tunnel is complete */
1397         if (!tb_port_is_usb3_up(tunnel->dst_port)) {
1398                 tb_port_warn(tunnel->dst_port,
1399                              "path does not end on an USB3 adapter, cleaning up\n");
1400                 goto err_deactivate;
1401         }
1402
1403         if (down != tunnel->src_port) {
1404                 tb_tunnel_warn(tunnel, "path is not complete, cleaning up\n");
1405                 goto err_deactivate;
1406         }
1407
1408         if (!tb_usb3_port_is_enabled(tunnel->dst_port)) {
1409                 tb_tunnel_warn(tunnel,
1410                                "tunnel is not fully activated, cleaning up\n");
1411                 goto err_deactivate;
1412         }
1413
1414         if (!tb_route(down->sw)) {
1415                 int ret;
1416
1417                 /*
1418                  * Read the initial bandwidth allocation for the first
1419                  * hop tunnel.
1420                  */
1421                 ret = usb4_usb3_port_allocated_bandwidth(down,
1422                         &tunnel->allocated_up, &tunnel->allocated_down);
1423                 if (ret)
1424                         goto err_deactivate;
1425
1426                 tb_tunnel_dbg(tunnel, "currently allocated bandwidth %d/%d Mb/s\n",
1427                               tunnel->allocated_up, tunnel->allocated_down);
1428
1429                 tunnel->init = tb_usb3_init;
1430                 tunnel->consumed_bandwidth = tb_usb3_consumed_bandwidth;
1431                 tunnel->release_unused_bandwidth =
1432                         tb_usb3_release_unused_bandwidth;
1433                 tunnel->reclaim_available_bandwidth =
1434                         tb_usb3_reclaim_available_bandwidth;
1435         }
1436
1437         tb_tunnel_dbg(tunnel, "discovered\n");
1438         return tunnel;
1439
1440 err_deactivate:
1441         tb_tunnel_deactivate(tunnel);
1442 err_free:
1443         tb_tunnel_free(tunnel);
1444
1445         return NULL;
1446 }
1447
1448 /**
1449  * tb_tunnel_alloc_usb3() - allocate a USB3 tunnel
1450  * @tb: Pointer to the domain structure
1451  * @up: USB3 upstream adapter port
1452  * @down: USB3 downstream adapter port
1453  * @max_up: Maximum available upstream bandwidth for the USB3 tunnel (%0
1454  *          if not limited).
1455  * @max_down: Maximum available downstream bandwidth for the USB3 tunnel
1456  *            (%0 if not limited).
1457  *
1458  * Allocate an USB3 tunnel. The ports must be of type @TB_TYPE_USB3_UP and
1459  * @TB_TYPE_USB3_DOWN.
1460  *
1461  * Return: Returns a tb_tunnel on success or %NULL on failure.
1462  */
1463 struct tb_tunnel *tb_tunnel_alloc_usb3(struct tb *tb, struct tb_port *up,
1464                                        struct tb_port *down, int max_up,
1465                                        int max_down)
1466 {
1467         struct tb_tunnel *tunnel;
1468         struct tb_path *path;
1469         int max_rate = 0;
1470
1471         /*
1472          * Check that we have enough bandwidth available for the new
1473          * USB3 tunnel.
1474          */
1475         if (max_up > 0 || max_down > 0) {
1476                 max_rate = tb_usb3_max_link_rate(down, up);
1477                 if (max_rate < 0)
1478                         return NULL;
1479
1480                 /* Only 90% can be allocated for USB3 isochronous transfers */
1481                 max_rate = max_rate * 90 / 100;
1482                 tb_port_dbg(up, "required bandwidth for USB3 tunnel %d Mb/s\n",
1483                             max_rate);
1484
1485                 if (max_rate > max_up || max_rate > max_down) {
1486                         tb_port_warn(up, "not enough bandwidth for USB3 tunnel\n");
1487                         return NULL;
1488                 }
1489         }
1490
1491         tunnel = tb_tunnel_alloc(tb, 2, TB_TUNNEL_USB3);
1492         if (!tunnel)
1493                 return NULL;
1494
1495         tunnel->activate = tb_usb3_activate;
1496         tunnel->src_port = down;
1497         tunnel->dst_port = up;
1498         tunnel->max_up = max_up;
1499         tunnel->max_down = max_down;
1500
1501         path = tb_path_alloc(tb, down, TB_USB3_HOPID, up, TB_USB3_HOPID, 0,
1502                              "USB3 Down");
1503         if (!path) {
1504                 tb_tunnel_free(tunnel);
1505                 return NULL;
1506         }
1507         tb_usb3_init_path(path);
1508         tunnel->paths[TB_USB3_PATH_DOWN] = path;
1509
1510         path = tb_path_alloc(tb, up, TB_USB3_HOPID, down, TB_USB3_HOPID, 0,
1511                              "USB3 Up");
1512         if (!path) {
1513                 tb_tunnel_free(tunnel);
1514                 return NULL;
1515         }
1516         tb_usb3_init_path(path);
1517         tunnel->paths[TB_USB3_PATH_UP] = path;
1518
1519         if (!tb_route(down->sw)) {
1520                 tunnel->allocated_up = max_rate;
1521                 tunnel->allocated_down = max_rate;
1522
1523                 tunnel->init = tb_usb3_init;
1524                 tunnel->consumed_bandwidth = tb_usb3_consumed_bandwidth;
1525                 tunnel->release_unused_bandwidth =
1526                         tb_usb3_release_unused_bandwidth;
1527                 tunnel->reclaim_available_bandwidth =
1528                         tb_usb3_reclaim_available_bandwidth;
1529         }
1530
1531         return tunnel;
1532 }
1533
1534 /**
1535  * tb_tunnel_free() - free a tunnel
1536  * @tunnel: Tunnel to be freed
1537  *
1538  * Frees a tunnel. The tunnel does not need to be deactivated.
1539  */
1540 void tb_tunnel_free(struct tb_tunnel *tunnel)
1541 {
1542         int i;
1543
1544         if (!tunnel)
1545                 return;
1546
1547         if (tunnel->deinit)
1548                 tunnel->deinit(tunnel);
1549
1550         for (i = 0; i < tunnel->npaths; i++) {
1551                 if (tunnel->paths[i])
1552                         tb_path_free(tunnel->paths[i]);
1553         }
1554
1555         kfree(tunnel->paths);
1556         kfree(tunnel);
1557 }
1558
1559 /**
1560  * tb_tunnel_is_invalid - check whether an activated path is still valid
1561  * @tunnel: Tunnel to check
1562  */
1563 bool tb_tunnel_is_invalid(struct tb_tunnel *tunnel)
1564 {
1565         int i;
1566
1567         for (i = 0; i < tunnel->npaths; i++) {
1568                 WARN_ON(!tunnel->paths[i]->activated);
1569                 if (tb_path_is_invalid(tunnel->paths[i]))
1570                         return true;
1571         }
1572
1573         return false;
1574 }
1575
1576 /**
1577  * tb_tunnel_restart() - activate a tunnel after a hardware reset
1578  * @tunnel: Tunnel to restart
1579  *
1580  * Return: 0 on success and negative errno in case if failure
1581  */
1582 int tb_tunnel_restart(struct tb_tunnel *tunnel)
1583 {
1584         int res, i;
1585
1586         tb_tunnel_dbg(tunnel, "activating\n");
1587
1588         /*
1589          * Make sure all paths are properly disabled before enabling
1590          * them again.
1591          */
1592         for (i = 0; i < tunnel->npaths; i++) {
1593                 if (tunnel->paths[i]->activated) {
1594                         tb_path_deactivate(tunnel->paths[i]);
1595                         tunnel->paths[i]->activated = false;
1596                 }
1597         }
1598
1599         if (tunnel->init) {
1600                 res = tunnel->init(tunnel);
1601                 if (res)
1602                         return res;
1603         }
1604
1605         for (i = 0; i < tunnel->npaths; i++) {
1606                 res = tb_path_activate(tunnel->paths[i]);
1607                 if (res)
1608                         goto err;
1609         }
1610
1611         if (tunnel->activate) {
1612                 res = tunnel->activate(tunnel, true);
1613                 if (res)
1614                         goto err;
1615         }
1616
1617         return 0;
1618
1619 err:
1620         tb_tunnel_warn(tunnel, "activation failed\n");
1621         tb_tunnel_deactivate(tunnel);
1622         return res;
1623 }
1624
1625 /**
1626  * tb_tunnel_activate() - activate a tunnel
1627  * @tunnel: Tunnel to activate
1628  *
1629  * Return: Returns 0 on success or an error code on failure.
1630  */
1631 int tb_tunnel_activate(struct tb_tunnel *tunnel)
1632 {
1633         int i;
1634
1635         for (i = 0; i < tunnel->npaths; i++) {
1636                 if (tunnel->paths[i]->activated) {
1637                         tb_tunnel_WARN(tunnel,
1638                                        "trying to activate an already activated tunnel\n");
1639                         return -EINVAL;
1640                 }
1641         }
1642
1643         return tb_tunnel_restart(tunnel);
1644 }
1645
1646 /**
1647  * tb_tunnel_deactivate() - deactivate a tunnel
1648  * @tunnel: Tunnel to deactivate
1649  */
1650 void tb_tunnel_deactivate(struct tb_tunnel *tunnel)
1651 {
1652         int i;
1653
1654         tb_tunnel_dbg(tunnel, "deactivating\n");
1655
1656         if (tunnel->activate)
1657                 tunnel->activate(tunnel, false);
1658
1659         for (i = 0; i < tunnel->npaths; i++) {
1660                 if (tunnel->paths[i] && tunnel->paths[i]->activated)
1661                         tb_path_deactivate(tunnel->paths[i]);
1662         }
1663 }
1664
1665 /**
1666  * tb_tunnel_port_on_path() - Does the tunnel go through port
1667  * @tunnel: Tunnel to check
1668  * @port: Port to check
1669  *
1670  * Returns true if @tunnel goes through @port (direction does not matter),
1671  * false otherwise.
1672  */
1673 bool tb_tunnel_port_on_path(const struct tb_tunnel *tunnel,
1674                             const struct tb_port *port)
1675 {
1676         int i;
1677
1678         for (i = 0; i < tunnel->npaths; i++) {
1679                 if (!tunnel->paths[i])
1680                         continue;
1681
1682                 if (tb_path_port_on_path(tunnel->paths[i], port))
1683                         return true;
1684         }
1685
1686         return false;
1687 }
1688
1689 static bool tb_tunnel_is_active(const struct tb_tunnel *tunnel)
1690 {
1691         int i;
1692
1693         for (i = 0; i < tunnel->npaths; i++) {
1694                 if (!tunnel->paths[i])
1695                         return false;
1696                 if (!tunnel->paths[i]->activated)
1697                         return false;
1698         }
1699
1700         return true;
1701 }
1702
1703 /**
1704  * tb_tunnel_consumed_bandwidth() - Return bandwidth consumed by the tunnel
1705  * @tunnel: Tunnel to check
1706  * @consumed_up: Consumed bandwidth in Mb/s from @dst_port to @src_port.
1707  *               Can be %NULL.
1708  * @consumed_down: Consumed bandwidth in Mb/s from @src_port to @dst_port.
1709  *                 Can be %NULL.
1710  *
1711  * Stores the amount of isochronous bandwidth @tunnel consumes in
1712  * @consumed_up and @consumed_down. In case of success returns %0,
1713  * negative errno otherwise.
1714  */
1715 int tb_tunnel_consumed_bandwidth(struct tb_tunnel *tunnel, int *consumed_up,
1716                                  int *consumed_down)
1717 {
1718         int up_bw = 0, down_bw = 0;
1719
1720         if (!tb_tunnel_is_active(tunnel))
1721                 goto out;
1722
1723         if (tunnel->consumed_bandwidth) {
1724                 int ret;
1725
1726                 ret = tunnel->consumed_bandwidth(tunnel, &up_bw, &down_bw);
1727                 if (ret)
1728                         return ret;
1729
1730                 tb_tunnel_dbg(tunnel, "consumed bandwidth %d/%d Mb/s\n", up_bw,
1731                               down_bw);
1732         }
1733
1734 out:
1735         if (consumed_up)
1736                 *consumed_up = up_bw;
1737         if (consumed_down)
1738                 *consumed_down = down_bw;
1739
1740         return 0;
1741 }
1742
1743 /**
1744  * tb_tunnel_release_unused_bandwidth() - Release unused bandwidth
1745  * @tunnel: Tunnel whose unused bandwidth to release
1746  *
1747  * If tunnel supports dynamic bandwidth management (USB3 tunnels at the
1748  * moment) this function makes it to release all the unused bandwidth.
1749  *
1750  * Returns %0 in case of success and negative errno otherwise.
1751  */
1752 int tb_tunnel_release_unused_bandwidth(struct tb_tunnel *tunnel)
1753 {
1754         if (!tb_tunnel_is_active(tunnel))
1755                 return 0;
1756
1757         if (tunnel->release_unused_bandwidth) {
1758                 int ret;
1759
1760                 ret = tunnel->release_unused_bandwidth(tunnel);
1761                 if (ret)
1762                         return ret;
1763         }
1764
1765         return 0;
1766 }
1767
1768 /**
1769  * tb_tunnel_reclaim_available_bandwidth() - Reclaim available bandwidth
1770  * @tunnel: Tunnel reclaiming available bandwidth
1771  * @available_up: Available upstream bandwidth (in Mb/s)
1772  * @available_down: Available downstream bandwidth (in Mb/s)
1773  *
1774  * Reclaims bandwidth from @available_up and @available_down and updates
1775  * the variables accordingly (e.g decreases both according to what was
1776  * reclaimed by the tunnel). If nothing was reclaimed the values are
1777  * kept as is.
1778  */
1779 void tb_tunnel_reclaim_available_bandwidth(struct tb_tunnel *tunnel,
1780                                            int *available_up,
1781                                            int *available_down)
1782 {
1783         if (!tb_tunnel_is_active(tunnel))
1784                 return;
1785
1786         if (tunnel->reclaim_available_bandwidth)
1787                 tunnel->reclaim_available_bandwidth(tunnel, available_up,
1788                                                     available_down);
1789 }