thunderbolt: Add helper to check if CL states are enabled on port
[platform/kernel/linux-starfive.git] / drivers / thunderbolt / switch.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Thunderbolt driver - switch/port utility functions
4  *
5  * Copyright (c) 2014 Andreas Noever <andreas.noever@gmail.com>
6  * Copyright (C) 2018, Intel Corporation
7  */
8
9 #include <linux/delay.h>
10 #include <linux/idr.h>
11 #include <linux/nvmem-provider.h>
12 #include <linux/pm_runtime.h>
13 #include <linux/sched/signal.h>
14 #include <linux/sizes.h>
15 #include <linux/slab.h>
16 #include <linux/module.h>
17
18 #include "tb.h"
19
20 /* Switch NVM support */
21
22 #define NVM_CSS                 0x10
23
24 struct nvm_auth_status {
25         struct list_head list;
26         uuid_t uuid;
27         u32 status;
28 };
29
30 static bool clx_enabled = true;
31 module_param_named(clx, clx_enabled, bool, 0444);
32 MODULE_PARM_DESC(clx, "allow low power states on the high-speed lanes (default: true)");
33
34 /*
35  * Hold NVM authentication failure status per switch This information
36  * needs to stay around even when the switch gets power cycled so we
37  * keep it separately.
38  */
39 static LIST_HEAD(nvm_auth_status_cache);
40 static DEFINE_MUTEX(nvm_auth_status_lock);
41
42 static struct nvm_auth_status *__nvm_get_auth_status(const struct tb_switch *sw)
43 {
44         struct nvm_auth_status *st;
45
46         list_for_each_entry(st, &nvm_auth_status_cache, list) {
47                 if (uuid_equal(&st->uuid, sw->uuid))
48                         return st;
49         }
50
51         return NULL;
52 }
53
54 static void nvm_get_auth_status(const struct tb_switch *sw, u32 *status)
55 {
56         struct nvm_auth_status *st;
57
58         mutex_lock(&nvm_auth_status_lock);
59         st = __nvm_get_auth_status(sw);
60         mutex_unlock(&nvm_auth_status_lock);
61
62         *status = st ? st->status : 0;
63 }
64
65 static void nvm_set_auth_status(const struct tb_switch *sw, u32 status)
66 {
67         struct nvm_auth_status *st;
68
69         if (WARN_ON(!sw->uuid))
70                 return;
71
72         mutex_lock(&nvm_auth_status_lock);
73         st = __nvm_get_auth_status(sw);
74
75         if (!st) {
76                 st = kzalloc(sizeof(*st), GFP_KERNEL);
77                 if (!st)
78                         goto unlock;
79
80                 memcpy(&st->uuid, sw->uuid, sizeof(st->uuid));
81                 INIT_LIST_HEAD(&st->list);
82                 list_add_tail(&st->list, &nvm_auth_status_cache);
83         }
84
85         st->status = status;
86 unlock:
87         mutex_unlock(&nvm_auth_status_lock);
88 }
89
90 static void nvm_clear_auth_status(const struct tb_switch *sw)
91 {
92         struct nvm_auth_status *st;
93
94         mutex_lock(&nvm_auth_status_lock);
95         st = __nvm_get_auth_status(sw);
96         if (st) {
97                 list_del(&st->list);
98                 kfree(st);
99         }
100         mutex_unlock(&nvm_auth_status_lock);
101 }
102
103 static int nvm_validate_and_write(struct tb_switch *sw)
104 {
105         unsigned int image_size, hdr_size;
106         const u8 *buf = sw->nvm->buf;
107         u16 ds_size;
108         int ret;
109
110         if (!buf)
111                 return -EINVAL;
112
113         image_size = sw->nvm->buf_data_size;
114         if (image_size < NVM_MIN_SIZE || image_size > NVM_MAX_SIZE)
115                 return -EINVAL;
116
117         /*
118          * FARB pointer must point inside the image and must at least
119          * contain parts of the digital section we will be reading here.
120          */
121         hdr_size = (*(u32 *)buf) & 0xffffff;
122         if (hdr_size + NVM_DEVID + 2 >= image_size)
123                 return -EINVAL;
124
125         /* Digital section start should be aligned to 4k page */
126         if (!IS_ALIGNED(hdr_size, SZ_4K))
127                 return -EINVAL;
128
129         /*
130          * Read digital section size and check that it also fits inside
131          * the image.
132          */
133         ds_size = *(u16 *)(buf + hdr_size);
134         if (ds_size >= image_size)
135                 return -EINVAL;
136
137         if (!sw->safe_mode) {
138                 u16 device_id;
139
140                 /*
141                  * Make sure the device ID in the image matches the one
142                  * we read from the switch config space.
143                  */
144                 device_id = *(u16 *)(buf + hdr_size + NVM_DEVID);
145                 if (device_id != sw->config.device_id)
146                         return -EINVAL;
147
148                 if (sw->generation < 3) {
149                         /* Write CSS headers first */
150                         ret = dma_port_flash_write(sw->dma_port,
151                                 DMA_PORT_CSS_ADDRESS, buf + NVM_CSS,
152                                 DMA_PORT_CSS_MAX_SIZE);
153                         if (ret)
154                                 return ret;
155                 }
156
157                 /* Skip headers in the image */
158                 buf += hdr_size;
159                 image_size -= hdr_size;
160         }
161
162         if (tb_switch_is_usb4(sw))
163                 ret = usb4_switch_nvm_write(sw, 0, buf, image_size);
164         else
165                 ret = dma_port_flash_write(sw->dma_port, 0, buf, image_size);
166         if (!ret)
167                 sw->nvm->flushed = true;
168         return ret;
169 }
170
171 static int nvm_authenticate_host_dma_port(struct tb_switch *sw)
172 {
173         int ret = 0;
174
175         /*
176          * Root switch NVM upgrade requires that we disconnect the
177          * existing paths first (in case it is not in safe mode
178          * already).
179          */
180         if (!sw->safe_mode) {
181                 u32 status;
182
183                 ret = tb_domain_disconnect_all_paths(sw->tb);
184                 if (ret)
185                         return ret;
186                 /*
187                  * The host controller goes away pretty soon after this if
188                  * everything goes well so getting timeout is expected.
189                  */
190                 ret = dma_port_flash_update_auth(sw->dma_port);
191                 if (!ret || ret == -ETIMEDOUT)
192                         return 0;
193
194                 /*
195                  * Any error from update auth operation requires power
196                  * cycling of the host router.
197                  */
198                 tb_sw_warn(sw, "failed to authenticate NVM, power cycling\n");
199                 if (dma_port_flash_update_auth_status(sw->dma_port, &status) > 0)
200                         nvm_set_auth_status(sw, status);
201         }
202
203         /*
204          * From safe mode we can get out by just power cycling the
205          * switch.
206          */
207         dma_port_power_cycle(sw->dma_port);
208         return ret;
209 }
210
211 static int nvm_authenticate_device_dma_port(struct tb_switch *sw)
212 {
213         int ret, retries = 10;
214
215         ret = dma_port_flash_update_auth(sw->dma_port);
216         switch (ret) {
217         case 0:
218         case -ETIMEDOUT:
219         case -EACCES:
220         case -EINVAL:
221                 /* Power cycle is required */
222                 break;
223         default:
224                 return ret;
225         }
226
227         /*
228          * Poll here for the authentication status. It takes some time
229          * for the device to respond (we get timeout for a while). Once
230          * we get response the device needs to be power cycled in order
231          * to the new NVM to be taken into use.
232          */
233         do {
234                 u32 status;
235
236                 ret = dma_port_flash_update_auth_status(sw->dma_port, &status);
237                 if (ret < 0 && ret != -ETIMEDOUT)
238                         return ret;
239                 if (ret > 0) {
240                         if (status) {
241                                 tb_sw_warn(sw, "failed to authenticate NVM\n");
242                                 nvm_set_auth_status(sw, status);
243                         }
244
245                         tb_sw_info(sw, "power cycling the switch now\n");
246                         dma_port_power_cycle(sw->dma_port);
247                         return 0;
248                 }
249
250                 msleep(500);
251         } while (--retries);
252
253         return -ETIMEDOUT;
254 }
255
256 static void nvm_authenticate_start_dma_port(struct tb_switch *sw)
257 {
258         struct pci_dev *root_port;
259
260         /*
261          * During host router NVM upgrade we should not allow root port to
262          * go into D3cold because some root ports cannot trigger PME
263          * itself. To be on the safe side keep the root port in D0 during
264          * the whole upgrade process.
265          */
266         root_port = pcie_find_root_port(sw->tb->nhi->pdev);
267         if (root_port)
268                 pm_runtime_get_noresume(&root_port->dev);
269 }
270
271 static void nvm_authenticate_complete_dma_port(struct tb_switch *sw)
272 {
273         struct pci_dev *root_port;
274
275         root_port = pcie_find_root_port(sw->tb->nhi->pdev);
276         if (root_port)
277                 pm_runtime_put(&root_port->dev);
278 }
279
280 static inline bool nvm_readable(struct tb_switch *sw)
281 {
282         if (tb_switch_is_usb4(sw)) {
283                 /*
284                  * USB4 devices must support NVM operations but it is
285                  * optional for hosts. Therefore we query the NVM sector
286                  * size here and if it is supported assume NVM
287                  * operations are implemented.
288                  */
289                 return usb4_switch_nvm_sector_size(sw) > 0;
290         }
291
292         /* Thunderbolt 2 and 3 devices support NVM through DMA port */
293         return !!sw->dma_port;
294 }
295
296 static inline bool nvm_upgradeable(struct tb_switch *sw)
297 {
298         if (sw->no_nvm_upgrade)
299                 return false;
300         return nvm_readable(sw);
301 }
302
303 static inline int nvm_read(struct tb_switch *sw, unsigned int address,
304                            void *buf, size_t size)
305 {
306         if (tb_switch_is_usb4(sw))
307                 return usb4_switch_nvm_read(sw, address, buf, size);
308         return dma_port_flash_read(sw->dma_port, address, buf, size);
309 }
310
311 static int nvm_authenticate(struct tb_switch *sw, bool auth_only)
312 {
313         int ret;
314
315         if (tb_switch_is_usb4(sw)) {
316                 if (auth_only) {
317                         ret = usb4_switch_nvm_set_offset(sw, 0);
318                         if (ret)
319                                 return ret;
320                 }
321                 sw->nvm->authenticating = true;
322                 return usb4_switch_nvm_authenticate(sw);
323         } else if (auth_only) {
324                 return -EOPNOTSUPP;
325         }
326
327         sw->nvm->authenticating = true;
328         if (!tb_route(sw)) {
329                 nvm_authenticate_start_dma_port(sw);
330                 ret = nvm_authenticate_host_dma_port(sw);
331         } else {
332                 ret = nvm_authenticate_device_dma_port(sw);
333         }
334
335         return ret;
336 }
337
338 static int tb_switch_nvm_read(void *priv, unsigned int offset, void *val,
339                               size_t bytes)
340 {
341         struct tb_nvm *nvm = priv;
342         struct tb_switch *sw = tb_to_switch(nvm->dev);
343         int ret;
344
345         pm_runtime_get_sync(&sw->dev);
346
347         if (!mutex_trylock(&sw->tb->lock)) {
348                 ret = restart_syscall();
349                 goto out;
350         }
351
352         ret = nvm_read(sw, offset, val, bytes);
353         mutex_unlock(&sw->tb->lock);
354
355 out:
356         pm_runtime_mark_last_busy(&sw->dev);
357         pm_runtime_put_autosuspend(&sw->dev);
358
359         return ret;
360 }
361
362 static int tb_switch_nvm_write(void *priv, unsigned int offset, void *val,
363                                size_t bytes)
364 {
365         struct tb_nvm *nvm = priv;
366         struct tb_switch *sw = tb_to_switch(nvm->dev);
367         int ret;
368
369         if (!mutex_trylock(&sw->tb->lock))
370                 return restart_syscall();
371
372         /*
373          * Since writing the NVM image might require some special steps,
374          * for example when CSS headers are written, we cache the image
375          * locally here and handle the special cases when the user asks
376          * us to authenticate the image.
377          */
378         ret = tb_nvm_write_buf(nvm, offset, val, bytes);
379         mutex_unlock(&sw->tb->lock);
380
381         return ret;
382 }
383
384 static int tb_switch_nvm_add(struct tb_switch *sw)
385 {
386         struct tb_nvm *nvm;
387         u32 val;
388         int ret;
389
390         if (!nvm_readable(sw))
391                 return 0;
392
393         /*
394          * The NVM format of non-Intel hardware is not known so
395          * currently restrict NVM upgrade for Intel hardware. We may
396          * relax this in the future when we learn other NVM formats.
397          */
398         if (sw->config.vendor_id != PCI_VENDOR_ID_INTEL &&
399             sw->config.vendor_id != 0x8087) {
400                 dev_info(&sw->dev,
401                          "NVM format of vendor %#x is not known, disabling NVM upgrade\n",
402                          sw->config.vendor_id);
403                 return 0;
404         }
405
406         nvm = tb_nvm_alloc(&sw->dev);
407         if (IS_ERR(nvm))
408                 return PTR_ERR(nvm);
409
410         /*
411          * If the switch is in safe-mode the only accessible portion of
412          * the NVM is the non-active one where userspace is expected to
413          * write new functional NVM.
414          */
415         if (!sw->safe_mode) {
416                 u32 nvm_size, hdr_size;
417
418                 ret = nvm_read(sw, NVM_FLASH_SIZE, &val, sizeof(val));
419                 if (ret)
420                         goto err_nvm;
421
422                 hdr_size = sw->generation < 3 ? SZ_8K : SZ_16K;
423                 nvm_size = (SZ_1M << (val & 7)) / 8;
424                 nvm_size = (nvm_size - hdr_size) / 2;
425
426                 ret = nvm_read(sw, NVM_VERSION, &val, sizeof(val));
427                 if (ret)
428                         goto err_nvm;
429
430                 nvm->major = val >> 16;
431                 nvm->minor = val >> 8;
432
433                 ret = tb_nvm_add_active(nvm, nvm_size, tb_switch_nvm_read);
434                 if (ret)
435                         goto err_nvm;
436         }
437
438         if (!sw->no_nvm_upgrade) {
439                 ret = tb_nvm_add_non_active(nvm, NVM_MAX_SIZE,
440                                             tb_switch_nvm_write);
441                 if (ret)
442                         goto err_nvm;
443         }
444
445         sw->nvm = nvm;
446         return 0;
447
448 err_nvm:
449         tb_nvm_free(nvm);
450         return ret;
451 }
452
453 static void tb_switch_nvm_remove(struct tb_switch *sw)
454 {
455         struct tb_nvm *nvm;
456
457         nvm = sw->nvm;
458         sw->nvm = NULL;
459
460         if (!nvm)
461                 return;
462
463         /* Remove authentication status in case the switch is unplugged */
464         if (!nvm->authenticating)
465                 nvm_clear_auth_status(sw);
466
467         tb_nvm_free(nvm);
468 }
469
470 /* port utility functions */
471
472 static const char *tb_port_type(const struct tb_regs_port_header *port)
473 {
474         switch (port->type >> 16) {
475         case 0:
476                 switch ((u8) port->type) {
477                 case 0:
478                         return "Inactive";
479                 case 1:
480                         return "Port";
481                 case 2:
482                         return "NHI";
483                 default:
484                         return "unknown";
485                 }
486         case 0x2:
487                 return "Ethernet";
488         case 0x8:
489                 return "SATA";
490         case 0xe:
491                 return "DP/HDMI";
492         case 0x10:
493                 return "PCIe";
494         case 0x20:
495                 return "USB";
496         default:
497                 return "unknown";
498         }
499 }
500
501 static void tb_dump_port(struct tb *tb, const struct tb_port *port)
502 {
503         const struct tb_regs_port_header *regs = &port->config;
504
505         tb_dbg(tb,
506                " Port %d: %x:%x (Revision: %d, TB Version: %d, Type: %s (%#x))\n",
507                regs->port_number, regs->vendor_id, regs->device_id,
508                regs->revision, regs->thunderbolt_version, tb_port_type(regs),
509                regs->type);
510         tb_dbg(tb, "  Max hop id (in/out): %d/%d\n",
511                regs->max_in_hop_id, regs->max_out_hop_id);
512         tb_dbg(tb, "  Max counters: %d\n", regs->max_counters);
513         tb_dbg(tb, "  NFC Credits: %#x\n", regs->nfc_credits);
514         tb_dbg(tb, "  Credits (total/control): %u/%u\n", port->total_credits,
515                port->ctl_credits);
516 }
517
518 /**
519  * tb_port_state() - get connectedness state of a port
520  * @port: the port to check
521  *
522  * The port must have a TB_CAP_PHY (i.e. it should be a real port).
523  *
524  * Return: Returns an enum tb_port_state on success or an error code on failure.
525  */
526 int tb_port_state(struct tb_port *port)
527 {
528         struct tb_cap_phy phy;
529         int res;
530         if (port->cap_phy == 0) {
531                 tb_port_WARN(port, "does not have a PHY\n");
532                 return -EINVAL;
533         }
534         res = tb_port_read(port, &phy, TB_CFG_PORT, port->cap_phy, 2);
535         if (res)
536                 return res;
537         return phy.state;
538 }
539
540 /**
541  * tb_wait_for_port() - wait for a port to become ready
542  * @port: Port to wait
543  * @wait_if_unplugged: Wait also when port is unplugged
544  *
545  * Wait up to 1 second for a port to reach state TB_PORT_UP. If
546  * wait_if_unplugged is set then we also wait if the port is in state
547  * TB_PORT_UNPLUGGED (it takes a while for the device to be registered after
548  * switch resume). Otherwise we only wait if a device is registered but the link
549  * has not yet been established.
550  *
551  * Return: Returns an error code on failure. Returns 0 if the port is not
552  * connected or failed to reach state TB_PORT_UP within one second. Returns 1
553  * if the port is connected and in state TB_PORT_UP.
554  */
555 int tb_wait_for_port(struct tb_port *port, bool wait_if_unplugged)
556 {
557         int retries = 10;
558         int state;
559         if (!port->cap_phy) {
560                 tb_port_WARN(port, "does not have PHY\n");
561                 return -EINVAL;
562         }
563         if (tb_is_upstream_port(port)) {
564                 tb_port_WARN(port, "is the upstream port\n");
565                 return -EINVAL;
566         }
567
568         while (retries--) {
569                 state = tb_port_state(port);
570                 if (state < 0)
571                         return state;
572                 if (state == TB_PORT_DISABLED) {
573                         tb_port_dbg(port, "is disabled (state: 0)\n");
574                         return 0;
575                 }
576                 if (state == TB_PORT_UNPLUGGED) {
577                         if (wait_if_unplugged) {
578                                 /* used during resume */
579                                 tb_port_dbg(port,
580                                             "is unplugged (state: 7), retrying...\n");
581                                 msleep(100);
582                                 continue;
583                         }
584                         tb_port_dbg(port, "is unplugged (state: 7)\n");
585                         return 0;
586                 }
587                 if (state == TB_PORT_UP) {
588                         tb_port_dbg(port, "is connected, link is up (state: 2)\n");
589                         return 1;
590                 }
591
592                 /*
593                  * After plug-in the state is TB_PORT_CONNECTING. Give it some
594                  * time.
595                  */
596                 tb_port_dbg(port,
597                             "is connected, link is not up (state: %d), retrying...\n",
598                             state);
599                 msleep(100);
600         }
601         tb_port_warn(port,
602                      "failed to reach state TB_PORT_UP. Ignoring port...\n");
603         return 0;
604 }
605
606 /**
607  * tb_port_add_nfc_credits() - add/remove non flow controlled credits to port
608  * @port: Port to add/remove NFC credits
609  * @credits: Credits to add/remove
610  *
611  * Change the number of NFC credits allocated to @port by @credits. To remove
612  * NFC credits pass a negative amount of credits.
613  *
614  * Return: Returns 0 on success or an error code on failure.
615  */
616 int tb_port_add_nfc_credits(struct tb_port *port, int credits)
617 {
618         u32 nfc_credits;
619
620         if (credits == 0 || port->sw->is_unplugged)
621                 return 0;
622
623         /*
624          * USB4 restricts programming NFC buffers to lane adapters only
625          * so skip other ports.
626          */
627         if (tb_switch_is_usb4(port->sw) && !tb_port_is_null(port))
628                 return 0;
629
630         nfc_credits = port->config.nfc_credits & ADP_CS_4_NFC_BUFFERS_MASK;
631         if (credits < 0)
632                 credits = max_t(int, -nfc_credits, credits);
633
634         nfc_credits += credits;
635
636         tb_port_dbg(port, "adding %d NFC credits to %lu", credits,
637                     port->config.nfc_credits & ADP_CS_4_NFC_BUFFERS_MASK);
638
639         port->config.nfc_credits &= ~ADP_CS_4_NFC_BUFFERS_MASK;
640         port->config.nfc_credits |= nfc_credits;
641
642         return tb_port_write(port, &port->config.nfc_credits,
643                              TB_CFG_PORT, ADP_CS_4, 1);
644 }
645
646 /**
647  * tb_port_clear_counter() - clear a counter in TB_CFG_COUNTER
648  * @port: Port whose counters to clear
649  * @counter: Counter index to clear
650  *
651  * Return: Returns 0 on success or an error code on failure.
652  */
653 int tb_port_clear_counter(struct tb_port *port, int counter)
654 {
655         u32 zero[3] = { 0, 0, 0 };
656         tb_port_dbg(port, "clearing counter %d\n", counter);
657         return tb_port_write(port, zero, TB_CFG_COUNTERS, 3 * counter, 3);
658 }
659
660 /**
661  * tb_port_unlock() - Unlock downstream port
662  * @port: Port to unlock
663  *
664  * Needed for USB4 but can be called for any CIO/USB4 ports. Makes the
665  * downstream router accessible for CM.
666  */
667 int tb_port_unlock(struct tb_port *port)
668 {
669         if (tb_switch_is_icm(port->sw))
670                 return 0;
671         if (!tb_port_is_null(port))
672                 return -EINVAL;
673         if (tb_switch_is_usb4(port->sw))
674                 return usb4_port_unlock(port);
675         return 0;
676 }
677
678 static int __tb_port_enable(struct tb_port *port, bool enable)
679 {
680         int ret;
681         u32 phy;
682
683         if (!tb_port_is_null(port))
684                 return -EINVAL;
685
686         ret = tb_port_read(port, &phy, TB_CFG_PORT,
687                            port->cap_phy + LANE_ADP_CS_1, 1);
688         if (ret)
689                 return ret;
690
691         if (enable)
692                 phy &= ~LANE_ADP_CS_1_LD;
693         else
694                 phy |= LANE_ADP_CS_1_LD;
695
696
697         ret = tb_port_write(port, &phy, TB_CFG_PORT,
698                             port->cap_phy + LANE_ADP_CS_1, 1);
699         if (ret)
700                 return ret;
701
702         tb_port_dbg(port, "lane %sabled\n", enable ? "en" : "dis");
703         return 0;
704 }
705
706 /**
707  * tb_port_enable() - Enable lane adapter
708  * @port: Port to enable (can be %NULL)
709  *
710  * This is used for lane 0 and 1 adapters to enable it.
711  */
712 int tb_port_enable(struct tb_port *port)
713 {
714         return __tb_port_enable(port, true);
715 }
716
717 /**
718  * tb_port_disable() - Disable lane adapter
719  * @port: Port to disable (can be %NULL)
720  *
721  * This is used for lane 0 and 1 adapters to disable it.
722  */
723 int tb_port_disable(struct tb_port *port)
724 {
725         return __tb_port_enable(port, false);
726 }
727
728 /*
729  * tb_init_port() - initialize a port
730  *
731  * This is a helper method for tb_switch_alloc. Does not check or initialize
732  * any downstream switches.
733  *
734  * Return: Returns 0 on success or an error code on failure.
735  */
736 static int tb_init_port(struct tb_port *port)
737 {
738         int res;
739         int cap;
740
741         INIT_LIST_HEAD(&port->list);
742
743         /* Control adapter does not have configuration space */
744         if (!port->port)
745                 return 0;
746
747         res = tb_port_read(port, &port->config, TB_CFG_PORT, 0, 8);
748         if (res) {
749                 if (res == -ENODEV) {
750                         tb_dbg(port->sw->tb, " Port %d: not implemented\n",
751                                port->port);
752                         port->disabled = true;
753                         return 0;
754                 }
755                 return res;
756         }
757
758         /* Port 0 is the switch itself and has no PHY. */
759         if (port->config.type == TB_TYPE_PORT) {
760                 cap = tb_port_find_cap(port, TB_PORT_CAP_PHY);
761
762                 if (cap > 0)
763                         port->cap_phy = cap;
764                 else
765                         tb_port_WARN(port, "non switch port without a PHY\n");
766
767                 cap = tb_port_find_cap(port, TB_PORT_CAP_USB4);
768                 if (cap > 0)
769                         port->cap_usb4 = cap;
770
771                 /*
772                  * USB4 ports the buffers allocated for the control path
773                  * can be read from the path config space. Legacy
774                  * devices we use hard-coded value.
775                  */
776                 if (tb_switch_is_usb4(port->sw)) {
777                         struct tb_regs_hop hop;
778
779                         if (!tb_port_read(port, &hop, TB_CFG_HOPS, 0, 2))
780                                 port->ctl_credits = hop.initial_credits;
781                 }
782                 if (!port->ctl_credits)
783                         port->ctl_credits = 2;
784
785         } else {
786                 cap = tb_port_find_cap(port, TB_PORT_CAP_ADAP);
787                 if (cap > 0)
788                         port->cap_adap = cap;
789         }
790
791         port->total_credits =
792                 (port->config.nfc_credits & ADP_CS_4_TOTAL_BUFFERS_MASK) >>
793                 ADP_CS_4_TOTAL_BUFFERS_SHIFT;
794
795         tb_dump_port(port->sw->tb, port);
796         return 0;
797 }
798
799 static int tb_port_alloc_hopid(struct tb_port *port, bool in, int min_hopid,
800                                int max_hopid)
801 {
802         int port_max_hopid;
803         struct ida *ida;
804
805         if (in) {
806                 port_max_hopid = port->config.max_in_hop_id;
807                 ida = &port->in_hopids;
808         } else {
809                 port_max_hopid = port->config.max_out_hop_id;
810                 ida = &port->out_hopids;
811         }
812
813         /*
814          * NHI can use HopIDs 1-max for other adapters HopIDs 0-7 are
815          * reserved.
816          */
817         if (!tb_port_is_nhi(port) && min_hopid < TB_PATH_MIN_HOPID)
818                 min_hopid = TB_PATH_MIN_HOPID;
819
820         if (max_hopid < 0 || max_hopid > port_max_hopid)
821                 max_hopid = port_max_hopid;
822
823         return ida_simple_get(ida, min_hopid, max_hopid + 1, GFP_KERNEL);
824 }
825
826 /**
827  * tb_port_alloc_in_hopid() - Allocate input HopID from port
828  * @port: Port to allocate HopID for
829  * @min_hopid: Minimum acceptable input HopID
830  * @max_hopid: Maximum acceptable input HopID
831  *
832  * Return: HopID between @min_hopid and @max_hopid or negative errno in
833  * case of error.
834  */
835 int tb_port_alloc_in_hopid(struct tb_port *port, int min_hopid, int max_hopid)
836 {
837         return tb_port_alloc_hopid(port, true, min_hopid, max_hopid);
838 }
839
840 /**
841  * tb_port_alloc_out_hopid() - Allocate output HopID from port
842  * @port: Port to allocate HopID for
843  * @min_hopid: Minimum acceptable output HopID
844  * @max_hopid: Maximum acceptable output HopID
845  *
846  * Return: HopID between @min_hopid and @max_hopid or negative errno in
847  * case of error.
848  */
849 int tb_port_alloc_out_hopid(struct tb_port *port, int min_hopid, int max_hopid)
850 {
851         return tb_port_alloc_hopid(port, false, min_hopid, max_hopid);
852 }
853
854 /**
855  * tb_port_release_in_hopid() - Release allocated input HopID from port
856  * @port: Port whose HopID to release
857  * @hopid: HopID to release
858  */
859 void tb_port_release_in_hopid(struct tb_port *port, int hopid)
860 {
861         ida_simple_remove(&port->in_hopids, hopid);
862 }
863
864 /**
865  * tb_port_release_out_hopid() - Release allocated output HopID from port
866  * @port: Port whose HopID to release
867  * @hopid: HopID to release
868  */
869 void tb_port_release_out_hopid(struct tb_port *port, int hopid)
870 {
871         ida_simple_remove(&port->out_hopids, hopid);
872 }
873
874 static inline bool tb_switch_is_reachable(const struct tb_switch *parent,
875                                           const struct tb_switch *sw)
876 {
877         u64 mask = (1ULL << parent->config.depth * 8) - 1;
878         return (tb_route(parent) & mask) == (tb_route(sw) & mask);
879 }
880
881 /**
882  * tb_next_port_on_path() - Return next port for given port on a path
883  * @start: Start port of the walk
884  * @end: End port of the walk
885  * @prev: Previous port (%NULL if this is the first)
886  *
887  * This function can be used to walk from one port to another if they
888  * are connected through zero or more switches. If the @prev is dual
889  * link port, the function follows that link and returns another end on
890  * that same link.
891  *
892  * If the @end port has been reached, return %NULL.
893  *
894  * Domain tb->lock must be held when this function is called.
895  */
896 struct tb_port *tb_next_port_on_path(struct tb_port *start, struct tb_port *end,
897                                      struct tb_port *prev)
898 {
899         struct tb_port *next;
900
901         if (!prev)
902                 return start;
903
904         if (prev->sw == end->sw) {
905                 if (prev == end)
906                         return NULL;
907                 return end;
908         }
909
910         if (tb_switch_is_reachable(prev->sw, end->sw)) {
911                 next = tb_port_at(tb_route(end->sw), prev->sw);
912                 /* Walk down the topology if next == prev */
913                 if (prev->remote &&
914                     (next == prev || next->dual_link_port == prev))
915                         next = prev->remote;
916         } else {
917                 if (tb_is_upstream_port(prev)) {
918                         next = prev->remote;
919                 } else {
920                         next = tb_upstream_port(prev->sw);
921                         /*
922                          * Keep the same link if prev and next are both
923                          * dual link ports.
924                          */
925                         if (next->dual_link_port &&
926                             next->link_nr != prev->link_nr) {
927                                 next = next->dual_link_port;
928                         }
929                 }
930         }
931
932         return next != prev ? next : NULL;
933 }
934
935 /**
936  * tb_port_get_link_speed() - Get current link speed
937  * @port: Port to check (USB4 or CIO)
938  *
939  * Returns link speed in Gb/s or negative errno in case of failure.
940  */
941 int tb_port_get_link_speed(struct tb_port *port)
942 {
943         u32 val, speed;
944         int ret;
945
946         if (!port->cap_phy)
947                 return -EINVAL;
948
949         ret = tb_port_read(port, &val, TB_CFG_PORT,
950                            port->cap_phy + LANE_ADP_CS_1, 1);
951         if (ret)
952                 return ret;
953
954         speed = (val & LANE_ADP_CS_1_CURRENT_SPEED_MASK) >>
955                 LANE_ADP_CS_1_CURRENT_SPEED_SHIFT;
956         return speed == LANE_ADP_CS_1_CURRENT_SPEED_GEN3 ? 20 : 10;
957 }
958
959 /**
960  * tb_port_get_link_width() - Get current link width
961  * @port: Port to check (USB4 or CIO)
962  *
963  * Returns link width. Return values can be 1 (Single-Lane), 2 (Dual-Lane)
964  * or negative errno in case of failure.
965  */
966 int tb_port_get_link_width(struct tb_port *port)
967 {
968         u32 val;
969         int ret;
970
971         if (!port->cap_phy)
972                 return -EINVAL;
973
974         ret = tb_port_read(port, &val, TB_CFG_PORT,
975                            port->cap_phy + LANE_ADP_CS_1, 1);
976         if (ret)
977                 return ret;
978
979         return (val & LANE_ADP_CS_1_CURRENT_WIDTH_MASK) >>
980                 LANE_ADP_CS_1_CURRENT_WIDTH_SHIFT;
981 }
982
983 static bool tb_port_is_width_supported(struct tb_port *port, int width)
984 {
985         u32 phy, widths;
986         int ret;
987
988         if (!port->cap_phy)
989                 return false;
990
991         ret = tb_port_read(port, &phy, TB_CFG_PORT,
992                            port->cap_phy + LANE_ADP_CS_0, 1);
993         if (ret)
994                 return false;
995
996         widths = (phy & LANE_ADP_CS_0_SUPPORTED_WIDTH_MASK) >>
997                 LANE_ADP_CS_0_SUPPORTED_WIDTH_SHIFT;
998
999         return !!(widths & width);
1000 }
1001
1002 /**
1003  * tb_port_set_link_width() - Set target link width of the lane adapter
1004  * @port: Lane adapter
1005  * @width: Target link width (%1 or %2)
1006  *
1007  * Sets the target link width of the lane adapter to @width. Does not
1008  * enable/disable lane bonding. For that call tb_port_set_lane_bonding().
1009  *
1010  * Return: %0 in case of success and negative errno in case of error
1011  */
1012 int tb_port_set_link_width(struct tb_port *port, unsigned int width)
1013 {
1014         u32 val;
1015         int ret;
1016
1017         if (!port->cap_phy)
1018                 return -EINVAL;
1019
1020         ret = tb_port_read(port, &val, TB_CFG_PORT,
1021                            port->cap_phy + LANE_ADP_CS_1, 1);
1022         if (ret)
1023                 return ret;
1024
1025         val &= ~LANE_ADP_CS_1_TARGET_WIDTH_MASK;
1026         switch (width) {
1027         case 1:
1028                 val |= LANE_ADP_CS_1_TARGET_WIDTH_SINGLE <<
1029                         LANE_ADP_CS_1_TARGET_WIDTH_SHIFT;
1030                 break;
1031         case 2:
1032                 val |= LANE_ADP_CS_1_TARGET_WIDTH_DUAL <<
1033                         LANE_ADP_CS_1_TARGET_WIDTH_SHIFT;
1034                 break;
1035         default:
1036                 return -EINVAL;
1037         }
1038
1039         return tb_port_write(port, &val, TB_CFG_PORT,
1040                              port->cap_phy + LANE_ADP_CS_1, 1);
1041 }
1042
1043 /**
1044  * tb_port_set_lane_bonding() - Enable/disable lane bonding
1045  * @port: Lane adapter
1046  * @bonding: enable/disable bonding
1047  *
1048  * Enables or disables lane bonding. This should be called after target
1049  * link width has been set (tb_port_set_link_width()). Note in most
1050  * cases one should use tb_port_lane_bonding_enable() instead to enable
1051  * lane bonding.
1052  *
1053  * As a side effect sets @port->bonding accordingly (and does the same
1054  * for lane 1 too).
1055  *
1056  * Return: %0 in case of success and negative errno in case of error
1057  */
1058 int tb_port_set_lane_bonding(struct tb_port *port, bool bonding)
1059 {
1060         u32 val;
1061         int ret;
1062
1063         if (!port->cap_phy)
1064                 return -EINVAL;
1065
1066         ret = tb_port_read(port, &val, TB_CFG_PORT,
1067                            port->cap_phy + LANE_ADP_CS_1, 1);
1068         if (ret)
1069                 return ret;
1070
1071         if (bonding)
1072                 val |= LANE_ADP_CS_1_LB;
1073         else
1074                 val &= ~LANE_ADP_CS_1_LB;
1075
1076         ret = tb_port_write(port, &val, TB_CFG_PORT,
1077                             port->cap_phy + LANE_ADP_CS_1, 1);
1078         if (ret)
1079                 return ret;
1080
1081         /*
1082          * When lane 0 bonding is set it will affect lane 1 too so
1083          * update both.
1084          */
1085         port->bonded = bonding;
1086         port->dual_link_port->bonded = bonding;
1087
1088         return 0;
1089 }
1090
1091 /**
1092  * tb_port_lane_bonding_enable() - Enable bonding on port
1093  * @port: port to enable
1094  *
1095  * Enable bonding by setting the link width of the port and the other
1096  * port in case of dual link port. Does not wait for the link to
1097  * actually reach the bonded state so caller needs to call
1098  * tb_port_wait_for_link_width() before enabling any paths through the
1099  * link to make sure the link is in expected state.
1100  *
1101  * Return: %0 in case of success and negative errno in case of error
1102  */
1103 int tb_port_lane_bonding_enable(struct tb_port *port)
1104 {
1105         int ret;
1106
1107         /*
1108          * Enable lane bonding for both links if not already enabled by
1109          * for example the boot firmware.
1110          */
1111         ret = tb_port_get_link_width(port);
1112         if (ret == 1) {
1113                 ret = tb_port_set_link_width(port, 2);
1114                 if (ret)
1115                         goto err_lane0;
1116         }
1117
1118         ret = tb_port_get_link_width(port->dual_link_port);
1119         if (ret == 1) {
1120                 ret = tb_port_set_link_width(port->dual_link_port, 2);
1121                 if (ret)
1122                         goto err_lane0;
1123         }
1124
1125         ret = tb_port_set_lane_bonding(port, true);
1126         if (ret)
1127                 goto err_lane1;
1128
1129         return 0;
1130
1131 err_lane1:
1132         tb_port_set_link_width(port->dual_link_port, 1);
1133 err_lane0:
1134         tb_port_set_link_width(port, 1);
1135         return ret;
1136 }
1137
1138 /**
1139  * tb_port_lane_bonding_disable() - Disable bonding on port
1140  * @port: port to disable
1141  *
1142  * Disable bonding by setting the link width of the port and the
1143  * other port in case of dual link port.
1144  */
1145 void tb_port_lane_bonding_disable(struct tb_port *port)
1146 {
1147         tb_port_set_lane_bonding(port, false);
1148         tb_port_set_link_width(port->dual_link_port, 1);
1149         tb_port_set_link_width(port, 1);
1150 }
1151
1152 /**
1153  * tb_port_wait_for_link_width() - Wait until link reaches specific width
1154  * @port: Port to wait for
1155  * @width: Expected link width (%1 or %2)
1156  * @timeout_msec: Timeout in ms how long to wait
1157  *
1158  * Should be used after both ends of the link have been bonded (or
1159  * bonding has been disabled) to wait until the link actually reaches
1160  * the expected state. Returns %-ETIMEDOUT if the @width was not reached
1161  * within the given timeout, %0 if it did.
1162  */
1163 int tb_port_wait_for_link_width(struct tb_port *port, int width,
1164                                 int timeout_msec)
1165 {
1166         ktime_t timeout = ktime_add_ms(ktime_get(), timeout_msec);
1167         int ret;
1168
1169         do {
1170                 ret = tb_port_get_link_width(port);
1171                 if (ret < 0) {
1172                         /*
1173                          * Sometimes we get port locked error when
1174                          * polling the lanes so we can ignore it and
1175                          * retry.
1176                          */
1177                         if (ret != -EACCES)
1178                                 return ret;
1179                 } else if (ret == width) {
1180                         return 0;
1181                 }
1182
1183                 usleep_range(1000, 2000);
1184         } while (ktime_before(ktime_get(), timeout));
1185
1186         return -ETIMEDOUT;
1187 }
1188
1189 static int tb_port_do_update_credits(struct tb_port *port)
1190 {
1191         u32 nfc_credits;
1192         int ret;
1193
1194         ret = tb_port_read(port, &nfc_credits, TB_CFG_PORT, ADP_CS_4, 1);
1195         if (ret)
1196                 return ret;
1197
1198         if (nfc_credits != port->config.nfc_credits) {
1199                 u32 total;
1200
1201                 total = (nfc_credits & ADP_CS_4_TOTAL_BUFFERS_MASK) >>
1202                         ADP_CS_4_TOTAL_BUFFERS_SHIFT;
1203
1204                 tb_port_dbg(port, "total credits changed %u -> %u\n",
1205                             port->total_credits, total);
1206
1207                 port->config.nfc_credits = nfc_credits;
1208                 port->total_credits = total;
1209         }
1210
1211         return 0;
1212 }
1213
1214 /**
1215  * tb_port_update_credits() - Re-read port total credits
1216  * @port: Port to update
1217  *
1218  * After the link is bonded (or bonding was disabled) the port total
1219  * credits may change, so this function needs to be called to re-read
1220  * the credits. Updates also the second lane adapter.
1221  */
1222 int tb_port_update_credits(struct tb_port *port)
1223 {
1224         int ret;
1225
1226         ret = tb_port_do_update_credits(port);
1227         if (ret)
1228                 return ret;
1229         return tb_port_do_update_credits(port->dual_link_port);
1230 }
1231
1232 static int __tb_port_pm_secondary_set(struct tb_port *port, bool secondary)
1233 {
1234         u32 phy;
1235         int ret;
1236
1237         ret = tb_port_read(port, &phy, TB_CFG_PORT,
1238                            port->cap_phy + LANE_ADP_CS_1, 1);
1239         if (ret)
1240                 return ret;
1241
1242         if (secondary)
1243                 phy |= LANE_ADP_CS_1_PMS;
1244         else
1245                 phy &= ~LANE_ADP_CS_1_PMS;
1246
1247         return tb_port_write(port, &phy, TB_CFG_PORT,
1248                              port->cap_phy + LANE_ADP_CS_1, 1);
1249 }
1250
1251 static int tb_port_pm_secondary_enable(struct tb_port *port)
1252 {
1253         return __tb_port_pm_secondary_set(port, true);
1254 }
1255
1256 static int tb_port_pm_secondary_disable(struct tb_port *port)
1257 {
1258         return __tb_port_pm_secondary_set(port, false);
1259 }
1260
1261 /* Called for USB4 or Titan Ridge routers only */
1262 static bool tb_port_clx_supported(struct tb_port *port, unsigned int clx_mask)
1263 {
1264         u32 val, mask = 0;
1265         bool ret;
1266
1267         /* Don't enable CLx in case of two single-lane links */
1268         if (!port->bonded && port->dual_link_port)
1269                 return false;
1270
1271         /* Don't enable CLx in case of inter-domain link */
1272         if (port->xdomain)
1273                 return false;
1274
1275         if (tb_switch_is_usb4(port->sw)) {
1276                 if (!usb4_port_clx_supported(port))
1277                         return false;
1278         } else if (!tb_lc_is_clx_supported(port)) {
1279                 return false;
1280         }
1281
1282         if (clx_mask & TB_CL1) {
1283                 /* CL0s and CL1 are enabled and supported together */
1284                 mask |= LANE_ADP_CS_0_CL0S_SUPPORT | LANE_ADP_CS_0_CL1_SUPPORT;
1285         }
1286         if (clx_mask & TB_CL2)
1287                 mask |= LANE_ADP_CS_0_CL2_SUPPORT;
1288
1289         ret = tb_port_read(port, &val, TB_CFG_PORT,
1290                            port->cap_phy + LANE_ADP_CS_0, 1);
1291         if (ret)
1292                 return false;
1293
1294         return !!(val & mask);
1295 }
1296
1297 static int __tb_port_clx_set(struct tb_port *port, enum tb_clx clx, bool enable)
1298 {
1299         u32 phy, mask;
1300         int ret;
1301
1302         /* CL0s and CL1 are enabled and supported together */
1303         if (clx == TB_CL1)
1304                 mask = LANE_ADP_CS_1_CL0S_ENABLE | LANE_ADP_CS_1_CL1_ENABLE;
1305         else
1306                 /* For now we support only CL0s and CL1. Not CL2 */
1307                 return -EOPNOTSUPP;
1308
1309         ret = tb_port_read(port, &phy, TB_CFG_PORT,
1310                            port->cap_phy + LANE_ADP_CS_1, 1);
1311         if (ret)
1312                 return ret;
1313
1314         if (enable)
1315                 phy |= mask;
1316         else
1317                 phy &= ~mask;
1318
1319         return tb_port_write(port, &phy, TB_CFG_PORT,
1320                              port->cap_phy + LANE_ADP_CS_1, 1);
1321 }
1322
1323 static int tb_port_clx_disable(struct tb_port *port, enum tb_clx clx)
1324 {
1325         return __tb_port_clx_set(port, clx, false);
1326 }
1327
1328 static int tb_port_clx_enable(struct tb_port *port, enum tb_clx clx)
1329 {
1330         return __tb_port_clx_set(port, clx, true);
1331 }
1332
1333 /**
1334  * tb_port_is_clx_enabled() - Is given CL state enabled
1335  * @port: USB4 port to check
1336  * @clx_mask: Mask of CL states to check
1337  *
1338  * Returns true if any of the given CL states is enabled for @port.
1339  */
1340 bool tb_port_is_clx_enabled(struct tb_port *port, unsigned int clx_mask)
1341 {
1342         u32 val, mask = 0;
1343         int ret;
1344
1345         if (!tb_port_clx_supported(port, clx_mask))
1346                 return false;
1347
1348         if (clx_mask & TB_CL1)
1349                 mask |= LANE_ADP_CS_1_CL0S_ENABLE | LANE_ADP_CS_1_CL1_ENABLE;
1350         if (clx_mask & TB_CL2)
1351                 mask |= LANE_ADP_CS_1_CL2_ENABLE;
1352
1353         ret = tb_port_read(port, &val, TB_CFG_PORT,
1354                            port->cap_phy + LANE_ADP_CS_1, 1);
1355         if (ret)
1356                 return false;
1357
1358         return !!(val & mask);
1359 }
1360
1361 static int tb_port_start_lane_initialization(struct tb_port *port)
1362 {
1363         int ret;
1364
1365         if (tb_switch_is_usb4(port->sw))
1366                 return 0;
1367
1368         ret = tb_lc_start_lane_initialization(port);
1369         return ret == -EINVAL ? 0 : ret;
1370 }
1371
1372 /*
1373  * Returns true if the port had something (router, XDomain) connected
1374  * before suspend.
1375  */
1376 static bool tb_port_resume(struct tb_port *port)
1377 {
1378         bool has_remote = tb_port_has_remote(port);
1379
1380         if (port->usb4) {
1381                 usb4_port_device_resume(port->usb4);
1382         } else if (!has_remote) {
1383                 /*
1384                  * For disconnected downstream lane adapters start lane
1385                  * initialization now so we detect future connects.
1386                  *
1387                  * For XDomain start the lane initialzation now so the
1388                  * link gets re-established.
1389                  *
1390                  * This is only needed for non-USB4 ports.
1391                  */
1392                 if (!tb_is_upstream_port(port) || port->xdomain)
1393                         tb_port_start_lane_initialization(port);
1394         }
1395
1396         return has_remote || port->xdomain;
1397 }
1398
1399 /**
1400  * tb_port_is_enabled() - Is the adapter port enabled
1401  * @port: Port to check
1402  */
1403 bool tb_port_is_enabled(struct tb_port *port)
1404 {
1405         switch (port->config.type) {
1406         case TB_TYPE_PCIE_UP:
1407         case TB_TYPE_PCIE_DOWN:
1408                 return tb_pci_port_is_enabled(port);
1409
1410         case TB_TYPE_DP_HDMI_IN:
1411         case TB_TYPE_DP_HDMI_OUT:
1412                 return tb_dp_port_is_enabled(port);
1413
1414         case TB_TYPE_USB3_UP:
1415         case TB_TYPE_USB3_DOWN:
1416                 return tb_usb3_port_is_enabled(port);
1417
1418         default:
1419                 return false;
1420         }
1421 }
1422
1423 /**
1424  * tb_usb3_port_is_enabled() - Is the USB3 adapter port enabled
1425  * @port: USB3 adapter port to check
1426  */
1427 bool tb_usb3_port_is_enabled(struct tb_port *port)
1428 {
1429         u32 data;
1430
1431         if (tb_port_read(port, &data, TB_CFG_PORT,
1432                          port->cap_adap + ADP_USB3_CS_0, 1))
1433                 return false;
1434
1435         return !!(data & ADP_USB3_CS_0_PE);
1436 }
1437
1438 /**
1439  * tb_usb3_port_enable() - Enable USB3 adapter port
1440  * @port: USB3 adapter port to enable
1441  * @enable: Enable/disable the USB3 adapter
1442  */
1443 int tb_usb3_port_enable(struct tb_port *port, bool enable)
1444 {
1445         u32 word = enable ? (ADP_USB3_CS_0_PE | ADP_USB3_CS_0_V)
1446                           : ADP_USB3_CS_0_V;
1447
1448         if (!port->cap_adap)
1449                 return -ENXIO;
1450         return tb_port_write(port, &word, TB_CFG_PORT,
1451                              port->cap_adap + ADP_USB3_CS_0, 1);
1452 }
1453
1454 /**
1455  * tb_pci_port_is_enabled() - Is the PCIe adapter port enabled
1456  * @port: PCIe port to check
1457  */
1458 bool tb_pci_port_is_enabled(struct tb_port *port)
1459 {
1460         u32 data;
1461
1462         if (tb_port_read(port, &data, TB_CFG_PORT,
1463                          port->cap_adap + ADP_PCIE_CS_0, 1))
1464                 return false;
1465
1466         return !!(data & ADP_PCIE_CS_0_PE);
1467 }
1468
1469 /**
1470  * tb_pci_port_enable() - Enable PCIe adapter port
1471  * @port: PCIe port to enable
1472  * @enable: Enable/disable the PCIe adapter
1473  */
1474 int tb_pci_port_enable(struct tb_port *port, bool enable)
1475 {
1476         u32 word = enable ? ADP_PCIE_CS_0_PE : 0x0;
1477         if (!port->cap_adap)
1478                 return -ENXIO;
1479         return tb_port_write(port, &word, TB_CFG_PORT,
1480                              port->cap_adap + ADP_PCIE_CS_0, 1);
1481 }
1482
1483 /**
1484  * tb_dp_port_hpd_is_active() - Is HPD already active
1485  * @port: DP out port to check
1486  *
1487  * Checks if the DP OUT adapter port has HDP bit already set.
1488  */
1489 int tb_dp_port_hpd_is_active(struct tb_port *port)
1490 {
1491         u32 data;
1492         int ret;
1493
1494         ret = tb_port_read(port, &data, TB_CFG_PORT,
1495                            port->cap_adap + ADP_DP_CS_2, 1);
1496         if (ret)
1497                 return ret;
1498
1499         return !!(data & ADP_DP_CS_2_HDP);
1500 }
1501
1502 /**
1503  * tb_dp_port_hpd_clear() - Clear HPD from DP IN port
1504  * @port: Port to clear HPD
1505  *
1506  * If the DP IN port has HDP set, this function can be used to clear it.
1507  */
1508 int tb_dp_port_hpd_clear(struct tb_port *port)
1509 {
1510         u32 data;
1511         int ret;
1512
1513         ret = tb_port_read(port, &data, TB_CFG_PORT,
1514                            port->cap_adap + ADP_DP_CS_3, 1);
1515         if (ret)
1516                 return ret;
1517
1518         data |= ADP_DP_CS_3_HDPC;
1519         return tb_port_write(port, &data, TB_CFG_PORT,
1520                              port->cap_adap + ADP_DP_CS_3, 1);
1521 }
1522
1523 /**
1524  * tb_dp_port_set_hops() - Set video/aux Hop IDs for DP port
1525  * @port: DP IN/OUT port to set hops
1526  * @video: Video Hop ID
1527  * @aux_tx: AUX TX Hop ID
1528  * @aux_rx: AUX RX Hop ID
1529  *
1530  * Programs specified Hop IDs for DP IN/OUT port. Can be called for USB4
1531  * router DP adapters too but does not program the values as the fields
1532  * are read-only.
1533  */
1534 int tb_dp_port_set_hops(struct tb_port *port, unsigned int video,
1535                         unsigned int aux_tx, unsigned int aux_rx)
1536 {
1537         u32 data[2];
1538         int ret;
1539
1540         if (tb_switch_is_usb4(port->sw))
1541                 return 0;
1542
1543         ret = tb_port_read(port, data, TB_CFG_PORT,
1544                            port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1545         if (ret)
1546                 return ret;
1547
1548         data[0] &= ~ADP_DP_CS_0_VIDEO_HOPID_MASK;
1549         data[1] &= ~ADP_DP_CS_1_AUX_RX_HOPID_MASK;
1550         data[1] &= ~ADP_DP_CS_1_AUX_RX_HOPID_MASK;
1551
1552         data[0] |= (video << ADP_DP_CS_0_VIDEO_HOPID_SHIFT) &
1553                 ADP_DP_CS_0_VIDEO_HOPID_MASK;
1554         data[1] |= aux_tx & ADP_DP_CS_1_AUX_TX_HOPID_MASK;
1555         data[1] |= (aux_rx << ADP_DP_CS_1_AUX_RX_HOPID_SHIFT) &
1556                 ADP_DP_CS_1_AUX_RX_HOPID_MASK;
1557
1558         return tb_port_write(port, data, TB_CFG_PORT,
1559                              port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1560 }
1561
1562 /**
1563  * tb_dp_port_is_enabled() - Is DP adapter port enabled
1564  * @port: DP adapter port to check
1565  */
1566 bool tb_dp_port_is_enabled(struct tb_port *port)
1567 {
1568         u32 data[2];
1569
1570         if (tb_port_read(port, data, TB_CFG_PORT, port->cap_adap + ADP_DP_CS_0,
1571                          ARRAY_SIZE(data)))
1572                 return false;
1573
1574         return !!(data[0] & (ADP_DP_CS_0_VE | ADP_DP_CS_0_AE));
1575 }
1576
1577 /**
1578  * tb_dp_port_enable() - Enables/disables DP paths of a port
1579  * @port: DP IN/OUT port
1580  * @enable: Enable/disable DP path
1581  *
1582  * Once Hop IDs are programmed DP paths can be enabled or disabled by
1583  * calling this function.
1584  */
1585 int tb_dp_port_enable(struct tb_port *port, bool enable)
1586 {
1587         u32 data[2];
1588         int ret;
1589
1590         ret = tb_port_read(port, data, TB_CFG_PORT,
1591                           port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1592         if (ret)
1593                 return ret;
1594
1595         if (enable)
1596                 data[0] |= ADP_DP_CS_0_VE | ADP_DP_CS_0_AE;
1597         else
1598                 data[0] &= ~(ADP_DP_CS_0_VE | ADP_DP_CS_0_AE);
1599
1600         return tb_port_write(port, data, TB_CFG_PORT,
1601                              port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1602 }
1603
1604 /* switch utility functions */
1605
1606 static const char *tb_switch_generation_name(const struct tb_switch *sw)
1607 {
1608         switch (sw->generation) {
1609         case 1:
1610                 return "Thunderbolt 1";
1611         case 2:
1612                 return "Thunderbolt 2";
1613         case 3:
1614                 return "Thunderbolt 3";
1615         case 4:
1616                 return "USB4";
1617         default:
1618                 return "Unknown";
1619         }
1620 }
1621
1622 static void tb_dump_switch(const struct tb *tb, const struct tb_switch *sw)
1623 {
1624         const struct tb_regs_switch_header *regs = &sw->config;
1625
1626         tb_dbg(tb, " %s Switch: %x:%x (Revision: %d, TB Version: %d)\n",
1627                tb_switch_generation_name(sw), regs->vendor_id, regs->device_id,
1628                regs->revision, regs->thunderbolt_version);
1629         tb_dbg(tb, "  Max Port Number: %d\n", regs->max_port_number);
1630         tb_dbg(tb, "  Config:\n");
1631         tb_dbg(tb,
1632                 "   Upstream Port Number: %d Depth: %d Route String: %#llx Enabled: %d, PlugEventsDelay: %dms\n",
1633                regs->upstream_port_number, regs->depth,
1634                (((u64) regs->route_hi) << 32) | regs->route_lo,
1635                regs->enabled, regs->plug_events_delay);
1636         tb_dbg(tb, "   unknown1: %#x unknown4: %#x\n",
1637                regs->__unknown1, regs->__unknown4);
1638 }
1639
1640 /**
1641  * tb_switch_reset() - reconfigure route, enable and send TB_CFG_PKG_RESET
1642  * @sw: Switch to reset
1643  *
1644  * Return: Returns 0 on success or an error code on failure.
1645  */
1646 int tb_switch_reset(struct tb_switch *sw)
1647 {
1648         struct tb_cfg_result res;
1649
1650         if (sw->generation > 1)
1651                 return 0;
1652
1653         tb_sw_dbg(sw, "resetting switch\n");
1654
1655         res.err = tb_sw_write(sw, ((u32 *) &sw->config) + 2,
1656                               TB_CFG_SWITCH, 2, 2);
1657         if (res.err)
1658                 return res.err;
1659         res = tb_cfg_reset(sw->tb->ctl, tb_route(sw));
1660         if (res.err > 0)
1661                 return -EIO;
1662         return res.err;
1663 }
1664
1665 /**
1666  * tb_switch_wait_for_bit() - Wait for specified value of bits in offset
1667  * @sw: Router to read the offset value from
1668  * @offset: Offset in the router config space to read from
1669  * @bit: Bit mask in the offset to wait for
1670  * @value: Value of the bits to wait for
1671  * @timeout_msec: Timeout in ms how long to wait
1672  *
1673  * Wait till the specified bits in specified offset reach specified value.
1674  * Returns %0 in case of success, %-ETIMEDOUT if the @value was not reached
1675  * within the given timeout or a negative errno in case of failure.
1676  */
1677 int tb_switch_wait_for_bit(struct tb_switch *sw, u32 offset, u32 bit,
1678                            u32 value, int timeout_msec)
1679 {
1680         ktime_t timeout = ktime_add_ms(ktime_get(), timeout_msec);
1681
1682         do {
1683                 u32 val;
1684                 int ret;
1685
1686                 ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, offset, 1);
1687                 if (ret)
1688                         return ret;
1689
1690                 if ((val & bit) == value)
1691                         return 0;
1692
1693                 usleep_range(50, 100);
1694         } while (ktime_before(ktime_get(), timeout));
1695
1696         return -ETIMEDOUT;
1697 }
1698
1699 /*
1700  * tb_plug_events_active() - enable/disable plug events on a switch
1701  *
1702  * Also configures a sane plug_events_delay of 255ms.
1703  *
1704  * Return: Returns 0 on success or an error code on failure.
1705  */
1706 static int tb_plug_events_active(struct tb_switch *sw, bool active)
1707 {
1708         u32 data;
1709         int res;
1710
1711         if (tb_switch_is_icm(sw) || tb_switch_is_usb4(sw))
1712                 return 0;
1713
1714         sw->config.plug_events_delay = 0xff;
1715         res = tb_sw_write(sw, ((u32 *) &sw->config) + 4, TB_CFG_SWITCH, 4, 1);
1716         if (res)
1717                 return res;
1718
1719         res = tb_sw_read(sw, &data, TB_CFG_SWITCH, sw->cap_plug_events + 1, 1);
1720         if (res)
1721                 return res;
1722
1723         if (active) {
1724                 data = data & 0xFFFFFF83;
1725                 switch (sw->config.device_id) {
1726                 case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
1727                 case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
1728                 case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
1729                         break;
1730                 default:
1731                         /*
1732                          * Skip Alpine Ridge, it needs to have vendor
1733                          * specific USB hotplug event enabled for the
1734                          * internal xHCI to work.
1735                          */
1736                         if (!tb_switch_is_alpine_ridge(sw))
1737                                 data |= TB_PLUG_EVENTS_USB_DISABLE;
1738                 }
1739         } else {
1740                 data = data | 0x7c;
1741         }
1742         return tb_sw_write(sw, &data, TB_CFG_SWITCH,
1743                            sw->cap_plug_events + 1, 1);
1744 }
1745
1746 static ssize_t authorized_show(struct device *dev,
1747                                struct device_attribute *attr,
1748                                char *buf)
1749 {
1750         struct tb_switch *sw = tb_to_switch(dev);
1751
1752         return sprintf(buf, "%u\n", sw->authorized);
1753 }
1754
1755 static int disapprove_switch(struct device *dev, void *not_used)
1756 {
1757         char *envp[] = { "AUTHORIZED=0", NULL };
1758         struct tb_switch *sw;
1759
1760         sw = tb_to_switch(dev);
1761         if (sw && sw->authorized) {
1762                 int ret;
1763
1764                 /* First children */
1765                 ret = device_for_each_child_reverse(&sw->dev, NULL, disapprove_switch);
1766                 if (ret)
1767                         return ret;
1768
1769                 ret = tb_domain_disapprove_switch(sw->tb, sw);
1770                 if (ret)
1771                         return ret;
1772
1773                 sw->authorized = 0;
1774                 kobject_uevent_env(&sw->dev.kobj, KOBJ_CHANGE, envp);
1775         }
1776
1777         return 0;
1778 }
1779
1780 static int tb_switch_set_authorized(struct tb_switch *sw, unsigned int val)
1781 {
1782         char envp_string[13];
1783         int ret = -EINVAL;
1784         char *envp[] = { envp_string, NULL };
1785
1786         if (!mutex_trylock(&sw->tb->lock))
1787                 return restart_syscall();
1788
1789         if (!!sw->authorized == !!val)
1790                 goto unlock;
1791
1792         switch (val) {
1793         /* Disapprove switch */
1794         case 0:
1795                 if (tb_route(sw)) {
1796                         ret = disapprove_switch(&sw->dev, NULL);
1797                         goto unlock;
1798                 }
1799                 break;
1800
1801         /* Approve switch */
1802         case 1:
1803                 if (sw->key)
1804                         ret = tb_domain_approve_switch_key(sw->tb, sw);
1805                 else
1806                         ret = tb_domain_approve_switch(sw->tb, sw);
1807                 break;
1808
1809         /* Challenge switch */
1810         case 2:
1811                 if (sw->key)
1812                         ret = tb_domain_challenge_switch_key(sw->tb, sw);
1813                 break;
1814
1815         default:
1816                 break;
1817         }
1818
1819         if (!ret) {
1820                 sw->authorized = val;
1821                 /*
1822                  * Notify status change to the userspace, informing the new
1823                  * value of /sys/bus/thunderbolt/devices/.../authorized.
1824                  */
1825                 sprintf(envp_string, "AUTHORIZED=%u", sw->authorized);
1826                 kobject_uevent_env(&sw->dev.kobj, KOBJ_CHANGE, envp);
1827         }
1828
1829 unlock:
1830         mutex_unlock(&sw->tb->lock);
1831         return ret;
1832 }
1833
1834 static ssize_t authorized_store(struct device *dev,
1835                                 struct device_attribute *attr,
1836                                 const char *buf, size_t count)
1837 {
1838         struct tb_switch *sw = tb_to_switch(dev);
1839         unsigned int val;
1840         ssize_t ret;
1841
1842         ret = kstrtouint(buf, 0, &val);
1843         if (ret)
1844                 return ret;
1845         if (val > 2)
1846                 return -EINVAL;
1847
1848         pm_runtime_get_sync(&sw->dev);
1849         ret = tb_switch_set_authorized(sw, val);
1850         pm_runtime_mark_last_busy(&sw->dev);
1851         pm_runtime_put_autosuspend(&sw->dev);
1852
1853         return ret ? ret : count;
1854 }
1855 static DEVICE_ATTR_RW(authorized);
1856
1857 static ssize_t boot_show(struct device *dev, struct device_attribute *attr,
1858                          char *buf)
1859 {
1860         struct tb_switch *sw = tb_to_switch(dev);
1861
1862         return sprintf(buf, "%u\n", sw->boot);
1863 }
1864 static DEVICE_ATTR_RO(boot);
1865
1866 static ssize_t device_show(struct device *dev, struct device_attribute *attr,
1867                            char *buf)
1868 {
1869         struct tb_switch *sw = tb_to_switch(dev);
1870
1871         return sprintf(buf, "%#x\n", sw->device);
1872 }
1873 static DEVICE_ATTR_RO(device);
1874
1875 static ssize_t
1876 device_name_show(struct device *dev, struct device_attribute *attr, char *buf)
1877 {
1878         struct tb_switch *sw = tb_to_switch(dev);
1879
1880         return sprintf(buf, "%s\n", sw->device_name ? sw->device_name : "");
1881 }
1882 static DEVICE_ATTR_RO(device_name);
1883
1884 static ssize_t
1885 generation_show(struct device *dev, struct device_attribute *attr, char *buf)
1886 {
1887         struct tb_switch *sw = tb_to_switch(dev);
1888
1889         return sprintf(buf, "%u\n", sw->generation);
1890 }
1891 static DEVICE_ATTR_RO(generation);
1892
1893 static ssize_t key_show(struct device *dev, struct device_attribute *attr,
1894                         char *buf)
1895 {
1896         struct tb_switch *sw = tb_to_switch(dev);
1897         ssize_t ret;
1898
1899         if (!mutex_trylock(&sw->tb->lock))
1900                 return restart_syscall();
1901
1902         if (sw->key)
1903                 ret = sprintf(buf, "%*phN\n", TB_SWITCH_KEY_SIZE, sw->key);
1904         else
1905                 ret = sprintf(buf, "\n");
1906
1907         mutex_unlock(&sw->tb->lock);
1908         return ret;
1909 }
1910
1911 static ssize_t key_store(struct device *dev, struct device_attribute *attr,
1912                          const char *buf, size_t count)
1913 {
1914         struct tb_switch *sw = tb_to_switch(dev);
1915         u8 key[TB_SWITCH_KEY_SIZE];
1916         ssize_t ret = count;
1917         bool clear = false;
1918
1919         if (!strcmp(buf, "\n"))
1920                 clear = true;
1921         else if (hex2bin(key, buf, sizeof(key)))
1922                 return -EINVAL;
1923
1924         if (!mutex_trylock(&sw->tb->lock))
1925                 return restart_syscall();
1926
1927         if (sw->authorized) {
1928                 ret = -EBUSY;
1929         } else {
1930                 kfree(sw->key);
1931                 if (clear) {
1932                         sw->key = NULL;
1933                 } else {
1934                         sw->key = kmemdup(key, sizeof(key), GFP_KERNEL);
1935                         if (!sw->key)
1936                                 ret = -ENOMEM;
1937                 }
1938         }
1939
1940         mutex_unlock(&sw->tb->lock);
1941         return ret;
1942 }
1943 static DEVICE_ATTR(key, 0600, key_show, key_store);
1944
1945 static ssize_t speed_show(struct device *dev, struct device_attribute *attr,
1946                           char *buf)
1947 {
1948         struct tb_switch *sw = tb_to_switch(dev);
1949
1950         return sprintf(buf, "%u.0 Gb/s\n", sw->link_speed);
1951 }
1952
1953 /*
1954  * Currently all lanes must run at the same speed but we expose here
1955  * both directions to allow possible asymmetric links in the future.
1956  */
1957 static DEVICE_ATTR(rx_speed, 0444, speed_show, NULL);
1958 static DEVICE_ATTR(tx_speed, 0444, speed_show, NULL);
1959
1960 static ssize_t lanes_show(struct device *dev, struct device_attribute *attr,
1961                           char *buf)
1962 {
1963         struct tb_switch *sw = tb_to_switch(dev);
1964
1965         return sprintf(buf, "%u\n", sw->link_width);
1966 }
1967
1968 /*
1969  * Currently link has same amount of lanes both directions (1 or 2) but
1970  * expose them separately to allow possible asymmetric links in the future.
1971  */
1972 static DEVICE_ATTR(rx_lanes, 0444, lanes_show, NULL);
1973 static DEVICE_ATTR(tx_lanes, 0444, lanes_show, NULL);
1974
1975 static ssize_t nvm_authenticate_show(struct device *dev,
1976         struct device_attribute *attr, char *buf)
1977 {
1978         struct tb_switch *sw = tb_to_switch(dev);
1979         u32 status;
1980
1981         nvm_get_auth_status(sw, &status);
1982         return sprintf(buf, "%#x\n", status);
1983 }
1984
1985 static ssize_t nvm_authenticate_sysfs(struct device *dev, const char *buf,
1986                                       bool disconnect)
1987 {
1988         struct tb_switch *sw = tb_to_switch(dev);
1989         int val, ret;
1990
1991         pm_runtime_get_sync(&sw->dev);
1992
1993         if (!mutex_trylock(&sw->tb->lock)) {
1994                 ret = restart_syscall();
1995                 goto exit_rpm;
1996         }
1997
1998         /* If NVMem devices are not yet added */
1999         if (!sw->nvm) {
2000                 ret = -EAGAIN;
2001                 goto exit_unlock;
2002         }
2003
2004         ret = kstrtoint(buf, 10, &val);
2005         if (ret)
2006                 goto exit_unlock;
2007
2008         /* Always clear the authentication status */
2009         nvm_clear_auth_status(sw);
2010
2011         if (val > 0) {
2012                 if (val == AUTHENTICATE_ONLY) {
2013                         if (disconnect)
2014                                 ret = -EINVAL;
2015                         else
2016                                 ret = nvm_authenticate(sw, true);
2017                 } else {
2018                         if (!sw->nvm->flushed) {
2019                                 if (!sw->nvm->buf) {
2020                                         ret = -EINVAL;
2021                                         goto exit_unlock;
2022                                 }
2023
2024                                 ret = nvm_validate_and_write(sw);
2025                                 if (ret || val == WRITE_ONLY)
2026                                         goto exit_unlock;
2027                         }
2028                         if (val == WRITE_AND_AUTHENTICATE) {
2029                                 if (disconnect)
2030                                         ret = tb_lc_force_power(sw);
2031                                 else
2032                                         ret = nvm_authenticate(sw, false);
2033                         }
2034                 }
2035         }
2036
2037 exit_unlock:
2038         mutex_unlock(&sw->tb->lock);
2039 exit_rpm:
2040         pm_runtime_mark_last_busy(&sw->dev);
2041         pm_runtime_put_autosuspend(&sw->dev);
2042
2043         return ret;
2044 }
2045
2046 static ssize_t nvm_authenticate_store(struct device *dev,
2047         struct device_attribute *attr, const char *buf, size_t count)
2048 {
2049         int ret = nvm_authenticate_sysfs(dev, buf, false);
2050         if (ret)
2051                 return ret;
2052         return count;
2053 }
2054 static DEVICE_ATTR_RW(nvm_authenticate);
2055
2056 static ssize_t nvm_authenticate_on_disconnect_show(struct device *dev,
2057         struct device_attribute *attr, char *buf)
2058 {
2059         return nvm_authenticate_show(dev, attr, buf);
2060 }
2061
2062 static ssize_t nvm_authenticate_on_disconnect_store(struct device *dev,
2063         struct device_attribute *attr, const char *buf, size_t count)
2064 {
2065         int ret;
2066
2067         ret = nvm_authenticate_sysfs(dev, buf, true);
2068         return ret ? ret : count;
2069 }
2070 static DEVICE_ATTR_RW(nvm_authenticate_on_disconnect);
2071
2072 static ssize_t nvm_version_show(struct device *dev,
2073                                 struct device_attribute *attr, char *buf)
2074 {
2075         struct tb_switch *sw = tb_to_switch(dev);
2076         int ret;
2077
2078         if (!mutex_trylock(&sw->tb->lock))
2079                 return restart_syscall();
2080
2081         if (sw->safe_mode)
2082                 ret = -ENODATA;
2083         else if (!sw->nvm)
2084                 ret = -EAGAIN;
2085         else
2086                 ret = sprintf(buf, "%x.%x\n", sw->nvm->major, sw->nvm->minor);
2087
2088         mutex_unlock(&sw->tb->lock);
2089
2090         return ret;
2091 }
2092 static DEVICE_ATTR_RO(nvm_version);
2093
2094 static ssize_t vendor_show(struct device *dev, struct device_attribute *attr,
2095                            char *buf)
2096 {
2097         struct tb_switch *sw = tb_to_switch(dev);
2098
2099         return sprintf(buf, "%#x\n", sw->vendor);
2100 }
2101 static DEVICE_ATTR_RO(vendor);
2102
2103 static ssize_t
2104 vendor_name_show(struct device *dev, struct device_attribute *attr, char *buf)
2105 {
2106         struct tb_switch *sw = tb_to_switch(dev);
2107
2108         return sprintf(buf, "%s\n", sw->vendor_name ? sw->vendor_name : "");
2109 }
2110 static DEVICE_ATTR_RO(vendor_name);
2111
2112 static ssize_t unique_id_show(struct device *dev, struct device_attribute *attr,
2113                               char *buf)
2114 {
2115         struct tb_switch *sw = tb_to_switch(dev);
2116
2117         return sprintf(buf, "%pUb\n", sw->uuid);
2118 }
2119 static DEVICE_ATTR_RO(unique_id);
2120
2121 static struct attribute *switch_attrs[] = {
2122         &dev_attr_authorized.attr,
2123         &dev_attr_boot.attr,
2124         &dev_attr_device.attr,
2125         &dev_attr_device_name.attr,
2126         &dev_attr_generation.attr,
2127         &dev_attr_key.attr,
2128         &dev_attr_nvm_authenticate.attr,
2129         &dev_attr_nvm_authenticate_on_disconnect.attr,
2130         &dev_attr_nvm_version.attr,
2131         &dev_attr_rx_speed.attr,
2132         &dev_attr_rx_lanes.attr,
2133         &dev_attr_tx_speed.attr,
2134         &dev_attr_tx_lanes.attr,
2135         &dev_attr_vendor.attr,
2136         &dev_attr_vendor_name.attr,
2137         &dev_attr_unique_id.attr,
2138         NULL,
2139 };
2140
2141 static umode_t switch_attr_is_visible(struct kobject *kobj,
2142                                       struct attribute *attr, int n)
2143 {
2144         struct device *dev = kobj_to_dev(kobj);
2145         struct tb_switch *sw = tb_to_switch(dev);
2146
2147         if (attr == &dev_attr_authorized.attr) {
2148                 if (sw->tb->security_level == TB_SECURITY_NOPCIE ||
2149                     sw->tb->security_level == TB_SECURITY_DPONLY)
2150                         return 0;
2151         } else if (attr == &dev_attr_device.attr) {
2152                 if (!sw->device)
2153                         return 0;
2154         } else if (attr == &dev_attr_device_name.attr) {
2155                 if (!sw->device_name)
2156                         return 0;
2157         } else if (attr == &dev_attr_vendor.attr)  {
2158                 if (!sw->vendor)
2159                         return 0;
2160         } else if (attr == &dev_attr_vendor_name.attr)  {
2161                 if (!sw->vendor_name)
2162                         return 0;
2163         } else if (attr == &dev_attr_key.attr) {
2164                 if (tb_route(sw) &&
2165                     sw->tb->security_level == TB_SECURITY_SECURE &&
2166                     sw->security_level == TB_SECURITY_SECURE)
2167                         return attr->mode;
2168                 return 0;
2169         } else if (attr == &dev_attr_rx_speed.attr ||
2170                    attr == &dev_attr_rx_lanes.attr ||
2171                    attr == &dev_attr_tx_speed.attr ||
2172                    attr == &dev_attr_tx_lanes.attr) {
2173                 if (tb_route(sw))
2174                         return attr->mode;
2175                 return 0;
2176         } else if (attr == &dev_attr_nvm_authenticate.attr) {
2177                 if (nvm_upgradeable(sw))
2178                         return attr->mode;
2179                 return 0;
2180         } else if (attr == &dev_attr_nvm_version.attr) {
2181                 if (nvm_readable(sw))
2182                         return attr->mode;
2183                 return 0;
2184         } else if (attr == &dev_attr_boot.attr) {
2185                 if (tb_route(sw))
2186                         return attr->mode;
2187                 return 0;
2188         } else if (attr == &dev_attr_nvm_authenticate_on_disconnect.attr) {
2189                 if (sw->quirks & QUIRK_FORCE_POWER_LINK_CONTROLLER)
2190                         return attr->mode;
2191                 return 0;
2192         }
2193
2194         return sw->safe_mode ? 0 : attr->mode;
2195 }
2196
2197 static const struct attribute_group switch_group = {
2198         .is_visible = switch_attr_is_visible,
2199         .attrs = switch_attrs,
2200 };
2201
2202 static const struct attribute_group *switch_groups[] = {
2203         &switch_group,
2204         NULL,
2205 };
2206
2207 static void tb_switch_release(struct device *dev)
2208 {
2209         struct tb_switch *sw = tb_to_switch(dev);
2210         struct tb_port *port;
2211
2212         dma_port_free(sw->dma_port);
2213
2214         tb_switch_for_each_port(sw, port) {
2215                 ida_destroy(&port->in_hopids);
2216                 ida_destroy(&port->out_hopids);
2217         }
2218
2219         kfree(sw->uuid);
2220         kfree(sw->device_name);
2221         kfree(sw->vendor_name);
2222         kfree(sw->ports);
2223         kfree(sw->drom);
2224         kfree(sw->key);
2225         kfree(sw);
2226 }
2227
2228 static int tb_switch_uevent(struct device *dev, struct kobj_uevent_env *env)
2229 {
2230         struct tb_switch *sw = tb_to_switch(dev);
2231         const char *type;
2232
2233         if (sw->config.thunderbolt_version == USB4_VERSION_1_0) {
2234                 if (add_uevent_var(env, "USB4_VERSION=1.0"))
2235                         return -ENOMEM;
2236         }
2237
2238         if (!tb_route(sw)) {
2239                 type = "host";
2240         } else {
2241                 const struct tb_port *port;
2242                 bool hub = false;
2243
2244                 /* Device is hub if it has any downstream ports */
2245                 tb_switch_for_each_port(sw, port) {
2246                         if (!port->disabled && !tb_is_upstream_port(port) &&
2247                              tb_port_is_null(port)) {
2248                                 hub = true;
2249                                 break;
2250                         }
2251                 }
2252
2253                 type = hub ? "hub" : "device";
2254         }
2255
2256         if (add_uevent_var(env, "USB4_TYPE=%s", type))
2257                 return -ENOMEM;
2258         return 0;
2259 }
2260
2261 /*
2262  * Currently only need to provide the callbacks. Everything else is handled
2263  * in the connection manager.
2264  */
2265 static int __maybe_unused tb_switch_runtime_suspend(struct device *dev)
2266 {
2267         struct tb_switch *sw = tb_to_switch(dev);
2268         const struct tb_cm_ops *cm_ops = sw->tb->cm_ops;
2269
2270         if (cm_ops->runtime_suspend_switch)
2271                 return cm_ops->runtime_suspend_switch(sw);
2272
2273         return 0;
2274 }
2275
2276 static int __maybe_unused tb_switch_runtime_resume(struct device *dev)
2277 {
2278         struct tb_switch *sw = tb_to_switch(dev);
2279         const struct tb_cm_ops *cm_ops = sw->tb->cm_ops;
2280
2281         if (cm_ops->runtime_resume_switch)
2282                 return cm_ops->runtime_resume_switch(sw);
2283         return 0;
2284 }
2285
2286 static const struct dev_pm_ops tb_switch_pm_ops = {
2287         SET_RUNTIME_PM_OPS(tb_switch_runtime_suspend, tb_switch_runtime_resume,
2288                            NULL)
2289 };
2290
2291 struct device_type tb_switch_type = {
2292         .name = "thunderbolt_device",
2293         .release = tb_switch_release,
2294         .uevent = tb_switch_uevent,
2295         .pm = &tb_switch_pm_ops,
2296 };
2297
2298 static int tb_switch_get_generation(struct tb_switch *sw)
2299 {
2300         switch (sw->config.device_id) {
2301         case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
2302         case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
2303         case PCI_DEVICE_ID_INTEL_LIGHT_PEAK:
2304         case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_2C:
2305         case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C:
2306         case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
2307         case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_2C_BRIDGE:
2308         case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_4C_BRIDGE:
2309                 return 1;
2310
2311         case PCI_DEVICE_ID_INTEL_WIN_RIDGE_2C_BRIDGE:
2312         case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_BRIDGE:
2313         case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_BRIDGE:
2314                 return 2;
2315
2316         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_LP_BRIDGE:
2317         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_2C_BRIDGE:
2318         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_4C_BRIDGE:
2319         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_2C_BRIDGE:
2320         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_4C_BRIDGE:
2321         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_2C_BRIDGE:
2322         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_4C_BRIDGE:
2323         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_DD_BRIDGE:
2324         case PCI_DEVICE_ID_INTEL_ICL_NHI0:
2325         case PCI_DEVICE_ID_INTEL_ICL_NHI1:
2326                 return 3;
2327
2328         default:
2329                 if (tb_switch_is_usb4(sw))
2330                         return 4;
2331
2332                 /*
2333                  * For unknown switches assume generation to be 1 to be
2334                  * on the safe side.
2335                  */
2336                 tb_sw_warn(sw, "unsupported switch device id %#x\n",
2337                            sw->config.device_id);
2338                 return 1;
2339         }
2340 }
2341
2342 static bool tb_switch_exceeds_max_depth(const struct tb_switch *sw, int depth)
2343 {
2344         int max_depth;
2345
2346         if (tb_switch_is_usb4(sw) ||
2347             (sw->tb->root_switch && tb_switch_is_usb4(sw->tb->root_switch)))
2348                 max_depth = USB4_SWITCH_MAX_DEPTH;
2349         else
2350                 max_depth = TB_SWITCH_MAX_DEPTH;
2351
2352         return depth > max_depth;
2353 }
2354
2355 /**
2356  * tb_switch_alloc() - allocate a switch
2357  * @tb: Pointer to the owning domain
2358  * @parent: Parent device for this switch
2359  * @route: Route string for this switch
2360  *
2361  * Allocates and initializes a switch. Will not upload configuration to
2362  * the switch. For that you need to call tb_switch_configure()
2363  * separately. The returned switch should be released by calling
2364  * tb_switch_put().
2365  *
2366  * Return: Pointer to the allocated switch or ERR_PTR() in case of
2367  * failure.
2368  */
2369 struct tb_switch *tb_switch_alloc(struct tb *tb, struct device *parent,
2370                                   u64 route)
2371 {
2372         struct tb_switch *sw;
2373         int upstream_port;
2374         int i, ret, depth;
2375
2376         /* Unlock the downstream port so we can access the switch below */
2377         if (route) {
2378                 struct tb_switch *parent_sw = tb_to_switch(parent);
2379                 struct tb_port *down;
2380
2381                 down = tb_port_at(route, parent_sw);
2382                 tb_port_unlock(down);
2383         }
2384
2385         depth = tb_route_length(route);
2386
2387         upstream_port = tb_cfg_get_upstream_port(tb->ctl, route);
2388         if (upstream_port < 0)
2389                 return ERR_PTR(upstream_port);
2390
2391         sw = kzalloc(sizeof(*sw), GFP_KERNEL);
2392         if (!sw)
2393                 return ERR_PTR(-ENOMEM);
2394
2395         sw->tb = tb;
2396         ret = tb_cfg_read(tb->ctl, &sw->config, route, 0, TB_CFG_SWITCH, 0, 5);
2397         if (ret)
2398                 goto err_free_sw_ports;
2399
2400         sw->generation = tb_switch_get_generation(sw);
2401
2402         tb_dbg(tb, "current switch config:\n");
2403         tb_dump_switch(tb, sw);
2404
2405         /* configure switch */
2406         sw->config.upstream_port_number = upstream_port;
2407         sw->config.depth = depth;
2408         sw->config.route_hi = upper_32_bits(route);
2409         sw->config.route_lo = lower_32_bits(route);
2410         sw->config.enabled = 0;
2411
2412         /* Make sure we do not exceed maximum topology limit */
2413         if (tb_switch_exceeds_max_depth(sw, depth)) {
2414                 ret = -EADDRNOTAVAIL;
2415                 goto err_free_sw_ports;
2416         }
2417
2418         /* initialize ports */
2419         sw->ports = kcalloc(sw->config.max_port_number + 1, sizeof(*sw->ports),
2420                                 GFP_KERNEL);
2421         if (!sw->ports) {
2422                 ret = -ENOMEM;
2423                 goto err_free_sw_ports;
2424         }
2425
2426         for (i = 0; i <= sw->config.max_port_number; i++) {
2427                 /* minimum setup for tb_find_cap and tb_drom_read to work */
2428                 sw->ports[i].sw = sw;
2429                 sw->ports[i].port = i;
2430
2431                 /* Control port does not need HopID allocation */
2432                 if (i) {
2433                         ida_init(&sw->ports[i].in_hopids);
2434                         ida_init(&sw->ports[i].out_hopids);
2435                 }
2436         }
2437
2438         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_PLUG_EVENTS);
2439         if (ret > 0)
2440                 sw->cap_plug_events = ret;
2441
2442         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_TIME2);
2443         if (ret > 0)
2444                 sw->cap_vsec_tmu = ret;
2445
2446         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_LINK_CONTROLLER);
2447         if (ret > 0)
2448                 sw->cap_lc = ret;
2449
2450         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_CP_LP);
2451         if (ret > 0)
2452                 sw->cap_lp = ret;
2453
2454         /* Root switch is always authorized */
2455         if (!route)
2456                 sw->authorized = true;
2457
2458         device_initialize(&sw->dev);
2459         sw->dev.parent = parent;
2460         sw->dev.bus = &tb_bus_type;
2461         sw->dev.type = &tb_switch_type;
2462         sw->dev.groups = switch_groups;
2463         dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
2464
2465         return sw;
2466
2467 err_free_sw_ports:
2468         kfree(sw->ports);
2469         kfree(sw);
2470
2471         return ERR_PTR(ret);
2472 }
2473
2474 /**
2475  * tb_switch_alloc_safe_mode() - allocate a switch that is in safe mode
2476  * @tb: Pointer to the owning domain
2477  * @parent: Parent device for this switch
2478  * @route: Route string for this switch
2479  *
2480  * This creates a switch in safe mode. This means the switch pretty much
2481  * lacks all capabilities except DMA configuration port before it is
2482  * flashed with a valid NVM firmware.
2483  *
2484  * The returned switch must be released by calling tb_switch_put().
2485  *
2486  * Return: Pointer to the allocated switch or ERR_PTR() in case of failure
2487  */
2488 struct tb_switch *
2489 tb_switch_alloc_safe_mode(struct tb *tb, struct device *parent, u64 route)
2490 {
2491         struct tb_switch *sw;
2492
2493         sw = kzalloc(sizeof(*sw), GFP_KERNEL);
2494         if (!sw)
2495                 return ERR_PTR(-ENOMEM);
2496
2497         sw->tb = tb;
2498         sw->config.depth = tb_route_length(route);
2499         sw->config.route_hi = upper_32_bits(route);
2500         sw->config.route_lo = lower_32_bits(route);
2501         sw->safe_mode = true;
2502
2503         device_initialize(&sw->dev);
2504         sw->dev.parent = parent;
2505         sw->dev.bus = &tb_bus_type;
2506         sw->dev.type = &tb_switch_type;
2507         sw->dev.groups = switch_groups;
2508         dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
2509
2510         return sw;
2511 }
2512
2513 /**
2514  * tb_switch_configure() - Uploads configuration to the switch
2515  * @sw: Switch to configure
2516  *
2517  * Call this function before the switch is added to the system. It will
2518  * upload configuration to the switch and makes it available for the
2519  * connection manager to use. Can be called to the switch again after
2520  * resume from low power states to re-initialize it.
2521  *
2522  * Return: %0 in case of success and negative errno in case of failure
2523  */
2524 int tb_switch_configure(struct tb_switch *sw)
2525 {
2526         struct tb *tb = sw->tb;
2527         u64 route;
2528         int ret;
2529
2530         route = tb_route(sw);
2531
2532         tb_dbg(tb, "%s Switch at %#llx (depth: %d, up port: %d)\n",
2533                sw->config.enabled ? "restoring" : "initializing", route,
2534                tb_route_length(route), sw->config.upstream_port_number);
2535
2536         sw->config.enabled = 1;
2537
2538         if (tb_switch_is_usb4(sw)) {
2539                 /*
2540                  * For USB4 devices, we need to program the CM version
2541                  * accordingly so that it knows to expose all the
2542                  * additional capabilities.
2543                  */
2544                 sw->config.cmuv = USB4_VERSION_1_0;
2545
2546                 /* Enumerate the switch */
2547                 ret = tb_sw_write(sw, (u32 *)&sw->config + 1, TB_CFG_SWITCH,
2548                                   ROUTER_CS_1, 4);
2549                 if (ret)
2550                         return ret;
2551
2552                 ret = usb4_switch_setup(sw);
2553         } else {
2554                 if (sw->config.vendor_id != PCI_VENDOR_ID_INTEL)
2555                         tb_sw_warn(sw, "unknown switch vendor id %#x\n",
2556                                    sw->config.vendor_id);
2557
2558                 if (!sw->cap_plug_events) {
2559                         tb_sw_warn(sw, "cannot find TB_VSE_CAP_PLUG_EVENTS aborting\n");
2560                         return -ENODEV;
2561                 }
2562
2563                 /* Enumerate the switch */
2564                 ret = tb_sw_write(sw, (u32 *)&sw->config + 1, TB_CFG_SWITCH,
2565                                   ROUTER_CS_1, 3);
2566         }
2567         if (ret)
2568                 return ret;
2569
2570         return tb_plug_events_active(sw, true);
2571 }
2572
2573 static int tb_switch_set_uuid(struct tb_switch *sw)
2574 {
2575         bool uid = false;
2576         u32 uuid[4];
2577         int ret;
2578
2579         if (sw->uuid)
2580                 return 0;
2581
2582         if (tb_switch_is_usb4(sw)) {
2583                 ret = usb4_switch_read_uid(sw, &sw->uid);
2584                 if (ret)
2585                         return ret;
2586                 uid = true;
2587         } else {
2588                 /*
2589                  * The newer controllers include fused UUID as part of
2590                  * link controller specific registers
2591                  */
2592                 ret = tb_lc_read_uuid(sw, uuid);
2593                 if (ret) {
2594                         if (ret != -EINVAL)
2595                                 return ret;
2596                         uid = true;
2597                 }
2598         }
2599
2600         if (uid) {
2601                 /*
2602                  * ICM generates UUID based on UID and fills the upper
2603                  * two words with ones. This is not strictly following
2604                  * UUID format but we want to be compatible with it so
2605                  * we do the same here.
2606                  */
2607                 uuid[0] = sw->uid & 0xffffffff;
2608                 uuid[1] = (sw->uid >> 32) & 0xffffffff;
2609                 uuid[2] = 0xffffffff;
2610                 uuid[3] = 0xffffffff;
2611         }
2612
2613         sw->uuid = kmemdup(uuid, sizeof(uuid), GFP_KERNEL);
2614         if (!sw->uuid)
2615                 return -ENOMEM;
2616         return 0;
2617 }
2618
2619 static int tb_switch_add_dma_port(struct tb_switch *sw)
2620 {
2621         u32 status;
2622         int ret;
2623
2624         switch (sw->generation) {
2625         case 2:
2626                 /* Only root switch can be upgraded */
2627                 if (tb_route(sw))
2628                         return 0;
2629
2630                 fallthrough;
2631         case 3:
2632         case 4:
2633                 ret = tb_switch_set_uuid(sw);
2634                 if (ret)
2635                         return ret;
2636                 break;
2637
2638         default:
2639                 /*
2640                  * DMA port is the only thing available when the switch
2641                  * is in safe mode.
2642                  */
2643                 if (!sw->safe_mode)
2644                         return 0;
2645                 break;
2646         }
2647
2648         if (sw->no_nvm_upgrade)
2649                 return 0;
2650
2651         if (tb_switch_is_usb4(sw)) {
2652                 ret = usb4_switch_nvm_authenticate_status(sw, &status);
2653                 if (ret)
2654                         return ret;
2655
2656                 if (status) {
2657                         tb_sw_info(sw, "switch flash authentication failed\n");
2658                         nvm_set_auth_status(sw, status);
2659                 }
2660
2661                 return 0;
2662         }
2663
2664         /* Root switch DMA port requires running firmware */
2665         if (!tb_route(sw) && !tb_switch_is_icm(sw))
2666                 return 0;
2667
2668         sw->dma_port = dma_port_alloc(sw);
2669         if (!sw->dma_port)
2670                 return 0;
2671
2672         /*
2673          * If there is status already set then authentication failed
2674          * when the dma_port_flash_update_auth() returned. Power cycling
2675          * is not needed (it was done already) so only thing we do here
2676          * is to unblock runtime PM of the root port.
2677          */
2678         nvm_get_auth_status(sw, &status);
2679         if (status) {
2680                 if (!tb_route(sw))
2681                         nvm_authenticate_complete_dma_port(sw);
2682                 return 0;
2683         }
2684
2685         /*
2686          * Check status of the previous flash authentication. If there
2687          * is one we need to power cycle the switch in any case to make
2688          * it functional again.
2689          */
2690         ret = dma_port_flash_update_auth_status(sw->dma_port, &status);
2691         if (ret <= 0)
2692                 return ret;
2693
2694         /* Now we can allow root port to suspend again */
2695         if (!tb_route(sw))
2696                 nvm_authenticate_complete_dma_port(sw);
2697
2698         if (status) {
2699                 tb_sw_info(sw, "switch flash authentication failed\n");
2700                 nvm_set_auth_status(sw, status);
2701         }
2702
2703         tb_sw_info(sw, "power cycling the switch now\n");
2704         dma_port_power_cycle(sw->dma_port);
2705
2706         /*
2707          * We return error here which causes the switch adding failure.
2708          * It should appear back after power cycle is complete.
2709          */
2710         return -ESHUTDOWN;
2711 }
2712
2713 static void tb_switch_default_link_ports(struct tb_switch *sw)
2714 {
2715         int i;
2716
2717         for (i = 1; i <= sw->config.max_port_number; i++) {
2718                 struct tb_port *port = &sw->ports[i];
2719                 struct tb_port *subordinate;
2720
2721                 if (!tb_port_is_null(port))
2722                         continue;
2723
2724                 /* Check for the subordinate port */
2725                 if (i == sw->config.max_port_number ||
2726                     !tb_port_is_null(&sw->ports[i + 1]))
2727                         continue;
2728
2729                 /* Link them if not already done so (by DROM) */
2730                 subordinate = &sw->ports[i + 1];
2731                 if (!port->dual_link_port && !subordinate->dual_link_port) {
2732                         port->link_nr = 0;
2733                         port->dual_link_port = subordinate;
2734                         subordinate->link_nr = 1;
2735                         subordinate->dual_link_port = port;
2736
2737                         tb_sw_dbg(sw, "linked ports %d <-> %d\n",
2738                                   port->port, subordinate->port);
2739                 }
2740         }
2741 }
2742
2743 static bool tb_switch_lane_bonding_possible(struct tb_switch *sw)
2744 {
2745         const struct tb_port *up = tb_upstream_port(sw);
2746
2747         if (!up->dual_link_port || !up->dual_link_port->remote)
2748                 return false;
2749
2750         if (tb_switch_is_usb4(sw))
2751                 return usb4_switch_lane_bonding_possible(sw);
2752         return tb_lc_lane_bonding_possible(sw);
2753 }
2754
2755 static int tb_switch_update_link_attributes(struct tb_switch *sw)
2756 {
2757         struct tb_port *up;
2758         bool change = false;
2759         int ret;
2760
2761         if (!tb_route(sw) || tb_switch_is_icm(sw))
2762                 return 0;
2763
2764         up = tb_upstream_port(sw);
2765
2766         ret = tb_port_get_link_speed(up);
2767         if (ret < 0)
2768                 return ret;
2769         if (sw->link_speed != ret)
2770                 change = true;
2771         sw->link_speed = ret;
2772
2773         ret = tb_port_get_link_width(up);
2774         if (ret < 0)
2775                 return ret;
2776         if (sw->link_width != ret)
2777                 change = true;
2778         sw->link_width = ret;
2779
2780         /* Notify userspace that there is possible link attribute change */
2781         if (device_is_registered(&sw->dev) && change)
2782                 kobject_uevent(&sw->dev.kobj, KOBJ_CHANGE);
2783
2784         return 0;
2785 }
2786
2787 /**
2788  * tb_switch_lane_bonding_enable() - Enable lane bonding
2789  * @sw: Switch to enable lane bonding
2790  *
2791  * Connection manager can call this function to enable lane bonding of a
2792  * switch. If conditions are correct and both switches support the feature,
2793  * lanes are bonded. It is safe to call this to any switch.
2794  */
2795 int tb_switch_lane_bonding_enable(struct tb_switch *sw)
2796 {
2797         struct tb_switch *parent = tb_to_switch(sw->dev.parent);
2798         struct tb_port *up, *down;
2799         u64 route = tb_route(sw);
2800         int ret;
2801
2802         if (!route)
2803                 return 0;
2804
2805         if (!tb_switch_lane_bonding_possible(sw))
2806                 return 0;
2807
2808         up = tb_upstream_port(sw);
2809         down = tb_port_at(route, parent);
2810
2811         if (!tb_port_is_width_supported(up, 2) ||
2812             !tb_port_is_width_supported(down, 2))
2813                 return 0;
2814
2815         ret = tb_port_lane_bonding_enable(up);
2816         if (ret) {
2817                 tb_port_warn(up, "failed to enable lane bonding\n");
2818                 return ret;
2819         }
2820
2821         ret = tb_port_lane_bonding_enable(down);
2822         if (ret) {
2823                 tb_port_warn(down, "failed to enable lane bonding\n");
2824                 tb_port_lane_bonding_disable(up);
2825                 return ret;
2826         }
2827
2828         ret = tb_port_wait_for_link_width(down, 2, 100);
2829         if (ret) {
2830                 tb_port_warn(down, "timeout enabling lane bonding\n");
2831                 return ret;
2832         }
2833
2834         tb_port_update_credits(down);
2835         tb_port_update_credits(up);
2836         tb_switch_update_link_attributes(sw);
2837
2838         tb_sw_dbg(sw, "lane bonding enabled\n");
2839         return ret;
2840 }
2841
2842 /**
2843  * tb_switch_lane_bonding_disable() - Disable lane bonding
2844  * @sw: Switch whose lane bonding to disable
2845  *
2846  * Disables lane bonding between @sw and parent. This can be called even
2847  * if lanes were not bonded originally.
2848  */
2849 void tb_switch_lane_bonding_disable(struct tb_switch *sw)
2850 {
2851         struct tb_switch *parent = tb_to_switch(sw->dev.parent);
2852         struct tb_port *up, *down;
2853
2854         if (!tb_route(sw))
2855                 return;
2856
2857         up = tb_upstream_port(sw);
2858         if (!up->bonded)
2859                 return;
2860
2861         down = tb_port_at(tb_route(sw), parent);
2862
2863         tb_port_lane_bonding_disable(up);
2864         tb_port_lane_bonding_disable(down);
2865
2866         /*
2867          * It is fine if we get other errors as the router might have
2868          * been unplugged.
2869          */
2870         if (tb_port_wait_for_link_width(down, 1, 100) == -ETIMEDOUT)
2871                 tb_sw_warn(sw, "timeout disabling lane bonding\n");
2872
2873         tb_port_update_credits(down);
2874         tb_port_update_credits(up);
2875         tb_switch_update_link_attributes(sw);
2876
2877         tb_sw_dbg(sw, "lane bonding disabled\n");
2878 }
2879
2880 /**
2881  * tb_switch_configure_link() - Set link configured
2882  * @sw: Switch whose link is configured
2883  *
2884  * Sets the link upstream from @sw configured (from both ends) so that
2885  * it will not be disconnected when the domain exits sleep. Can be
2886  * called for any switch.
2887  *
2888  * It is recommended that this is called after lane bonding is enabled.
2889  *
2890  * Returns %0 on success and negative errno in case of error.
2891  */
2892 int tb_switch_configure_link(struct tb_switch *sw)
2893 {
2894         struct tb_port *up, *down;
2895         int ret;
2896
2897         if (!tb_route(sw) || tb_switch_is_icm(sw))
2898                 return 0;
2899
2900         up = tb_upstream_port(sw);
2901         if (tb_switch_is_usb4(up->sw))
2902                 ret = usb4_port_configure(up);
2903         else
2904                 ret = tb_lc_configure_port(up);
2905         if (ret)
2906                 return ret;
2907
2908         down = up->remote;
2909         if (tb_switch_is_usb4(down->sw))
2910                 return usb4_port_configure(down);
2911         return tb_lc_configure_port(down);
2912 }
2913
2914 /**
2915  * tb_switch_unconfigure_link() - Unconfigure link
2916  * @sw: Switch whose link is unconfigured
2917  *
2918  * Sets the link unconfigured so the @sw will be disconnected if the
2919  * domain exists sleep.
2920  */
2921 void tb_switch_unconfigure_link(struct tb_switch *sw)
2922 {
2923         struct tb_port *up, *down;
2924
2925         if (sw->is_unplugged)
2926                 return;
2927         if (!tb_route(sw) || tb_switch_is_icm(sw))
2928                 return;
2929
2930         up = tb_upstream_port(sw);
2931         if (tb_switch_is_usb4(up->sw))
2932                 usb4_port_unconfigure(up);
2933         else
2934                 tb_lc_unconfigure_port(up);
2935
2936         down = up->remote;
2937         if (tb_switch_is_usb4(down->sw))
2938                 usb4_port_unconfigure(down);
2939         else
2940                 tb_lc_unconfigure_port(down);
2941 }
2942
2943 static void tb_switch_credits_init(struct tb_switch *sw)
2944 {
2945         if (tb_switch_is_icm(sw))
2946                 return;
2947         if (!tb_switch_is_usb4(sw))
2948                 return;
2949         if (usb4_switch_credits_init(sw))
2950                 tb_sw_info(sw, "failed to determine preferred buffer allocation, using defaults\n");
2951 }
2952
2953 /**
2954  * tb_switch_add() - Add a switch to the domain
2955  * @sw: Switch to add
2956  *
2957  * This is the last step in adding switch to the domain. It will read
2958  * identification information from DROM and initializes ports so that
2959  * they can be used to connect other switches. The switch will be
2960  * exposed to the userspace when this function successfully returns. To
2961  * remove and release the switch, call tb_switch_remove().
2962  *
2963  * Return: %0 in case of success and negative errno in case of failure
2964  */
2965 int tb_switch_add(struct tb_switch *sw)
2966 {
2967         int i, ret;
2968
2969         /*
2970          * Initialize DMA control port now before we read DROM. Recent
2971          * host controllers have more complete DROM on NVM that includes
2972          * vendor and model identification strings which we then expose
2973          * to the userspace. NVM can be accessed through DMA
2974          * configuration based mailbox.
2975          */
2976         ret = tb_switch_add_dma_port(sw);
2977         if (ret) {
2978                 dev_err(&sw->dev, "failed to add DMA port\n");
2979                 return ret;
2980         }
2981
2982         if (!sw->safe_mode) {
2983                 tb_switch_credits_init(sw);
2984
2985                 /* read drom */
2986                 ret = tb_drom_read(sw);
2987                 if (ret)
2988                         dev_warn(&sw->dev, "reading DROM failed: %d\n", ret);
2989                 tb_sw_dbg(sw, "uid: %#llx\n", sw->uid);
2990
2991                 tb_check_quirks(sw);
2992
2993                 ret = tb_switch_set_uuid(sw);
2994                 if (ret) {
2995                         dev_err(&sw->dev, "failed to set UUID\n");
2996                         return ret;
2997                 }
2998
2999                 for (i = 0; i <= sw->config.max_port_number; i++) {
3000                         if (sw->ports[i].disabled) {
3001                                 tb_port_dbg(&sw->ports[i], "disabled by eeprom\n");
3002                                 continue;
3003                         }
3004                         ret = tb_init_port(&sw->ports[i]);
3005                         if (ret) {
3006                                 dev_err(&sw->dev, "failed to initialize port %d\n", i);
3007                                 return ret;
3008                         }
3009                 }
3010
3011                 tb_switch_default_link_ports(sw);
3012
3013                 ret = tb_switch_update_link_attributes(sw);
3014                 if (ret)
3015                         return ret;
3016
3017                 ret = tb_switch_tmu_init(sw);
3018                 if (ret)
3019                         return ret;
3020         }
3021
3022         ret = device_add(&sw->dev);
3023         if (ret) {
3024                 dev_err(&sw->dev, "failed to add device: %d\n", ret);
3025                 return ret;
3026         }
3027
3028         if (tb_route(sw)) {
3029                 dev_info(&sw->dev, "new device found, vendor=%#x device=%#x\n",
3030                          sw->vendor, sw->device);
3031                 if (sw->vendor_name && sw->device_name)
3032                         dev_info(&sw->dev, "%s %s\n", sw->vendor_name,
3033                                  sw->device_name);
3034         }
3035
3036         ret = usb4_switch_add_ports(sw);
3037         if (ret) {
3038                 dev_err(&sw->dev, "failed to add USB4 ports\n");
3039                 goto err_del;
3040         }
3041
3042         ret = tb_switch_nvm_add(sw);
3043         if (ret) {
3044                 dev_err(&sw->dev, "failed to add NVM devices\n");
3045                 goto err_ports;
3046         }
3047
3048         /*
3049          * Thunderbolt routers do not generate wakeups themselves but
3050          * they forward wakeups from tunneled protocols, so enable it
3051          * here.
3052          */
3053         device_init_wakeup(&sw->dev, true);
3054
3055         pm_runtime_set_active(&sw->dev);
3056         if (sw->rpm) {
3057                 pm_runtime_set_autosuspend_delay(&sw->dev, TB_AUTOSUSPEND_DELAY);
3058                 pm_runtime_use_autosuspend(&sw->dev);
3059                 pm_runtime_mark_last_busy(&sw->dev);
3060                 pm_runtime_enable(&sw->dev);
3061                 pm_request_autosuspend(&sw->dev);
3062         }
3063
3064         tb_switch_debugfs_init(sw);
3065         return 0;
3066
3067 err_ports:
3068         usb4_switch_remove_ports(sw);
3069 err_del:
3070         device_del(&sw->dev);
3071
3072         return ret;
3073 }
3074
3075 /**
3076  * tb_switch_remove() - Remove and release a switch
3077  * @sw: Switch to remove
3078  *
3079  * This will remove the switch from the domain and release it after last
3080  * reference count drops to zero. If there are switches connected below
3081  * this switch, they will be removed as well.
3082  */
3083 void tb_switch_remove(struct tb_switch *sw)
3084 {
3085         struct tb_port *port;
3086
3087         tb_switch_debugfs_remove(sw);
3088
3089         if (sw->rpm) {
3090                 pm_runtime_get_sync(&sw->dev);
3091                 pm_runtime_disable(&sw->dev);
3092         }
3093
3094         /* port 0 is the switch itself and never has a remote */
3095         tb_switch_for_each_port(sw, port) {
3096                 if (tb_port_has_remote(port)) {
3097                         tb_switch_remove(port->remote->sw);
3098                         port->remote = NULL;
3099                 } else if (port->xdomain) {
3100                         tb_xdomain_remove(port->xdomain);
3101                         port->xdomain = NULL;
3102                 }
3103
3104                 /* Remove any downstream retimers */
3105                 tb_retimer_remove_all(port);
3106         }
3107
3108         if (!sw->is_unplugged)
3109                 tb_plug_events_active(sw, false);
3110
3111         tb_switch_nvm_remove(sw);
3112         usb4_switch_remove_ports(sw);
3113
3114         if (tb_route(sw))
3115                 dev_info(&sw->dev, "device disconnected\n");
3116         device_unregister(&sw->dev);
3117 }
3118
3119 /**
3120  * tb_sw_set_unplugged() - set is_unplugged on switch and downstream switches
3121  * @sw: Router to mark unplugged
3122  */
3123 void tb_sw_set_unplugged(struct tb_switch *sw)
3124 {
3125         struct tb_port *port;
3126
3127         if (sw == sw->tb->root_switch) {
3128                 tb_sw_WARN(sw, "cannot unplug root switch\n");
3129                 return;
3130         }
3131         if (sw->is_unplugged) {
3132                 tb_sw_WARN(sw, "is_unplugged already set\n");
3133                 return;
3134         }
3135         sw->is_unplugged = true;
3136         tb_switch_for_each_port(sw, port) {
3137                 if (tb_port_has_remote(port))
3138                         tb_sw_set_unplugged(port->remote->sw);
3139                 else if (port->xdomain)
3140                         port->xdomain->is_unplugged = true;
3141         }
3142 }
3143
3144 static int tb_switch_set_wake(struct tb_switch *sw, unsigned int flags)
3145 {
3146         if (flags)
3147                 tb_sw_dbg(sw, "enabling wakeup: %#x\n", flags);
3148         else
3149                 tb_sw_dbg(sw, "disabling wakeup\n");
3150
3151         if (tb_switch_is_usb4(sw))
3152                 return usb4_switch_set_wake(sw, flags);
3153         return tb_lc_set_wake(sw, flags);
3154 }
3155
3156 int tb_switch_resume(struct tb_switch *sw)
3157 {
3158         struct tb_port *port;
3159         int err;
3160
3161         tb_sw_dbg(sw, "resuming switch\n");
3162
3163         /*
3164          * Check for UID of the connected switches except for root
3165          * switch which we assume cannot be removed.
3166          */
3167         if (tb_route(sw)) {
3168                 u64 uid;
3169
3170                 /*
3171                  * Check first that we can still read the switch config
3172                  * space. It may be that there is now another domain
3173                  * connected.
3174                  */
3175                 err = tb_cfg_get_upstream_port(sw->tb->ctl, tb_route(sw));
3176                 if (err < 0) {
3177                         tb_sw_info(sw, "switch not present anymore\n");
3178                         return err;
3179                 }
3180
3181                 /* We don't have any way to confirm this was the same device */
3182                 if (!sw->uid)
3183                         return -ENODEV;
3184
3185                 if (tb_switch_is_usb4(sw))
3186                         err = usb4_switch_read_uid(sw, &uid);
3187                 else
3188                         err = tb_drom_read_uid_only(sw, &uid);
3189                 if (err) {
3190                         tb_sw_warn(sw, "uid read failed\n");
3191                         return err;
3192                 }
3193                 if (sw->uid != uid) {
3194                         tb_sw_info(sw,
3195                                 "changed while suspended (uid %#llx -> %#llx)\n",
3196                                 sw->uid, uid);
3197                         return -ENODEV;
3198                 }
3199         }
3200
3201         err = tb_switch_configure(sw);
3202         if (err)
3203                 return err;
3204
3205         /* Disable wakes */
3206         tb_switch_set_wake(sw, 0);
3207
3208         err = tb_switch_tmu_init(sw);
3209         if (err)
3210                 return err;
3211
3212         /* check for surviving downstream switches */
3213         tb_switch_for_each_port(sw, port) {
3214                 if (!tb_port_is_null(port))
3215                         continue;
3216
3217                 if (!tb_port_resume(port))
3218                         continue;
3219
3220                 if (tb_wait_for_port(port, true) <= 0) {
3221                         tb_port_warn(port,
3222                                      "lost during suspend, disconnecting\n");
3223                         if (tb_port_has_remote(port))
3224                                 tb_sw_set_unplugged(port->remote->sw);
3225                         else if (port->xdomain)
3226                                 port->xdomain->is_unplugged = true;
3227                 } else {
3228                         /*
3229                          * Always unlock the port so the downstream
3230                          * switch/domain is accessible.
3231                          */
3232                         if (tb_port_unlock(port))
3233                                 tb_port_warn(port, "failed to unlock port\n");
3234                         if (port->remote && tb_switch_resume(port->remote->sw)) {
3235                                 tb_port_warn(port,
3236                                              "lost during suspend, disconnecting\n");
3237                                 tb_sw_set_unplugged(port->remote->sw);
3238                         }
3239                 }
3240         }
3241         return 0;
3242 }
3243
3244 /**
3245  * tb_switch_suspend() - Put a switch to sleep
3246  * @sw: Switch to suspend
3247  * @runtime: Is this runtime suspend or system sleep
3248  *
3249  * Suspends router and all its children. Enables wakes according to
3250  * value of @runtime and then sets sleep bit for the router. If @sw is
3251  * host router the domain is ready to go to sleep once this function
3252  * returns.
3253  */
3254 void tb_switch_suspend(struct tb_switch *sw, bool runtime)
3255 {
3256         unsigned int flags = 0;
3257         struct tb_port *port;
3258         int err;
3259
3260         tb_sw_dbg(sw, "suspending switch\n");
3261
3262         /*
3263          * Actually only needed for Titan Ridge but for simplicity can be
3264          * done for USB4 device too as CLx is re-enabled at resume.
3265          * CL0s and CL1 are enabled and supported together.
3266          */
3267         if (tb_switch_is_clx_enabled(sw, TB_CL1)) {
3268                 if (tb_switch_disable_clx(sw, TB_CL1))
3269                         tb_sw_warn(sw, "failed to disable %s on upstream port\n",
3270                                    tb_switch_clx_name(TB_CL1));
3271         }
3272
3273         err = tb_plug_events_active(sw, false);
3274         if (err)
3275                 return;
3276
3277         tb_switch_for_each_port(sw, port) {
3278                 if (tb_port_has_remote(port))
3279                         tb_switch_suspend(port->remote->sw, runtime);
3280         }
3281
3282         if (runtime) {
3283                 /* Trigger wake when something is plugged in/out */
3284                 flags |= TB_WAKE_ON_CONNECT | TB_WAKE_ON_DISCONNECT;
3285                 flags |= TB_WAKE_ON_USB4;
3286                 flags |= TB_WAKE_ON_USB3 | TB_WAKE_ON_PCIE | TB_WAKE_ON_DP;
3287         } else if (device_may_wakeup(&sw->dev)) {
3288                 flags |= TB_WAKE_ON_USB4 | TB_WAKE_ON_USB3 | TB_WAKE_ON_PCIE;
3289         }
3290
3291         tb_switch_set_wake(sw, flags);
3292
3293         if (tb_switch_is_usb4(sw))
3294                 usb4_switch_set_sleep(sw);
3295         else
3296                 tb_lc_set_sleep(sw);
3297 }
3298
3299 /**
3300  * tb_switch_query_dp_resource() - Query availability of DP resource
3301  * @sw: Switch whose DP resource is queried
3302  * @in: DP IN port
3303  *
3304  * Queries availability of DP resource for DP tunneling using switch
3305  * specific means. Returns %true if resource is available.
3306  */
3307 bool tb_switch_query_dp_resource(struct tb_switch *sw, struct tb_port *in)
3308 {
3309         if (tb_switch_is_usb4(sw))
3310                 return usb4_switch_query_dp_resource(sw, in);
3311         return tb_lc_dp_sink_query(sw, in);
3312 }
3313
3314 /**
3315  * tb_switch_alloc_dp_resource() - Allocate available DP resource
3316  * @sw: Switch whose DP resource is allocated
3317  * @in: DP IN port
3318  *
3319  * Allocates DP resource for DP tunneling. The resource must be
3320  * available for this to succeed (see tb_switch_query_dp_resource()).
3321  * Returns %0 in success and negative errno otherwise.
3322  */
3323 int tb_switch_alloc_dp_resource(struct tb_switch *sw, struct tb_port *in)
3324 {
3325         int ret;
3326
3327         if (tb_switch_is_usb4(sw))
3328                 ret = usb4_switch_alloc_dp_resource(sw, in);
3329         else
3330                 ret = tb_lc_dp_sink_alloc(sw, in);
3331
3332         if (ret)
3333                 tb_sw_warn(sw, "failed to allocate DP resource for port %d\n",
3334                            in->port);
3335         else
3336                 tb_sw_dbg(sw, "allocated DP resource for port %d\n", in->port);
3337
3338         return ret;
3339 }
3340
3341 /**
3342  * tb_switch_dealloc_dp_resource() - De-allocate DP resource
3343  * @sw: Switch whose DP resource is de-allocated
3344  * @in: DP IN port
3345  *
3346  * De-allocates DP resource that was previously allocated for DP
3347  * tunneling.
3348  */
3349 void tb_switch_dealloc_dp_resource(struct tb_switch *sw, struct tb_port *in)
3350 {
3351         int ret;
3352
3353         if (tb_switch_is_usb4(sw))
3354                 ret = usb4_switch_dealloc_dp_resource(sw, in);
3355         else
3356                 ret = tb_lc_dp_sink_dealloc(sw, in);
3357
3358         if (ret)
3359                 tb_sw_warn(sw, "failed to de-allocate DP resource for port %d\n",
3360                            in->port);
3361         else
3362                 tb_sw_dbg(sw, "released DP resource for port %d\n", in->port);
3363 }
3364
3365 struct tb_sw_lookup {
3366         struct tb *tb;
3367         u8 link;
3368         u8 depth;
3369         const uuid_t *uuid;
3370         u64 route;
3371 };
3372
3373 static int tb_switch_match(struct device *dev, const void *data)
3374 {
3375         struct tb_switch *sw = tb_to_switch(dev);
3376         const struct tb_sw_lookup *lookup = data;
3377
3378         if (!sw)
3379                 return 0;
3380         if (sw->tb != lookup->tb)
3381                 return 0;
3382
3383         if (lookup->uuid)
3384                 return !memcmp(sw->uuid, lookup->uuid, sizeof(*lookup->uuid));
3385
3386         if (lookup->route) {
3387                 return sw->config.route_lo == lower_32_bits(lookup->route) &&
3388                        sw->config.route_hi == upper_32_bits(lookup->route);
3389         }
3390
3391         /* Root switch is matched only by depth */
3392         if (!lookup->depth)
3393                 return !sw->depth;
3394
3395         return sw->link == lookup->link && sw->depth == lookup->depth;
3396 }
3397
3398 /**
3399  * tb_switch_find_by_link_depth() - Find switch by link and depth
3400  * @tb: Domain the switch belongs
3401  * @link: Link number the switch is connected
3402  * @depth: Depth of the switch in link
3403  *
3404  * Returned switch has reference count increased so the caller needs to
3405  * call tb_switch_put() when done with the switch.
3406  */
3407 struct tb_switch *tb_switch_find_by_link_depth(struct tb *tb, u8 link, u8 depth)
3408 {
3409         struct tb_sw_lookup lookup;
3410         struct device *dev;
3411
3412         memset(&lookup, 0, sizeof(lookup));
3413         lookup.tb = tb;
3414         lookup.link = link;
3415         lookup.depth = depth;
3416
3417         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
3418         if (dev)
3419                 return tb_to_switch(dev);
3420
3421         return NULL;
3422 }
3423
3424 /**
3425  * tb_switch_find_by_uuid() - Find switch by UUID
3426  * @tb: Domain the switch belongs
3427  * @uuid: UUID to look for
3428  *
3429  * Returned switch has reference count increased so the caller needs to
3430  * call tb_switch_put() when done with the switch.
3431  */
3432 struct tb_switch *tb_switch_find_by_uuid(struct tb *tb, const uuid_t *uuid)
3433 {
3434         struct tb_sw_lookup lookup;
3435         struct device *dev;
3436
3437         memset(&lookup, 0, sizeof(lookup));
3438         lookup.tb = tb;
3439         lookup.uuid = uuid;
3440
3441         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
3442         if (dev)
3443                 return tb_to_switch(dev);
3444
3445         return NULL;
3446 }
3447
3448 /**
3449  * tb_switch_find_by_route() - Find switch by route string
3450  * @tb: Domain the switch belongs
3451  * @route: Route string to look for
3452  *
3453  * Returned switch has reference count increased so the caller needs to
3454  * call tb_switch_put() when done with the switch.
3455  */
3456 struct tb_switch *tb_switch_find_by_route(struct tb *tb, u64 route)
3457 {
3458         struct tb_sw_lookup lookup;
3459         struct device *dev;
3460
3461         if (!route)
3462                 return tb_switch_get(tb->root_switch);
3463
3464         memset(&lookup, 0, sizeof(lookup));
3465         lookup.tb = tb;
3466         lookup.route = route;
3467
3468         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
3469         if (dev)
3470                 return tb_to_switch(dev);
3471
3472         return NULL;
3473 }
3474
3475 /**
3476  * tb_switch_find_port() - return the first port of @type on @sw or NULL
3477  * @sw: Switch to find the port from
3478  * @type: Port type to look for
3479  */
3480 struct tb_port *tb_switch_find_port(struct tb_switch *sw,
3481                                     enum tb_port_type type)
3482 {
3483         struct tb_port *port;
3484
3485         tb_switch_for_each_port(sw, port) {
3486                 if (port->config.type == type)
3487                         return port;
3488         }
3489
3490         return NULL;
3491 }
3492
3493 static int tb_switch_pm_secondary_resolve(struct tb_switch *sw)
3494 {
3495         struct tb_switch *parent = tb_switch_parent(sw);
3496         struct tb_port *up, *down;
3497         int ret;
3498
3499         if (!tb_route(sw))
3500                 return 0;
3501
3502         up = tb_upstream_port(sw);
3503         down = tb_port_at(tb_route(sw), parent);
3504         ret = tb_port_pm_secondary_enable(up);
3505         if (ret)
3506                 return ret;
3507
3508         return tb_port_pm_secondary_disable(down);
3509 }
3510
3511 static int __tb_switch_enable_clx(struct tb_switch *sw, enum tb_clx clx)
3512 {
3513         struct tb_switch *parent = tb_switch_parent(sw);
3514         bool up_clx_support, down_clx_support;
3515         struct tb_port *up, *down;
3516         int ret;
3517
3518         if (!tb_switch_is_clx_supported(sw))
3519                 return 0;
3520
3521         /*
3522          * Enable CLx for host router's downstream port as part of the
3523          * downstream router enabling procedure.
3524          */
3525         if (!tb_route(sw))
3526                 return 0;
3527
3528         /* Enable CLx only for first hop router (depth = 1) */
3529         if (tb_route(parent))
3530                 return 0;
3531
3532         ret = tb_switch_pm_secondary_resolve(sw);
3533         if (ret)
3534                 return ret;
3535
3536         up = tb_upstream_port(sw);
3537         down = tb_port_at(tb_route(sw), parent);
3538
3539         up_clx_support = tb_port_clx_supported(up, clx);
3540         down_clx_support = tb_port_clx_supported(down, clx);
3541
3542         tb_port_dbg(up, "%s %ssupported\n", tb_switch_clx_name(clx),
3543                     up_clx_support ? "" : "not ");
3544         tb_port_dbg(down, "%s %ssupported\n", tb_switch_clx_name(clx),
3545                     down_clx_support ? "" : "not ");
3546
3547         if (!up_clx_support || !down_clx_support)
3548                 return -EOPNOTSUPP;
3549
3550         ret = tb_port_clx_enable(up, clx);
3551         if (ret)
3552                 return ret;
3553
3554         ret = tb_port_clx_enable(down, clx);
3555         if (ret) {
3556                 tb_port_clx_disable(up, clx);
3557                 return ret;
3558         }
3559
3560         ret = tb_switch_mask_clx_objections(sw);
3561         if (ret) {
3562                 tb_port_clx_disable(up, clx);
3563                 tb_port_clx_disable(down, clx);
3564                 return ret;
3565         }
3566
3567         sw->clx = clx;
3568
3569         tb_port_dbg(up, "%s enabled\n", tb_switch_clx_name(clx));
3570         return 0;
3571 }
3572
3573 /**
3574  * tb_switch_enable_clx() - Enable CLx on upstream port of specified router
3575  * @sw: Router to enable CLx for
3576  * @clx: The CLx state to enable
3577  *
3578  * Enable CLx state only for first hop router. That is the most common
3579  * use-case, that is intended for better thermal management, and so helps
3580  * to improve performance. CLx is enabled only if both sides of the link
3581  * support CLx, and if both sides of the link are not configured as two
3582  * single lane links and only if the link is not inter-domain link. The
3583  * complete set of conditions is described in CM Guide 1.0 section 8.1.
3584  *
3585  * Return: Returns 0 on success or an error code on failure.
3586  */
3587 int tb_switch_enable_clx(struct tb_switch *sw, enum tb_clx clx)
3588 {
3589         struct tb_switch *root_sw = sw->tb->root_switch;
3590
3591         if (!clx_enabled)
3592                 return 0;
3593
3594         /*
3595          * CLx is not enabled and validated on Intel USB4 platforms before
3596          * Alder Lake.
3597          */
3598         if (root_sw->generation < 4 || tb_switch_is_tiger_lake(root_sw))
3599                 return 0;
3600
3601         switch (clx) {
3602         case TB_CL1:
3603                 /* CL0s and CL1 are enabled and supported together */
3604                 return __tb_switch_enable_clx(sw, clx);
3605
3606         default:
3607                 return -EOPNOTSUPP;
3608         }
3609 }
3610
3611 static int __tb_switch_disable_clx(struct tb_switch *sw, enum tb_clx clx)
3612 {
3613         struct tb_switch *parent = tb_switch_parent(sw);
3614         struct tb_port *up, *down;
3615         int ret;
3616
3617         if (!tb_switch_is_clx_supported(sw))
3618                 return 0;
3619
3620         /*
3621          * Disable CLx for host router's downstream port as part of the
3622          * downstream router enabling procedure.
3623          */
3624         if (!tb_route(sw))
3625                 return 0;
3626
3627         /* Disable CLx only for first hop router (depth = 1) */
3628         if (tb_route(parent))
3629                 return 0;
3630
3631         up = tb_upstream_port(sw);
3632         down = tb_port_at(tb_route(sw), parent);
3633         ret = tb_port_clx_disable(up, clx);
3634         if (ret)
3635                 return ret;
3636
3637         ret = tb_port_clx_disable(down, clx);
3638         if (ret)
3639                 return ret;
3640
3641         sw->clx = TB_CLX_DISABLE;
3642
3643         tb_port_dbg(up, "%s disabled\n", tb_switch_clx_name(clx));
3644         return 0;
3645 }
3646
3647 /**
3648  * tb_switch_disable_clx() - Disable CLx on upstream port of specified router
3649  * @sw: Router to disable CLx for
3650  * @clx: The CLx state to disable
3651  *
3652  * Return: Returns 0 on success or an error code on failure.
3653  */
3654 int tb_switch_disable_clx(struct tb_switch *sw, enum tb_clx clx)
3655 {
3656         if (!clx_enabled)
3657                 return 0;
3658
3659         switch (clx) {
3660         case TB_CL1:
3661                 /* CL0s and CL1 are enabled and supported together */
3662                 return __tb_switch_disable_clx(sw, clx);
3663
3664         default:
3665                 return -EOPNOTSUPP;
3666         }
3667 }
3668
3669 /**
3670  * tb_switch_mask_clx_objections() - Mask CLx objections for a router
3671  * @sw: Router to mask objections for
3672  *
3673  * Mask the objections coming from the second depth routers in order to
3674  * stop these objections from interfering with the CLx states of the first
3675  * depth link.
3676  */
3677 int tb_switch_mask_clx_objections(struct tb_switch *sw)
3678 {
3679         int up_port = sw->config.upstream_port_number;
3680         u32 offset, val[2], mask_obj, unmask_obj;
3681         int ret, i;
3682
3683         /* Only Titan Ridge of pre-USB4 devices support CLx states */
3684         if (!tb_switch_is_titan_ridge(sw))
3685                 return 0;
3686
3687         if (!tb_route(sw))
3688                 return 0;
3689
3690         /*
3691          * In Titan Ridge there are only 2 dual-lane Thunderbolt ports:
3692          * Port A consists of lane adapters 1,2 and
3693          * Port B consists of lane adapters 3,4
3694          * If upstream port is A, (lanes are 1,2), we mask objections from
3695          * port B (lanes 3,4) and unmask objections from Port A and vice-versa.
3696          */
3697         if (up_port == 1) {
3698                 mask_obj = TB_LOW_PWR_C0_PORT_B_MASK;
3699                 unmask_obj = TB_LOW_PWR_C1_PORT_A_MASK;
3700                 offset = TB_LOW_PWR_C1_CL1;
3701         } else {
3702                 mask_obj = TB_LOW_PWR_C1_PORT_A_MASK;
3703                 unmask_obj = TB_LOW_PWR_C0_PORT_B_MASK;
3704                 offset = TB_LOW_PWR_C3_CL1;
3705         }
3706
3707         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH,
3708                          sw->cap_lp + offset, ARRAY_SIZE(val));
3709         if (ret)
3710                 return ret;
3711
3712         for (i = 0; i < ARRAY_SIZE(val); i++) {
3713                 val[i] |= mask_obj;
3714                 val[i] &= ~unmask_obj;
3715         }
3716
3717         return tb_sw_write(sw, &val, TB_CFG_SWITCH,
3718                            sw->cap_lp + offset, ARRAY_SIZE(val));
3719 }
3720
3721 /*
3722  * Can be used for read/write a specified PCIe bridge for any Thunderbolt 3
3723  * device. For now used only for Titan Ridge.
3724  */
3725 static int tb_switch_pcie_bridge_write(struct tb_switch *sw, unsigned int bridge,
3726                                        unsigned int pcie_offset, u32 value)
3727 {
3728         u32 offset, command, val;
3729         int ret;
3730
3731         if (sw->generation != 3)
3732                 return -EOPNOTSUPP;
3733
3734         offset = sw->cap_plug_events + TB_PLUG_EVENTS_PCIE_WR_DATA;
3735         ret = tb_sw_write(sw, &value, TB_CFG_SWITCH, offset, 1);
3736         if (ret)
3737                 return ret;
3738
3739         command = pcie_offset & TB_PLUG_EVENTS_PCIE_CMD_DW_OFFSET_MASK;
3740         command |= BIT(bridge + TB_PLUG_EVENTS_PCIE_CMD_BR_SHIFT);
3741         command |= TB_PLUG_EVENTS_PCIE_CMD_RD_WR_MASK;
3742         command |= TB_PLUG_EVENTS_PCIE_CMD_COMMAND_VAL
3743                         << TB_PLUG_EVENTS_PCIE_CMD_COMMAND_SHIFT;
3744         command |= TB_PLUG_EVENTS_PCIE_CMD_REQ_ACK_MASK;
3745
3746         offset = sw->cap_plug_events + TB_PLUG_EVENTS_PCIE_CMD;
3747
3748         ret = tb_sw_write(sw, &command, TB_CFG_SWITCH, offset, 1);
3749         if (ret)
3750                 return ret;
3751
3752         ret = tb_switch_wait_for_bit(sw, offset,
3753                                      TB_PLUG_EVENTS_PCIE_CMD_REQ_ACK_MASK, 0, 100);
3754         if (ret)
3755                 return ret;
3756
3757         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, offset, 1);
3758         if (ret)
3759                 return ret;
3760
3761         if (val & TB_PLUG_EVENTS_PCIE_CMD_TIMEOUT_MASK)
3762                 return -ETIMEDOUT;
3763
3764         return 0;
3765 }
3766
3767 /**
3768  * tb_switch_pcie_l1_enable() - Enable PCIe link to enter L1 state
3769  * @sw: Router to enable PCIe L1
3770  *
3771  * For Titan Ridge switch to enter CLx state, its PCIe bridges shall enable
3772  * entry to PCIe L1 state. Shall be called after the upstream PCIe tunnel
3773  * was configured. Due to Intel platforms limitation, shall be called only
3774  * for first hop switch.
3775  */
3776 int tb_switch_pcie_l1_enable(struct tb_switch *sw)
3777 {
3778         struct tb_switch *parent = tb_switch_parent(sw);
3779         int ret;
3780
3781         if (!tb_route(sw))
3782                 return 0;
3783
3784         if (!tb_switch_is_titan_ridge(sw))
3785                 return 0;
3786
3787         /* Enable PCIe L1 enable only for first hop router (depth = 1) */
3788         if (tb_route(parent))
3789                 return 0;
3790
3791         /* Write to downstream PCIe bridge #5 aka Dn4 */
3792         ret = tb_switch_pcie_bridge_write(sw, 5, 0x143, 0x0c7806b1);
3793         if (ret)
3794                 return ret;
3795
3796         /* Write to Upstream PCIe bridge #0 aka Up0 */
3797         return tb_switch_pcie_bridge_write(sw, 0, 0x143, 0x0c5806b1);
3798 }
3799
3800 /**
3801  * tb_switch_xhci_connect() - Connect internal xHCI
3802  * @sw: Router whose xHCI to connect
3803  *
3804  * Can be called to any router. For Alpine Ridge and Titan Ridge
3805  * performs special flows that bring the xHCI functional for any device
3806  * connected to the type-C port. Call only after PCIe tunnel has been
3807  * established. The function only does the connect if not done already
3808  * so can be called several times for the same router.
3809  */
3810 int tb_switch_xhci_connect(struct tb_switch *sw)
3811 {
3812         bool usb_port1, usb_port3, xhci_port1, xhci_port3;
3813         struct tb_port *port1, *port3;
3814         int ret;
3815
3816         port1 = &sw->ports[1];
3817         port3 = &sw->ports[3];
3818
3819         if (tb_switch_is_alpine_ridge(sw)) {
3820                 usb_port1 = tb_lc_is_usb_plugged(port1);
3821                 usb_port3 = tb_lc_is_usb_plugged(port3);
3822                 xhci_port1 = tb_lc_is_xhci_connected(port1);
3823                 xhci_port3 = tb_lc_is_xhci_connected(port3);
3824
3825                 /* Figure out correct USB port to connect */
3826                 if (usb_port1 && !xhci_port1) {
3827                         ret = tb_lc_xhci_connect(port1);
3828                         if (ret)
3829                                 return ret;
3830                 }
3831                 if (usb_port3 && !xhci_port3)
3832                         return tb_lc_xhci_connect(port3);
3833         } else if (tb_switch_is_titan_ridge(sw)) {
3834                 ret = tb_lc_xhci_connect(port1);
3835                 if (ret)
3836                         return ret;
3837                 return tb_lc_xhci_connect(port3);
3838         }
3839
3840         return 0;
3841 }
3842
3843 /**
3844  * tb_switch_xhci_disconnect() - Disconnect internal xHCI
3845  * @sw: Router whose xHCI to disconnect
3846  *
3847  * The opposite of tb_switch_xhci_connect(). Disconnects xHCI on both
3848  * ports.
3849  */
3850 void tb_switch_xhci_disconnect(struct tb_switch *sw)
3851 {
3852         if (sw->generation == 3) {
3853                 struct tb_port *port1 = &sw->ports[1];
3854                 struct tb_port *port3 = &sw->ports[3];
3855
3856                 tb_lc_xhci_disconnect(port1);
3857                 tb_port_dbg(port1, "disconnected xHCI\n");
3858                 tb_lc_xhci_disconnect(port3);
3859                 tb_port_dbg(port3, "disconnected xHCI\n");
3860         }
3861 }