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