thunderbolt: Split setting link width and lane bonding into own functions
[linux-2.6-microblaze.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                         return ret;
1173                 else if (ret == width)
1174                         return 0;
1175
1176                 usleep_range(1000, 2000);
1177         } while (ktime_before(ktime_get(), timeout));
1178
1179         return -ETIMEDOUT;
1180 }
1181
1182 static int tb_port_do_update_credits(struct tb_port *port)
1183 {
1184         u32 nfc_credits;
1185         int ret;
1186
1187         ret = tb_port_read(port, &nfc_credits, TB_CFG_PORT, ADP_CS_4, 1);
1188         if (ret)
1189                 return ret;
1190
1191         if (nfc_credits != port->config.nfc_credits) {
1192                 u32 total;
1193
1194                 total = (nfc_credits & ADP_CS_4_TOTAL_BUFFERS_MASK) >>
1195                         ADP_CS_4_TOTAL_BUFFERS_SHIFT;
1196
1197                 tb_port_dbg(port, "total credits changed %u -> %u\n",
1198                             port->total_credits, total);
1199
1200                 port->config.nfc_credits = nfc_credits;
1201                 port->total_credits = total;
1202         }
1203
1204         return 0;
1205 }
1206
1207 /**
1208  * tb_port_update_credits() - Re-read port total credits
1209  * @port: Port to update
1210  *
1211  * After the link is bonded (or bonding was disabled) the port total
1212  * credits may change, so this function needs to be called to re-read
1213  * the credits. Updates also the second lane adapter.
1214  */
1215 int tb_port_update_credits(struct tb_port *port)
1216 {
1217         int ret;
1218
1219         ret = tb_port_do_update_credits(port);
1220         if (ret)
1221                 return ret;
1222         return tb_port_do_update_credits(port->dual_link_port);
1223 }
1224
1225 static int tb_port_start_lane_initialization(struct tb_port *port)
1226 {
1227         int ret;
1228
1229         if (tb_switch_is_usb4(port->sw))
1230                 return 0;
1231
1232         ret = tb_lc_start_lane_initialization(port);
1233         return ret == -EINVAL ? 0 : ret;
1234 }
1235
1236 /*
1237  * Returns true if the port had something (router, XDomain) connected
1238  * before suspend.
1239  */
1240 static bool tb_port_resume(struct tb_port *port)
1241 {
1242         bool has_remote = tb_port_has_remote(port);
1243
1244         if (port->usb4) {
1245                 usb4_port_device_resume(port->usb4);
1246         } else if (!has_remote) {
1247                 /*
1248                  * For disconnected downstream lane adapters start lane
1249                  * initialization now so we detect future connects.
1250                  *
1251                  * For XDomain start the lane initialzation now so the
1252                  * link gets re-established.
1253                  *
1254                  * This is only needed for non-USB4 ports.
1255                  */
1256                 if (!tb_is_upstream_port(port) || port->xdomain)
1257                         tb_port_start_lane_initialization(port);
1258         }
1259
1260         return has_remote || port->xdomain;
1261 }
1262
1263 /**
1264  * tb_port_is_enabled() - Is the adapter port enabled
1265  * @port: Port to check
1266  */
1267 bool tb_port_is_enabled(struct tb_port *port)
1268 {
1269         switch (port->config.type) {
1270         case TB_TYPE_PCIE_UP:
1271         case TB_TYPE_PCIE_DOWN:
1272                 return tb_pci_port_is_enabled(port);
1273
1274         case TB_TYPE_DP_HDMI_IN:
1275         case TB_TYPE_DP_HDMI_OUT:
1276                 return tb_dp_port_is_enabled(port);
1277
1278         case TB_TYPE_USB3_UP:
1279         case TB_TYPE_USB3_DOWN:
1280                 return tb_usb3_port_is_enabled(port);
1281
1282         default:
1283                 return false;
1284         }
1285 }
1286
1287 /**
1288  * tb_usb3_port_is_enabled() - Is the USB3 adapter port enabled
1289  * @port: USB3 adapter port to check
1290  */
1291 bool tb_usb3_port_is_enabled(struct tb_port *port)
1292 {
1293         u32 data;
1294
1295         if (tb_port_read(port, &data, TB_CFG_PORT,
1296                          port->cap_adap + ADP_USB3_CS_0, 1))
1297                 return false;
1298
1299         return !!(data & ADP_USB3_CS_0_PE);
1300 }
1301
1302 /**
1303  * tb_usb3_port_enable() - Enable USB3 adapter port
1304  * @port: USB3 adapter port to enable
1305  * @enable: Enable/disable the USB3 adapter
1306  */
1307 int tb_usb3_port_enable(struct tb_port *port, bool enable)
1308 {
1309         u32 word = enable ? (ADP_USB3_CS_0_PE | ADP_USB3_CS_0_V)
1310                           : ADP_USB3_CS_0_V;
1311
1312         if (!port->cap_adap)
1313                 return -ENXIO;
1314         return tb_port_write(port, &word, TB_CFG_PORT,
1315                              port->cap_adap + ADP_USB3_CS_0, 1);
1316 }
1317
1318 /**
1319  * tb_pci_port_is_enabled() - Is the PCIe adapter port enabled
1320  * @port: PCIe port to check
1321  */
1322 bool tb_pci_port_is_enabled(struct tb_port *port)
1323 {
1324         u32 data;
1325
1326         if (tb_port_read(port, &data, TB_CFG_PORT,
1327                          port->cap_adap + ADP_PCIE_CS_0, 1))
1328                 return false;
1329
1330         return !!(data & ADP_PCIE_CS_0_PE);
1331 }
1332
1333 /**
1334  * tb_pci_port_enable() - Enable PCIe adapter port
1335  * @port: PCIe port to enable
1336  * @enable: Enable/disable the PCIe adapter
1337  */
1338 int tb_pci_port_enable(struct tb_port *port, bool enable)
1339 {
1340         u32 word = enable ? ADP_PCIE_CS_0_PE : 0x0;
1341         if (!port->cap_adap)
1342                 return -ENXIO;
1343         return tb_port_write(port, &word, TB_CFG_PORT,
1344                              port->cap_adap + ADP_PCIE_CS_0, 1);
1345 }
1346
1347 /**
1348  * tb_dp_port_hpd_is_active() - Is HPD already active
1349  * @port: DP out port to check
1350  *
1351  * Checks if the DP OUT adapter port has HDP bit already set.
1352  */
1353 int tb_dp_port_hpd_is_active(struct tb_port *port)
1354 {
1355         u32 data;
1356         int ret;
1357
1358         ret = tb_port_read(port, &data, TB_CFG_PORT,
1359                            port->cap_adap + ADP_DP_CS_2, 1);
1360         if (ret)
1361                 return ret;
1362
1363         return !!(data & ADP_DP_CS_2_HDP);
1364 }
1365
1366 /**
1367  * tb_dp_port_hpd_clear() - Clear HPD from DP IN port
1368  * @port: Port to clear HPD
1369  *
1370  * If the DP IN port has HDP set, this function can be used to clear it.
1371  */
1372 int tb_dp_port_hpd_clear(struct tb_port *port)
1373 {
1374         u32 data;
1375         int ret;
1376
1377         ret = tb_port_read(port, &data, TB_CFG_PORT,
1378                            port->cap_adap + ADP_DP_CS_3, 1);
1379         if (ret)
1380                 return ret;
1381
1382         data |= ADP_DP_CS_3_HDPC;
1383         return tb_port_write(port, &data, TB_CFG_PORT,
1384                              port->cap_adap + ADP_DP_CS_3, 1);
1385 }
1386
1387 /**
1388  * tb_dp_port_set_hops() - Set video/aux Hop IDs for DP port
1389  * @port: DP IN/OUT port to set hops
1390  * @video: Video Hop ID
1391  * @aux_tx: AUX TX Hop ID
1392  * @aux_rx: AUX RX Hop ID
1393  *
1394  * Programs specified Hop IDs for DP IN/OUT port. Can be called for USB4
1395  * router DP adapters too but does not program the values as the fields
1396  * are read-only.
1397  */
1398 int tb_dp_port_set_hops(struct tb_port *port, unsigned int video,
1399                         unsigned int aux_tx, unsigned int aux_rx)
1400 {
1401         u32 data[2];
1402         int ret;
1403
1404         if (tb_switch_is_usb4(port->sw))
1405                 return 0;
1406
1407         ret = tb_port_read(port, data, TB_CFG_PORT,
1408                            port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1409         if (ret)
1410                 return ret;
1411
1412         data[0] &= ~ADP_DP_CS_0_VIDEO_HOPID_MASK;
1413         data[1] &= ~ADP_DP_CS_1_AUX_RX_HOPID_MASK;
1414         data[1] &= ~ADP_DP_CS_1_AUX_RX_HOPID_MASK;
1415
1416         data[0] |= (video << ADP_DP_CS_0_VIDEO_HOPID_SHIFT) &
1417                 ADP_DP_CS_0_VIDEO_HOPID_MASK;
1418         data[1] |= aux_tx & ADP_DP_CS_1_AUX_TX_HOPID_MASK;
1419         data[1] |= (aux_rx << ADP_DP_CS_1_AUX_RX_HOPID_SHIFT) &
1420                 ADP_DP_CS_1_AUX_RX_HOPID_MASK;
1421
1422         return tb_port_write(port, data, TB_CFG_PORT,
1423                              port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1424 }
1425
1426 /**
1427  * tb_dp_port_is_enabled() - Is DP adapter port enabled
1428  * @port: DP adapter port to check
1429  */
1430 bool tb_dp_port_is_enabled(struct tb_port *port)
1431 {
1432         u32 data[2];
1433
1434         if (tb_port_read(port, data, TB_CFG_PORT, port->cap_adap + ADP_DP_CS_0,
1435                          ARRAY_SIZE(data)))
1436                 return false;
1437
1438         return !!(data[0] & (ADP_DP_CS_0_VE | ADP_DP_CS_0_AE));
1439 }
1440
1441 /**
1442  * tb_dp_port_enable() - Enables/disables DP paths of a port
1443  * @port: DP IN/OUT port
1444  * @enable: Enable/disable DP path
1445  *
1446  * Once Hop IDs are programmed DP paths can be enabled or disabled by
1447  * calling this function.
1448  */
1449 int tb_dp_port_enable(struct tb_port *port, bool enable)
1450 {
1451         u32 data[2];
1452         int ret;
1453
1454         ret = tb_port_read(port, data, TB_CFG_PORT,
1455                           port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1456         if (ret)
1457                 return ret;
1458
1459         if (enable)
1460                 data[0] |= ADP_DP_CS_0_VE | ADP_DP_CS_0_AE;
1461         else
1462                 data[0] &= ~(ADP_DP_CS_0_VE | ADP_DP_CS_0_AE);
1463
1464         return tb_port_write(port, data, TB_CFG_PORT,
1465                              port->cap_adap + ADP_DP_CS_0, ARRAY_SIZE(data));
1466 }
1467
1468 /* switch utility functions */
1469
1470 static const char *tb_switch_generation_name(const struct tb_switch *sw)
1471 {
1472         switch (sw->generation) {
1473         case 1:
1474                 return "Thunderbolt 1";
1475         case 2:
1476                 return "Thunderbolt 2";
1477         case 3:
1478                 return "Thunderbolt 3";
1479         case 4:
1480                 return "USB4";
1481         default:
1482                 return "Unknown";
1483         }
1484 }
1485
1486 static void tb_dump_switch(const struct tb *tb, const struct tb_switch *sw)
1487 {
1488         const struct tb_regs_switch_header *regs = &sw->config;
1489
1490         tb_dbg(tb, " %s Switch: %x:%x (Revision: %d, TB Version: %d)\n",
1491                tb_switch_generation_name(sw), regs->vendor_id, regs->device_id,
1492                regs->revision, regs->thunderbolt_version);
1493         tb_dbg(tb, "  Max Port Number: %d\n", regs->max_port_number);
1494         tb_dbg(tb, "  Config:\n");
1495         tb_dbg(tb,
1496                 "   Upstream Port Number: %d Depth: %d Route String: %#llx Enabled: %d, PlugEventsDelay: %dms\n",
1497                regs->upstream_port_number, regs->depth,
1498                (((u64) regs->route_hi) << 32) | regs->route_lo,
1499                regs->enabled, regs->plug_events_delay);
1500         tb_dbg(tb, "   unknown1: %#x unknown4: %#x\n",
1501                regs->__unknown1, regs->__unknown4);
1502 }
1503
1504 /**
1505  * tb_switch_reset() - reconfigure route, enable and send TB_CFG_PKG_RESET
1506  * @sw: Switch to reset
1507  *
1508  * Return: Returns 0 on success or an error code on failure.
1509  */
1510 int tb_switch_reset(struct tb_switch *sw)
1511 {
1512         struct tb_cfg_result res;
1513
1514         if (sw->generation > 1)
1515                 return 0;
1516
1517         tb_sw_dbg(sw, "resetting switch\n");
1518
1519         res.err = tb_sw_write(sw, ((u32 *) &sw->config) + 2,
1520                               TB_CFG_SWITCH, 2, 2);
1521         if (res.err)
1522                 return res.err;
1523         res = tb_cfg_reset(sw->tb->ctl, tb_route(sw));
1524         if (res.err > 0)
1525                 return -EIO;
1526         return res.err;
1527 }
1528
1529 /**
1530  * tb_switch_wait_for_bit() - Wait for specified value of bits in offset
1531  * @sw: Router to read the offset value from
1532  * @offset: Offset in the router config space to read from
1533  * @bit: Bit mask in the offset to wait for
1534  * @value: Value of the bits to wait for
1535  * @timeout_msec: Timeout in ms how long to wait
1536  *
1537  * Wait till the specified bits in specified offset reach specified value.
1538  * Returns %0 in case of success, %-ETIMEDOUT if the @value was not reached
1539  * within the given timeout or a negative errno in case of failure.
1540  */
1541 int tb_switch_wait_for_bit(struct tb_switch *sw, u32 offset, u32 bit,
1542                            u32 value, int timeout_msec)
1543 {
1544         ktime_t timeout = ktime_add_ms(ktime_get(), timeout_msec);
1545
1546         do {
1547                 u32 val;
1548                 int ret;
1549
1550                 ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, offset, 1);
1551                 if (ret)
1552                         return ret;
1553
1554                 if ((val & bit) == value)
1555                         return 0;
1556
1557                 usleep_range(50, 100);
1558         } while (ktime_before(ktime_get(), timeout));
1559
1560         return -ETIMEDOUT;
1561 }
1562
1563 /*
1564  * tb_plug_events_active() - enable/disable plug events on a switch
1565  *
1566  * Also configures a sane plug_events_delay of 255ms.
1567  *
1568  * Return: Returns 0 on success or an error code on failure.
1569  */
1570 static int tb_plug_events_active(struct tb_switch *sw, bool active)
1571 {
1572         u32 data;
1573         int res;
1574
1575         if (tb_switch_is_icm(sw) || tb_switch_is_usb4(sw))
1576                 return 0;
1577
1578         sw->config.plug_events_delay = 0xff;
1579         res = tb_sw_write(sw, ((u32 *) &sw->config) + 4, TB_CFG_SWITCH, 4, 1);
1580         if (res)
1581                 return res;
1582
1583         res = tb_sw_read(sw, &data, TB_CFG_SWITCH, sw->cap_plug_events + 1, 1);
1584         if (res)
1585                 return res;
1586
1587         if (active) {
1588                 data = data & 0xFFFFFF83;
1589                 switch (sw->config.device_id) {
1590                 case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
1591                 case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
1592                 case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
1593                         break;
1594                 default:
1595                         /*
1596                          * Skip Alpine Ridge, it needs to have vendor
1597                          * specific USB hotplug event enabled for the
1598                          * internal xHCI to work.
1599                          */
1600                         if (!tb_switch_is_alpine_ridge(sw))
1601                                 data |= TB_PLUG_EVENTS_USB_DISABLE;
1602                 }
1603         } else {
1604                 data = data | 0x7c;
1605         }
1606         return tb_sw_write(sw, &data, TB_CFG_SWITCH,
1607                            sw->cap_plug_events + 1, 1);
1608 }
1609
1610 static ssize_t authorized_show(struct device *dev,
1611                                struct device_attribute *attr,
1612                                char *buf)
1613 {
1614         struct tb_switch *sw = tb_to_switch(dev);
1615
1616         return sprintf(buf, "%u\n", sw->authorized);
1617 }
1618
1619 static int disapprove_switch(struct device *dev, void *not_used)
1620 {
1621         char *envp[] = { "AUTHORIZED=0", NULL };
1622         struct tb_switch *sw;
1623
1624         sw = tb_to_switch(dev);
1625         if (sw && sw->authorized) {
1626                 int ret;
1627
1628                 /* First children */
1629                 ret = device_for_each_child_reverse(&sw->dev, NULL, disapprove_switch);
1630                 if (ret)
1631                         return ret;
1632
1633                 ret = tb_domain_disapprove_switch(sw->tb, sw);
1634                 if (ret)
1635                         return ret;
1636
1637                 sw->authorized = 0;
1638                 kobject_uevent_env(&sw->dev.kobj, KOBJ_CHANGE, envp);
1639         }
1640
1641         return 0;
1642 }
1643
1644 static int tb_switch_set_authorized(struct tb_switch *sw, unsigned int val)
1645 {
1646         char envp_string[13];
1647         int ret = -EINVAL;
1648         char *envp[] = { envp_string, NULL };
1649
1650         if (!mutex_trylock(&sw->tb->lock))
1651                 return restart_syscall();
1652
1653         if (!!sw->authorized == !!val)
1654                 goto unlock;
1655
1656         switch (val) {
1657         /* Disapprove switch */
1658         case 0:
1659                 if (tb_route(sw)) {
1660                         ret = disapprove_switch(&sw->dev, NULL);
1661                         goto unlock;
1662                 }
1663                 break;
1664
1665         /* Approve switch */
1666         case 1:
1667                 if (sw->key)
1668                         ret = tb_domain_approve_switch_key(sw->tb, sw);
1669                 else
1670                         ret = tb_domain_approve_switch(sw->tb, sw);
1671                 break;
1672
1673         /* Challenge switch */
1674         case 2:
1675                 if (sw->key)
1676                         ret = tb_domain_challenge_switch_key(sw->tb, sw);
1677                 break;
1678
1679         default:
1680                 break;
1681         }
1682
1683         if (!ret) {
1684                 sw->authorized = val;
1685                 /*
1686                  * Notify status change to the userspace, informing the new
1687                  * value of /sys/bus/thunderbolt/devices/.../authorized.
1688                  */
1689                 sprintf(envp_string, "AUTHORIZED=%u", sw->authorized);
1690                 kobject_uevent_env(&sw->dev.kobj, KOBJ_CHANGE, envp);
1691         }
1692
1693 unlock:
1694         mutex_unlock(&sw->tb->lock);
1695         return ret;
1696 }
1697
1698 static ssize_t authorized_store(struct device *dev,
1699                                 struct device_attribute *attr,
1700                                 const char *buf, size_t count)
1701 {
1702         struct tb_switch *sw = tb_to_switch(dev);
1703         unsigned int val;
1704         ssize_t ret;
1705
1706         ret = kstrtouint(buf, 0, &val);
1707         if (ret)
1708                 return ret;
1709         if (val > 2)
1710                 return -EINVAL;
1711
1712         pm_runtime_get_sync(&sw->dev);
1713         ret = tb_switch_set_authorized(sw, val);
1714         pm_runtime_mark_last_busy(&sw->dev);
1715         pm_runtime_put_autosuspend(&sw->dev);
1716
1717         return ret ? ret : count;
1718 }
1719 static DEVICE_ATTR_RW(authorized);
1720
1721 static ssize_t boot_show(struct device *dev, struct device_attribute *attr,
1722                          char *buf)
1723 {
1724         struct tb_switch *sw = tb_to_switch(dev);
1725
1726         return sprintf(buf, "%u\n", sw->boot);
1727 }
1728 static DEVICE_ATTR_RO(boot);
1729
1730 static ssize_t device_show(struct device *dev, struct device_attribute *attr,
1731                            char *buf)
1732 {
1733         struct tb_switch *sw = tb_to_switch(dev);
1734
1735         return sprintf(buf, "%#x\n", sw->device);
1736 }
1737 static DEVICE_ATTR_RO(device);
1738
1739 static ssize_t
1740 device_name_show(struct device *dev, struct device_attribute *attr, char *buf)
1741 {
1742         struct tb_switch *sw = tb_to_switch(dev);
1743
1744         return sprintf(buf, "%s\n", sw->device_name ? sw->device_name : "");
1745 }
1746 static DEVICE_ATTR_RO(device_name);
1747
1748 static ssize_t
1749 generation_show(struct device *dev, struct device_attribute *attr, char *buf)
1750 {
1751         struct tb_switch *sw = tb_to_switch(dev);
1752
1753         return sprintf(buf, "%u\n", sw->generation);
1754 }
1755 static DEVICE_ATTR_RO(generation);
1756
1757 static ssize_t key_show(struct device *dev, struct device_attribute *attr,
1758                         char *buf)
1759 {
1760         struct tb_switch *sw = tb_to_switch(dev);
1761         ssize_t ret;
1762
1763         if (!mutex_trylock(&sw->tb->lock))
1764                 return restart_syscall();
1765
1766         if (sw->key)
1767                 ret = sprintf(buf, "%*phN\n", TB_SWITCH_KEY_SIZE, sw->key);
1768         else
1769                 ret = sprintf(buf, "\n");
1770
1771         mutex_unlock(&sw->tb->lock);
1772         return ret;
1773 }
1774
1775 static ssize_t key_store(struct device *dev, struct device_attribute *attr,
1776                          const char *buf, size_t count)
1777 {
1778         struct tb_switch *sw = tb_to_switch(dev);
1779         u8 key[TB_SWITCH_KEY_SIZE];
1780         ssize_t ret = count;
1781         bool clear = false;
1782
1783         if (!strcmp(buf, "\n"))
1784                 clear = true;
1785         else if (hex2bin(key, buf, sizeof(key)))
1786                 return -EINVAL;
1787
1788         if (!mutex_trylock(&sw->tb->lock))
1789                 return restart_syscall();
1790
1791         if (sw->authorized) {
1792                 ret = -EBUSY;
1793         } else {
1794                 kfree(sw->key);
1795                 if (clear) {
1796                         sw->key = NULL;
1797                 } else {
1798                         sw->key = kmemdup(key, sizeof(key), GFP_KERNEL);
1799                         if (!sw->key)
1800                                 ret = -ENOMEM;
1801                 }
1802         }
1803
1804         mutex_unlock(&sw->tb->lock);
1805         return ret;
1806 }
1807 static DEVICE_ATTR(key, 0600, key_show, key_store);
1808
1809 static ssize_t speed_show(struct device *dev, struct device_attribute *attr,
1810                           char *buf)
1811 {
1812         struct tb_switch *sw = tb_to_switch(dev);
1813
1814         return sprintf(buf, "%u.0 Gb/s\n", sw->link_speed);
1815 }
1816
1817 /*
1818  * Currently all lanes must run at the same speed but we expose here
1819  * both directions to allow possible asymmetric links in the future.
1820  */
1821 static DEVICE_ATTR(rx_speed, 0444, speed_show, NULL);
1822 static DEVICE_ATTR(tx_speed, 0444, speed_show, NULL);
1823
1824 static ssize_t lanes_show(struct device *dev, struct device_attribute *attr,
1825                           char *buf)
1826 {
1827         struct tb_switch *sw = tb_to_switch(dev);
1828
1829         return sprintf(buf, "%u\n", sw->link_width);
1830 }
1831
1832 /*
1833  * Currently link has same amount of lanes both directions (1 or 2) but
1834  * expose them separately to allow possible asymmetric links in the future.
1835  */
1836 static DEVICE_ATTR(rx_lanes, 0444, lanes_show, NULL);
1837 static DEVICE_ATTR(tx_lanes, 0444, lanes_show, NULL);
1838
1839 static ssize_t nvm_authenticate_show(struct device *dev,
1840         struct device_attribute *attr, char *buf)
1841 {
1842         struct tb_switch *sw = tb_to_switch(dev);
1843         u32 status;
1844
1845         nvm_get_auth_status(sw, &status);
1846         return sprintf(buf, "%#x\n", status);
1847 }
1848
1849 static ssize_t nvm_authenticate_sysfs(struct device *dev, const char *buf,
1850                                       bool disconnect)
1851 {
1852         struct tb_switch *sw = tb_to_switch(dev);
1853         int val, ret;
1854
1855         pm_runtime_get_sync(&sw->dev);
1856
1857         if (!mutex_trylock(&sw->tb->lock)) {
1858                 ret = restart_syscall();
1859                 goto exit_rpm;
1860         }
1861
1862         /* If NVMem devices are not yet added */
1863         if (!sw->nvm) {
1864                 ret = -EAGAIN;
1865                 goto exit_unlock;
1866         }
1867
1868         ret = kstrtoint(buf, 10, &val);
1869         if (ret)
1870                 goto exit_unlock;
1871
1872         /* Always clear the authentication status */
1873         nvm_clear_auth_status(sw);
1874
1875         if (val > 0) {
1876                 if (val == AUTHENTICATE_ONLY) {
1877                         if (disconnect)
1878                                 ret = -EINVAL;
1879                         else
1880                                 ret = nvm_authenticate(sw, true);
1881                 } else {
1882                         if (!sw->nvm->flushed) {
1883                                 if (!sw->nvm->buf) {
1884                                         ret = -EINVAL;
1885                                         goto exit_unlock;
1886                                 }
1887
1888                                 ret = nvm_validate_and_write(sw);
1889                                 if (ret || val == WRITE_ONLY)
1890                                         goto exit_unlock;
1891                         }
1892                         if (val == WRITE_AND_AUTHENTICATE) {
1893                                 if (disconnect)
1894                                         ret = tb_lc_force_power(sw);
1895                                 else
1896                                         ret = nvm_authenticate(sw, false);
1897                         }
1898                 }
1899         }
1900
1901 exit_unlock:
1902         mutex_unlock(&sw->tb->lock);
1903 exit_rpm:
1904         pm_runtime_mark_last_busy(&sw->dev);
1905         pm_runtime_put_autosuspend(&sw->dev);
1906
1907         return ret;
1908 }
1909
1910 static ssize_t nvm_authenticate_store(struct device *dev,
1911         struct device_attribute *attr, const char *buf, size_t count)
1912 {
1913         int ret = nvm_authenticate_sysfs(dev, buf, false);
1914         if (ret)
1915                 return ret;
1916         return count;
1917 }
1918 static DEVICE_ATTR_RW(nvm_authenticate);
1919
1920 static ssize_t nvm_authenticate_on_disconnect_show(struct device *dev,
1921         struct device_attribute *attr, char *buf)
1922 {
1923         return nvm_authenticate_show(dev, attr, buf);
1924 }
1925
1926 static ssize_t nvm_authenticate_on_disconnect_store(struct device *dev,
1927         struct device_attribute *attr, const char *buf, size_t count)
1928 {
1929         int ret;
1930
1931         ret = nvm_authenticate_sysfs(dev, buf, true);
1932         return ret ? ret : count;
1933 }
1934 static DEVICE_ATTR_RW(nvm_authenticate_on_disconnect);
1935
1936 static ssize_t nvm_version_show(struct device *dev,
1937                                 struct device_attribute *attr, char *buf)
1938 {
1939         struct tb_switch *sw = tb_to_switch(dev);
1940         int ret;
1941
1942         if (!mutex_trylock(&sw->tb->lock))
1943                 return restart_syscall();
1944
1945         if (sw->safe_mode)
1946                 ret = -ENODATA;
1947         else if (!sw->nvm)
1948                 ret = -EAGAIN;
1949         else
1950                 ret = sprintf(buf, "%x.%x\n", sw->nvm->major, sw->nvm->minor);
1951
1952         mutex_unlock(&sw->tb->lock);
1953
1954         return ret;
1955 }
1956 static DEVICE_ATTR_RO(nvm_version);
1957
1958 static ssize_t vendor_show(struct device *dev, struct device_attribute *attr,
1959                            char *buf)
1960 {
1961         struct tb_switch *sw = tb_to_switch(dev);
1962
1963         return sprintf(buf, "%#x\n", sw->vendor);
1964 }
1965 static DEVICE_ATTR_RO(vendor);
1966
1967 static ssize_t
1968 vendor_name_show(struct device *dev, struct device_attribute *attr, char *buf)
1969 {
1970         struct tb_switch *sw = tb_to_switch(dev);
1971
1972         return sprintf(buf, "%s\n", sw->vendor_name ? sw->vendor_name : "");
1973 }
1974 static DEVICE_ATTR_RO(vendor_name);
1975
1976 static ssize_t unique_id_show(struct device *dev, struct device_attribute *attr,
1977                               char *buf)
1978 {
1979         struct tb_switch *sw = tb_to_switch(dev);
1980
1981         return sprintf(buf, "%pUb\n", sw->uuid);
1982 }
1983 static DEVICE_ATTR_RO(unique_id);
1984
1985 static struct attribute *switch_attrs[] = {
1986         &dev_attr_authorized.attr,
1987         &dev_attr_boot.attr,
1988         &dev_attr_device.attr,
1989         &dev_attr_device_name.attr,
1990         &dev_attr_generation.attr,
1991         &dev_attr_key.attr,
1992         &dev_attr_nvm_authenticate.attr,
1993         &dev_attr_nvm_authenticate_on_disconnect.attr,
1994         &dev_attr_nvm_version.attr,
1995         &dev_attr_rx_speed.attr,
1996         &dev_attr_rx_lanes.attr,
1997         &dev_attr_tx_speed.attr,
1998         &dev_attr_tx_lanes.attr,
1999         &dev_attr_vendor.attr,
2000         &dev_attr_vendor_name.attr,
2001         &dev_attr_unique_id.attr,
2002         NULL,
2003 };
2004
2005 static umode_t switch_attr_is_visible(struct kobject *kobj,
2006                                       struct attribute *attr, int n)
2007 {
2008         struct device *dev = kobj_to_dev(kobj);
2009         struct tb_switch *sw = tb_to_switch(dev);
2010
2011         if (attr == &dev_attr_authorized.attr) {
2012                 if (sw->tb->security_level == TB_SECURITY_NOPCIE ||
2013                     sw->tb->security_level == TB_SECURITY_DPONLY)
2014                         return 0;
2015         } else if (attr == &dev_attr_device.attr) {
2016                 if (!sw->device)
2017                         return 0;
2018         } else if (attr == &dev_attr_device_name.attr) {
2019                 if (!sw->device_name)
2020                         return 0;
2021         } else if (attr == &dev_attr_vendor.attr)  {
2022                 if (!sw->vendor)
2023                         return 0;
2024         } else if (attr == &dev_attr_vendor_name.attr)  {
2025                 if (!sw->vendor_name)
2026                         return 0;
2027         } else if (attr == &dev_attr_key.attr) {
2028                 if (tb_route(sw) &&
2029                     sw->tb->security_level == TB_SECURITY_SECURE &&
2030                     sw->security_level == TB_SECURITY_SECURE)
2031                         return attr->mode;
2032                 return 0;
2033         } else if (attr == &dev_attr_rx_speed.attr ||
2034                    attr == &dev_attr_rx_lanes.attr ||
2035                    attr == &dev_attr_tx_speed.attr ||
2036                    attr == &dev_attr_tx_lanes.attr) {
2037                 if (tb_route(sw))
2038                         return attr->mode;
2039                 return 0;
2040         } else if (attr == &dev_attr_nvm_authenticate.attr) {
2041                 if (nvm_upgradeable(sw))
2042                         return attr->mode;
2043                 return 0;
2044         } else if (attr == &dev_attr_nvm_version.attr) {
2045                 if (nvm_readable(sw))
2046                         return attr->mode;
2047                 return 0;
2048         } else if (attr == &dev_attr_boot.attr) {
2049                 if (tb_route(sw))
2050                         return attr->mode;
2051                 return 0;
2052         } else if (attr == &dev_attr_nvm_authenticate_on_disconnect.attr) {
2053                 if (sw->quirks & QUIRK_FORCE_POWER_LINK_CONTROLLER)
2054                         return attr->mode;
2055                 return 0;
2056         }
2057
2058         return sw->safe_mode ? 0 : attr->mode;
2059 }
2060
2061 static const struct attribute_group switch_group = {
2062         .is_visible = switch_attr_is_visible,
2063         .attrs = switch_attrs,
2064 };
2065
2066 static const struct attribute_group *switch_groups[] = {
2067         &switch_group,
2068         NULL,
2069 };
2070
2071 static void tb_switch_release(struct device *dev)
2072 {
2073         struct tb_switch *sw = tb_to_switch(dev);
2074         struct tb_port *port;
2075
2076         dma_port_free(sw->dma_port);
2077
2078         tb_switch_for_each_port(sw, port) {
2079                 ida_destroy(&port->in_hopids);
2080                 ida_destroy(&port->out_hopids);
2081         }
2082
2083         kfree(sw->uuid);
2084         kfree(sw->device_name);
2085         kfree(sw->vendor_name);
2086         kfree(sw->ports);
2087         kfree(sw->drom);
2088         kfree(sw->key);
2089         kfree(sw);
2090 }
2091
2092 static int tb_switch_uevent(struct device *dev, struct kobj_uevent_env *env)
2093 {
2094         struct tb_switch *sw = tb_to_switch(dev);
2095         const char *type;
2096
2097         if (sw->config.thunderbolt_version == USB4_VERSION_1_0) {
2098                 if (add_uevent_var(env, "USB4_VERSION=1.0"))
2099                         return -ENOMEM;
2100         }
2101
2102         if (!tb_route(sw)) {
2103                 type = "host";
2104         } else {
2105                 const struct tb_port *port;
2106                 bool hub = false;
2107
2108                 /* Device is hub if it has any downstream ports */
2109                 tb_switch_for_each_port(sw, port) {
2110                         if (!port->disabled && !tb_is_upstream_port(port) &&
2111                              tb_port_is_null(port)) {
2112                                 hub = true;
2113                                 break;
2114                         }
2115                 }
2116
2117                 type = hub ? "hub" : "device";
2118         }
2119
2120         if (add_uevent_var(env, "USB4_TYPE=%s", type))
2121                 return -ENOMEM;
2122         return 0;
2123 }
2124
2125 /*
2126  * Currently only need to provide the callbacks. Everything else is handled
2127  * in the connection manager.
2128  */
2129 static int __maybe_unused tb_switch_runtime_suspend(struct device *dev)
2130 {
2131         struct tb_switch *sw = tb_to_switch(dev);
2132         const struct tb_cm_ops *cm_ops = sw->tb->cm_ops;
2133
2134         if (cm_ops->runtime_suspend_switch)
2135                 return cm_ops->runtime_suspend_switch(sw);
2136
2137         return 0;
2138 }
2139
2140 static int __maybe_unused tb_switch_runtime_resume(struct device *dev)
2141 {
2142         struct tb_switch *sw = tb_to_switch(dev);
2143         const struct tb_cm_ops *cm_ops = sw->tb->cm_ops;
2144
2145         if (cm_ops->runtime_resume_switch)
2146                 return cm_ops->runtime_resume_switch(sw);
2147         return 0;
2148 }
2149
2150 static const struct dev_pm_ops tb_switch_pm_ops = {
2151         SET_RUNTIME_PM_OPS(tb_switch_runtime_suspend, tb_switch_runtime_resume,
2152                            NULL)
2153 };
2154
2155 struct device_type tb_switch_type = {
2156         .name = "thunderbolt_device",
2157         .release = tb_switch_release,
2158         .uevent = tb_switch_uevent,
2159         .pm = &tb_switch_pm_ops,
2160 };
2161
2162 static int tb_switch_get_generation(struct tb_switch *sw)
2163 {
2164         switch (sw->config.device_id) {
2165         case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
2166         case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
2167         case PCI_DEVICE_ID_INTEL_LIGHT_PEAK:
2168         case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_2C:
2169         case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C:
2170         case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
2171         case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_2C_BRIDGE:
2172         case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_4C_BRIDGE:
2173                 return 1;
2174
2175         case PCI_DEVICE_ID_INTEL_WIN_RIDGE_2C_BRIDGE:
2176         case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_BRIDGE:
2177         case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_BRIDGE:
2178                 return 2;
2179
2180         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_LP_BRIDGE:
2181         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_2C_BRIDGE:
2182         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_4C_BRIDGE:
2183         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_2C_BRIDGE:
2184         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_4C_BRIDGE:
2185         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_2C_BRIDGE:
2186         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_4C_BRIDGE:
2187         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_DD_BRIDGE:
2188         case PCI_DEVICE_ID_INTEL_ICL_NHI0:
2189         case PCI_DEVICE_ID_INTEL_ICL_NHI1:
2190                 return 3;
2191
2192         default:
2193                 if (tb_switch_is_usb4(sw))
2194                         return 4;
2195
2196                 /*
2197                  * For unknown switches assume generation to be 1 to be
2198                  * on the safe side.
2199                  */
2200                 tb_sw_warn(sw, "unsupported switch device id %#x\n",
2201                            sw->config.device_id);
2202                 return 1;
2203         }
2204 }
2205
2206 static bool tb_switch_exceeds_max_depth(const struct tb_switch *sw, int depth)
2207 {
2208         int max_depth;
2209
2210         if (tb_switch_is_usb4(sw) ||
2211             (sw->tb->root_switch && tb_switch_is_usb4(sw->tb->root_switch)))
2212                 max_depth = USB4_SWITCH_MAX_DEPTH;
2213         else
2214                 max_depth = TB_SWITCH_MAX_DEPTH;
2215
2216         return depth > max_depth;
2217 }
2218
2219 /**
2220  * tb_switch_alloc() - allocate a switch
2221  * @tb: Pointer to the owning domain
2222  * @parent: Parent device for this switch
2223  * @route: Route string for this switch
2224  *
2225  * Allocates and initializes a switch. Will not upload configuration to
2226  * the switch. For that you need to call tb_switch_configure()
2227  * separately. The returned switch should be released by calling
2228  * tb_switch_put().
2229  *
2230  * Return: Pointer to the allocated switch or ERR_PTR() in case of
2231  * failure.
2232  */
2233 struct tb_switch *tb_switch_alloc(struct tb *tb, struct device *parent,
2234                                   u64 route)
2235 {
2236         struct tb_switch *sw;
2237         int upstream_port;
2238         int i, ret, depth;
2239
2240         /* Unlock the downstream port so we can access the switch below */
2241         if (route) {
2242                 struct tb_switch *parent_sw = tb_to_switch(parent);
2243                 struct tb_port *down;
2244
2245                 down = tb_port_at(route, parent_sw);
2246                 tb_port_unlock(down);
2247         }
2248
2249         depth = tb_route_length(route);
2250
2251         upstream_port = tb_cfg_get_upstream_port(tb->ctl, route);
2252         if (upstream_port < 0)
2253                 return ERR_PTR(upstream_port);
2254
2255         sw = kzalloc(sizeof(*sw), GFP_KERNEL);
2256         if (!sw)
2257                 return ERR_PTR(-ENOMEM);
2258
2259         sw->tb = tb;
2260         ret = tb_cfg_read(tb->ctl, &sw->config, route, 0, TB_CFG_SWITCH, 0, 5);
2261         if (ret)
2262                 goto err_free_sw_ports;
2263
2264         sw->generation = tb_switch_get_generation(sw);
2265
2266         tb_dbg(tb, "current switch config:\n");
2267         tb_dump_switch(tb, sw);
2268
2269         /* configure switch */
2270         sw->config.upstream_port_number = upstream_port;
2271         sw->config.depth = depth;
2272         sw->config.route_hi = upper_32_bits(route);
2273         sw->config.route_lo = lower_32_bits(route);
2274         sw->config.enabled = 0;
2275
2276         /* Make sure we do not exceed maximum topology limit */
2277         if (tb_switch_exceeds_max_depth(sw, depth)) {
2278                 ret = -EADDRNOTAVAIL;
2279                 goto err_free_sw_ports;
2280         }
2281
2282         /* initialize ports */
2283         sw->ports = kcalloc(sw->config.max_port_number + 1, sizeof(*sw->ports),
2284                                 GFP_KERNEL);
2285         if (!sw->ports) {
2286                 ret = -ENOMEM;
2287                 goto err_free_sw_ports;
2288         }
2289
2290         for (i = 0; i <= sw->config.max_port_number; i++) {
2291                 /* minimum setup for tb_find_cap and tb_drom_read to work */
2292                 sw->ports[i].sw = sw;
2293                 sw->ports[i].port = i;
2294
2295                 /* Control port does not need HopID allocation */
2296                 if (i) {
2297                         ida_init(&sw->ports[i].in_hopids);
2298                         ida_init(&sw->ports[i].out_hopids);
2299                 }
2300         }
2301
2302         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_PLUG_EVENTS);
2303         if (ret > 0)
2304                 sw->cap_plug_events = ret;
2305
2306         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_TIME2);
2307         if (ret > 0)
2308                 sw->cap_vsec_tmu = ret;
2309
2310         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_LINK_CONTROLLER);
2311         if (ret > 0)
2312                 sw->cap_lc = ret;
2313
2314         ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_CP_LP);
2315         if (ret > 0)
2316                 sw->cap_lp = ret;
2317
2318         /* Root switch is always authorized */
2319         if (!route)
2320                 sw->authorized = true;
2321
2322         device_initialize(&sw->dev);
2323         sw->dev.parent = parent;
2324         sw->dev.bus = &tb_bus_type;
2325         sw->dev.type = &tb_switch_type;
2326         sw->dev.groups = switch_groups;
2327         dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
2328
2329         return sw;
2330
2331 err_free_sw_ports:
2332         kfree(sw->ports);
2333         kfree(sw);
2334
2335         return ERR_PTR(ret);
2336 }
2337
2338 /**
2339  * tb_switch_alloc_safe_mode() - allocate a switch that is in safe mode
2340  * @tb: Pointer to the owning domain
2341  * @parent: Parent device for this switch
2342  * @route: Route string for this switch
2343  *
2344  * This creates a switch in safe mode. This means the switch pretty much
2345  * lacks all capabilities except DMA configuration port before it is
2346  * flashed with a valid NVM firmware.
2347  *
2348  * The returned switch must be released by calling tb_switch_put().
2349  *
2350  * Return: Pointer to the allocated switch or ERR_PTR() in case of failure
2351  */
2352 struct tb_switch *
2353 tb_switch_alloc_safe_mode(struct tb *tb, struct device *parent, u64 route)
2354 {
2355         struct tb_switch *sw;
2356
2357         sw = kzalloc(sizeof(*sw), GFP_KERNEL);
2358         if (!sw)
2359                 return ERR_PTR(-ENOMEM);
2360
2361         sw->tb = tb;
2362         sw->config.depth = tb_route_length(route);
2363         sw->config.route_hi = upper_32_bits(route);
2364         sw->config.route_lo = lower_32_bits(route);
2365         sw->safe_mode = true;
2366
2367         device_initialize(&sw->dev);
2368         sw->dev.parent = parent;
2369         sw->dev.bus = &tb_bus_type;
2370         sw->dev.type = &tb_switch_type;
2371         sw->dev.groups = switch_groups;
2372         dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
2373
2374         return sw;
2375 }
2376
2377 /**
2378  * tb_switch_configure() - Uploads configuration to the switch
2379  * @sw: Switch to configure
2380  *
2381  * Call this function before the switch is added to the system. It will
2382  * upload configuration to the switch and makes it available for the
2383  * connection manager to use. Can be called to the switch again after
2384  * resume from low power states to re-initialize it.
2385  *
2386  * Return: %0 in case of success and negative errno in case of failure
2387  */
2388 int tb_switch_configure(struct tb_switch *sw)
2389 {
2390         struct tb *tb = sw->tb;
2391         u64 route;
2392         int ret;
2393
2394         route = tb_route(sw);
2395
2396         tb_dbg(tb, "%s Switch at %#llx (depth: %d, up port: %d)\n",
2397                sw->config.enabled ? "restoring" : "initializing", route,
2398                tb_route_length(route), sw->config.upstream_port_number);
2399
2400         sw->config.enabled = 1;
2401
2402         if (tb_switch_is_usb4(sw)) {
2403                 /*
2404                  * For USB4 devices, we need to program the CM version
2405                  * accordingly so that it knows to expose all the
2406                  * additional capabilities.
2407                  */
2408                 sw->config.cmuv = USB4_VERSION_1_0;
2409
2410                 /* Enumerate the switch */
2411                 ret = tb_sw_write(sw, (u32 *)&sw->config + 1, TB_CFG_SWITCH,
2412                                   ROUTER_CS_1, 4);
2413                 if (ret)
2414                         return ret;
2415
2416                 ret = usb4_switch_setup(sw);
2417         } else {
2418                 if (sw->config.vendor_id != PCI_VENDOR_ID_INTEL)
2419                         tb_sw_warn(sw, "unknown switch vendor id %#x\n",
2420                                    sw->config.vendor_id);
2421
2422                 if (!sw->cap_plug_events) {
2423                         tb_sw_warn(sw, "cannot find TB_VSE_CAP_PLUG_EVENTS aborting\n");
2424                         return -ENODEV;
2425                 }
2426
2427                 /* Enumerate the switch */
2428                 ret = tb_sw_write(sw, (u32 *)&sw->config + 1, TB_CFG_SWITCH,
2429                                   ROUTER_CS_1, 3);
2430         }
2431         if (ret)
2432                 return ret;
2433
2434         return tb_plug_events_active(sw, true);
2435 }
2436
2437 static int tb_switch_set_uuid(struct tb_switch *sw)
2438 {
2439         bool uid = false;
2440         u32 uuid[4];
2441         int ret;
2442
2443         if (sw->uuid)
2444                 return 0;
2445
2446         if (tb_switch_is_usb4(sw)) {
2447                 ret = usb4_switch_read_uid(sw, &sw->uid);
2448                 if (ret)
2449                         return ret;
2450                 uid = true;
2451         } else {
2452                 /*
2453                  * The newer controllers include fused UUID as part of
2454                  * link controller specific registers
2455                  */
2456                 ret = tb_lc_read_uuid(sw, uuid);
2457                 if (ret) {
2458                         if (ret != -EINVAL)
2459                                 return ret;
2460                         uid = true;
2461                 }
2462         }
2463
2464         if (uid) {
2465                 /*
2466                  * ICM generates UUID based on UID and fills the upper
2467                  * two words with ones. This is not strictly following
2468                  * UUID format but we want to be compatible with it so
2469                  * we do the same here.
2470                  */
2471                 uuid[0] = sw->uid & 0xffffffff;
2472                 uuid[1] = (sw->uid >> 32) & 0xffffffff;
2473                 uuid[2] = 0xffffffff;
2474                 uuid[3] = 0xffffffff;
2475         }
2476
2477         sw->uuid = kmemdup(uuid, sizeof(uuid), GFP_KERNEL);
2478         if (!sw->uuid)
2479                 return -ENOMEM;
2480         return 0;
2481 }
2482
2483 static int tb_switch_add_dma_port(struct tb_switch *sw)
2484 {
2485         u32 status;
2486         int ret;
2487
2488         switch (sw->generation) {
2489         case 2:
2490                 /* Only root switch can be upgraded */
2491                 if (tb_route(sw))
2492                         return 0;
2493
2494                 fallthrough;
2495         case 3:
2496         case 4:
2497                 ret = tb_switch_set_uuid(sw);
2498                 if (ret)
2499                         return ret;
2500                 break;
2501
2502         default:
2503                 /*
2504                  * DMA port is the only thing available when the switch
2505                  * is in safe mode.
2506                  */
2507                 if (!sw->safe_mode)
2508                         return 0;
2509                 break;
2510         }
2511
2512         if (sw->no_nvm_upgrade)
2513                 return 0;
2514
2515         if (tb_switch_is_usb4(sw)) {
2516                 ret = usb4_switch_nvm_authenticate_status(sw, &status);
2517                 if (ret)
2518                         return ret;
2519
2520                 if (status) {
2521                         tb_sw_info(sw, "switch flash authentication failed\n");
2522                         nvm_set_auth_status(sw, status);
2523                 }
2524
2525                 return 0;
2526         }
2527
2528         /* Root switch DMA port requires running firmware */
2529         if (!tb_route(sw) && !tb_switch_is_icm(sw))
2530                 return 0;
2531
2532         sw->dma_port = dma_port_alloc(sw);
2533         if (!sw->dma_port)
2534                 return 0;
2535
2536         /*
2537          * If there is status already set then authentication failed
2538          * when the dma_port_flash_update_auth() returned. Power cycling
2539          * is not needed (it was done already) so only thing we do here
2540          * is to unblock runtime PM of the root port.
2541          */
2542         nvm_get_auth_status(sw, &status);
2543         if (status) {
2544                 if (!tb_route(sw))
2545                         nvm_authenticate_complete_dma_port(sw);
2546                 return 0;
2547         }
2548
2549         /*
2550          * Check status of the previous flash authentication. If there
2551          * is one we need to power cycle the switch in any case to make
2552          * it functional again.
2553          */
2554         ret = dma_port_flash_update_auth_status(sw->dma_port, &status);
2555         if (ret <= 0)
2556                 return ret;
2557
2558         /* Now we can allow root port to suspend again */
2559         if (!tb_route(sw))
2560                 nvm_authenticate_complete_dma_port(sw);
2561
2562         if (status) {
2563                 tb_sw_info(sw, "switch flash authentication failed\n");
2564                 nvm_set_auth_status(sw, status);
2565         }
2566
2567         tb_sw_info(sw, "power cycling the switch now\n");
2568         dma_port_power_cycle(sw->dma_port);
2569
2570         /*
2571          * We return error here which causes the switch adding failure.
2572          * It should appear back after power cycle is complete.
2573          */
2574         return -ESHUTDOWN;
2575 }
2576
2577 static void tb_switch_default_link_ports(struct tb_switch *sw)
2578 {
2579         int i;
2580
2581         for (i = 1; i <= sw->config.max_port_number; i++) {
2582                 struct tb_port *port = &sw->ports[i];
2583                 struct tb_port *subordinate;
2584
2585                 if (!tb_port_is_null(port))
2586                         continue;
2587
2588                 /* Check for the subordinate port */
2589                 if (i == sw->config.max_port_number ||
2590                     !tb_port_is_null(&sw->ports[i + 1]))
2591                         continue;
2592
2593                 /* Link them if not already done so (by DROM) */
2594                 subordinate = &sw->ports[i + 1];
2595                 if (!port->dual_link_port && !subordinate->dual_link_port) {
2596                         port->link_nr = 0;
2597                         port->dual_link_port = subordinate;
2598                         subordinate->link_nr = 1;
2599                         subordinate->dual_link_port = port;
2600
2601                         tb_sw_dbg(sw, "linked ports %d <-> %d\n",
2602                                   port->port, subordinate->port);
2603                 }
2604         }
2605 }
2606
2607 static bool tb_switch_lane_bonding_possible(struct tb_switch *sw)
2608 {
2609         const struct tb_port *up = tb_upstream_port(sw);
2610
2611         if (!up->dual_link_port || !up->dual_link_port->remote)
2612                 return false;
2613
2614         if (tb_switch_is_usb4(sw))
2615                 return usb4_switch_lane_bonding_possible(sw);
2616         return tb_lc_lane_bonding_possible(sw);
2617 }
2618
2619 static int tb_switch_update_link_attributes(struct tb_switch *sw)
2620 {
2621         struct tb_port *up;
2622         bool change = false;
2623         int ret;
2624
2625         if (!tb_route(sw) || tb_switch_is_icm(sw))
2626                 return 0;
2627
2628         up = tb_upstream_port(sw);
2629
2630         ret = tb_port_get_link_speed(up);
2631         if (ret < 0)
2632                 return ret;
2633         if (sw->link_speed != ret)
2634                 change = true;
2635         sw->link_speed = ret;
2636
2637         ret = tb_port_get_link_width(up);
2638         if (ret < 0)
2639                 return ret;
2640         if (sw->link_width != ret)
2641                 change = true;
2642         sw->link_width = ret;
2643
2644         /* Notify userspace that there is possible link attribute change */
2645         if (device_is_registered(&sw->dev) && change)
2646                 kobject_uevent(&sw->dev.kobj, KOBJ_CHANGE);
2647
2648         return 0;
2649 }
2650
2651 /**
2652  * tb_switch_lane_bonding_enable() - Enable lane bonding
2653  * @sw: Switch to enable lane bonding
2654  *
2655  * Connection manager can call this function to enable lane bonding of a
2656  * switch. If conditions are correct and both switches support the feature,
2657  * lanes are bonded. It is safe to call this to any switch.
2658  */
2659 int tb_switch_lane_bonding_enable(struct tb_switch *sw)
2660 {
2661         struct tb_switch *parent = tb_to_switch(sw->dev.parent);
2662         struct tb_port *up, *down;
2663         u64 route = tb_route(sw);
2664         int ret;
2665
2666         if (!route)
2667                 return 0;
2668
2669         if (!tb_switch_lane_bonding_possible(sw))
2670                 return 0;
2671
2672         up = tb_upstream_port(sw);
2673         down = tb_port_at(route, parent);
2674
2675         if (!tb_port_is_width_supported(up, 2) ||
2676             !tb_port_is_width_supported(down, 2))
2677                 return 0;
2678
2679         ret = tb_port_lane_bonding_enable(up);
2680         if (ret) {
2681                 tb_port_warn(up, "failed to enable lane bonding\n");
2682                 return ret;
2683         }
2684
2685         ret = tb_port_lane_bonding_enable(down);
2686         if (ret) {
2687                 tb_port_warn(down, "failed to enable lane bonding\n");
2688                 tb_port_lane_bonding_disable(up);
2689                 return ret;
2690         }
2691
2692         ret = tb_port_wait_for_link_width(down, 2, 100);
2693         if (ret) {
2694                 tb_port_warn(down, "timeout enabling lane bonding\n");
2695                 return ret;
2696         }
2697
2698         tb_port_update_credits(down);
2699         tb_port_update_credits(up);
2700         tb_switch_update_link_attributes(sw);
2701
2702         tb_sw_dbg(sw, "lane bonding enabled\n");
2703         return ret;
2704 }
2705
2706 /**
2707  * tb_switch_lane_bonding_disable() - Disable lane bonding
2708  * @sw: Switch whose lane bonding to disable
2709  *
2710  * Disables lane bonding between @sw and parent. This can be called even
2711  * if lanes were not bonded originally.
2712  */
2713 void tb_switch_lane_bonding_disable(struct tb_switch *sw)
2714 {
2715         struct tb_switch *parent = tb_to_switch(sw->dev.parent);
2716         struct tb_port *up, *down;
2717
2718         if (!tb_route(sw))
2719                 return;
2720
2721         up = tb_upstream_port(sw);
2722         if (!up->bonded)
2723                 return;
2724
2725         down = tb_port_at(tb_route(sw), parent);
2726
2727         tb_port_lane_bonding_disable(up);
2728         tb_port_lane_bonding_disable(down);
2729
2730         /*
2731          * It is fine if we get other errors as the router might have
2732          * been unplugged.
2733          */
2734         if (tb_port_wait_for_link_width(down, 1, 100) == -ETIMEDOUT)
2735                 tb_sw_warn(sw, "timeout disabling lane bonding\n");
2736
2737         tb_port_update_credits(down);
2738         tb_port_update_credits(up);
2739         tb_switch_update_link_attributes(sw);
2740
2741         tb_sw_dbg(sw, "lane bonding disabled\n");
2742 }
2743
2744 /**
2745  * tb_switch_configure_link() - Set link configured
2746  * @sw: Switch whose link is configured
2747  *
2748  * Sets the link upstream from @sw configured (from both ends) so that
2749  * it will not be disconnected when the domain exits sleep. Can be
2750  * called for any switch.
2751  *
2752  * It is recommended that this is called after lane bonding is enabled.
2753  *
2754  * Returns %0 on success and negative errno in case of error.
2755  */
2756 int tb_switch_configure_link(struct tb_switch *sw)
2757 {
2758         struct tb_port *up, *down;
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         if (tb_switch_is_usb4(up->sw))
2766                 ret = usb4_port_configure(up);
2767         else
2768                 ret = tb_lc_configure_port(up);
2769         if (ret)
2770                 return ret;
2771
2772         down = up->remote;
2773         if (tb_switch_is_usb4(down->sw))
2774                 return usb4_port_configure(down);
2775         return tb_lc_configure_port(down);
2776 }
2777
2778 /**
2779  * tb_switch_unconfigure_link() - Unconfigure link
2780  * @sw: Switch whose link is unconfigured
2781  *
2782  * Sets the link unconfigured so the @sw will be disconnected if the
2783  * domain exists sleep.
2784  */
2785 void tb_switch_unconfigure_link(struct tb_switch *sw)
2786 {
2787         struct tb_port *up, *down;
2788
2789         if (sw->is_unplugged)
2790                 return;
2791         if (!tb_route(sw) || tb_switch_is_icm(sw))
2792                 return;
2793
2794         up = tb_upstream_port(sw);
2795         if (tb_switch_is_usb4(up->sw))
2796                 usb4_port_unconfigure(up);
2797         else
2798                 tb_lc_unconfigure_port(up);
2799
2800         down = up->remote;
2801         if (tb_switch_is_usb4(down->sw))
2802                 usb4_port_unconfigure(down);
2803         else
2804                 tb_lc_unconfigure_port(down);
2805 }
2806
2807 static void tb_switch_credits_init(struct tb_switch *sw)
2808 {
2809         if (tb_switch_is_icm(sw))
2810                 return;
2811         if (!tb_switch_is_usb4(sw))
2812                 return;
2813         if (usb4_switch_credits_init(sw))
2814                 tb_sw_info(sw, "failed to determine preferred buffer allocation, using defaults\n");
2815 }
2816
2817 /**
2818  * tb_switch_add() - Add a switch to the domain
2819  * @sw: Switch to add
2820  *
2821  * This is the last step in adding switch to the domain. It will read
2822  * identification information from DROM and initializes ports so that
2823  * they can be used to connect other switches. The switch will be
2824  * exposed to the userspace when this function successfully returns. To
2825  * remove and release the switch, call tb_switch_remove().
2826  *
2827  * Return: %0 in case of success and negative errno in case of failure
2828  */
2829 int tb_switch_add(struct tb_switch *sw)
2830 {
2831         int i, ret;
2832
2833         /*
2834          * Initialize DMA control port now before we read DROM. Recent
2835          * host controllers have more complete DROM on NVM that includes
2836          * vendor and model identification strings which we then expose
2837          * to the userspace. NVM can be accessed through DMA
2838          * configuration based mailbox.
2839          */
2840         ret = tb_switch_add_dma_port(sw);
2841         if (ret) {
2842                 dev_err(&sw->dev, "failed to add DMA port\n");
2843                 return ret;
2844         }
2845
2846         if (!sw->safe_mode) {
2847                 tb_switch_credits_init(sw);
2848
2849                 /* read drom */
2850                 ret = tb_drom_read(sw);
2851                 if (ret)
2852                         dev_warn(&sw->dev, "reading DROM failed: %d\n", ret);
2853                 tb_sw_dbg(sw, "uid: %#llx\n", sw->uid);
2854
2855                 tb_check_quirks(sw);
2856
2857                 ret = tb_switch_set_uuid(sw);
2858                 if (ret) {
2859                         dev_err(&sw->dev, "failed to set UUID\n");
2860                         return ret;
2861                 }
2862
2863                 for (i = 0; i <= sw->config.max_port_number; i++) {
2864                         if (sw->ports[i].disabled) {
2865                                 tb_port_dbg(&sw->ports[i], "disabled by eeprom\n");
2866                                 continue;
2867                         }
2868                         ret = tb_init_port(&sw->ports[i]);
2869                         if (ret) {
2870                                 dev_err(&sw->dev, "failed to initialize port %d\n", i);
2871                                 return ret;
2872                         }
2873                 }
2874
2875                 tb_switch_default_link_ports(sw);
2876
2877                 ret = tb_switch_update_link_attributes(sw);
2878                 if (ret)
2879                         return ret;
2880
2881                 ret = tb_switch_tmu_init(sw);
2882                 if (ret)
2883                         return ret;
2884         }
2885
2886         ret = device_add(&sw->dev);
2887         if (ret) {
2888                 dev_err(&sw->dev, "failed to add device: %d\n", ret);
2889                 return ret;
2890         }
2891
2892         if (tb_route(sw)) {
2893                 dev_info(&sw->dev, "new device found, vendor=%#x device=%#x\n",
2894                          sw->vendor, sw->device);
2895                 if (sw->vendor_name && sw->device_name)
2896                         dev_info(&sw->dev, "%s %s\n", sw->vendor_name,
2897                                  sw->device_name);
2898         }
2899
2900         ret = usb4_switch_add_ports(sw);
2901         if (ret) {
2902                 dev_err(&sw->dev, "failed to add USB4 ports\n");
2903                 goto err_del;
2904         }
2905
2906         ret = tb_switch_nvm_add(sw);
2907         if (ret) {
2908                 dev_err(&sw->dev, "failed to add NVM devices\n");
2909                 goto err_ports;
2910         }
2911
2912         /*
2913          * Thunderbolt routers do not generate wakeups themselves but
2914          * they forward wakeups from tunneled protocols, so enable it
2915          * here.
2916          */
2917         device_init_wakeup(&sw->dev, true);
2918
2919         pm_runtime_set_active(&sw->dev);
2920         if (sw->rpm) {
2921                 pm_runtime_set_autosuspend_delay(&sw->dev, TB_AUTOSUSPEND_DELAY);
2922                 pm_runtime_use_autosuspend(&sw->dev);
2923                 pm_runtime_mark_last_busy(&sw->dev);
2924                 pm_runtime_enable(&sw->dev);
2925                 pm_request_autosuspend(&sw->dev);
2926         }
2927
2928         tb_switch_debugfs_init(sw);
2929         return 0;
2930
2931 err_ports:
2932         usb4_switch_remove_ports(sw);
2933 err_del:
2934         device_del(&sw->dev);
2935
2936         return ret;
2937 }
2938
2939 /**
2940  * tb_switch_remove() - Remove and release a switch
2941  * @sw: Switch to remove
2942  *
2943  * This will remove the switch from the domain and release it after last
2944  * reference count drops to zero. If there are switches connected below
2945  * this switch, they will be removed as well.
2946  */
2947 void tb_switch_remove(struct tb_switch *sw)
2948 {
2949         struct tb_port *port;
2950
2951         tb_switch_debugfs_remove(sw);
2952
2953         if (sw->rpm) {
2954                 pm_runtime_get_sync(&sw->dev);
2955                 pm_runtime_disable(&sw->dev);
2956         }
2957
2958         /* port 0 is the switch itself and never has a remote */
2959         tb_switch_for_each_port(sw, port) {
2960                 if (tb_port_has_remote(port)) {
2961                         tb_switch_remove(port->remote->sw);
2962                         port->remote = NULL;
2963                 } else if (port->xdomain) {
2964                         tb_xdomain_remove(port->xdomain);
2965                         port->xdomain = NULL;
2966                 }
2967
2968                 /* Remove any downstream retimers */
2969                 tb_retimer_remove_all(port);
2970         }
2971
2972         if (!sw->is_unplugged)
2973                 tb_plug_events_active(sw, false);
2974
2975         tb_switch_nvm_remove(sw);
2976         usb4_switch_remove_ports(sw);
2977
2978         if (tb_route(sw))
2979                 dev_info(&sw->dev, "device disconnected\n");
2980         device_unregister(&sw->dev);
2981 }
2982
2983 /**
2984  * tb_sw_set_unplugged() - set is_unplugged on switch and downstream switches
2985  * @sw: Router to mark unplugged
2986  */
2987 void tb_sw_set_unplugged(struct tb_switch *sw)
2988 {
2989         struct tb_port *port;
2990
2991         if (sw == sw->tb->root_switch) {
2992                 tb_sw_WARN(sw, "cannot unplug root switch\n");
2993                 return;
2994         }
2995         if (sw->is_unplugged) {
2996                 tb_sw_WARN(sw, "is_unplugged already set\n");
2997                 return;
2998         }
2999         sw->is_unplugged = true;
3000         tb_switch_for_each_port(sw, port) {
3001                 if (tb_port_has_remote(port))
3002                         tb_sw_set_unplugged(port->remote->sw);
3003                 else if (port->xdomain)
3004                         port->xdomain->is_unplugged = true;
3005         }
3006 }
3007
3008 static int tb_switch_set_wake(struct tb_switch *sw, unsigned int flags)
3009 {
3010         if (flags)
3011                 tb_sw_dbg(sw, "enabling wakeup: %#x\n", flags);
3012         else
3013                 tb_sw_dbg(sw, "disabling wakeup\n");
3014
3015         if (tb_switch_is_usb4(sw))
3016                 return usb4_switch_set_wake(sw, flags);
3017         return tb_lc_set_wake(sw, flags);
3018 }
3019
3020 int tb_switch_resume(struct tb_switch *sw)
3021 {
3022         struct tb_port *port;
3023         int err;
3024
3025         tb_sw_dbg(sw, "resuming switch\n");
3026
3027         /*
3028          * Check for UID of the connected switches except for root
3029          * switch which we assume cannot be removed.
3030          */
3031         if (tb_route(sw)) {
3032                 u64 uid;
3033
3034                 /*
3035                  * Check first that we can still read the switch config
3036                  * space. It may be that there is now another domain
3037                  * connected.
3038                  */
3039                 err = tb_cfg_get_upstream_port(sw->tb->ctl, tb_route(sw));
3040                 if (err < 0) {
3041                         tb_sw_info(sw, "switch not present anymore\n");
3042                         return err;
3043                 }
3044
3045                 /* We don't have any way to confirm this was the same device */
3046                 if (!sw->uid)
3047                         return -ENODEV;
3048
3049                 if (tb_switch_is_usb4(sw))
3050                         err = usb4_switch_read_uid(sw, &uid);
3051                 else
3052                         err = tb_drom_read_uid_only(sw, &uid);
3053                 if (err) {
3054                         tb_sw_warn(sw, "uid read failed\n");
3055                         return err;
3056                 }
3057                 if (sw->uid != uid) {
3058                         tb_sw_info(sw,
3059                                 "changed while suspended (uid %#llx -> %#llx)\n",
3060                                 sw->uid, uid);
3061                         return -ENODEV;
3062                 }
3063         }
3064
3065         err = tb_switch_configure(sw);
3066         if (err)
3067                 return err;
3068
3069         /* Disable wakes */
3070         tb_switch_set_wake(sw, 0);
3071
3072         err = tb_switch_tmu_init(sw);
3073         if (err)
3074                 return err;
3075
3076         /* check for surviving downstream switches */
3077         tb_switch_for_each_port(sw, port) {
3078                 if (!tb_port_is_null(port))
3079                         continue;
3080
3081                 if (!tb_port_resume(port))
3082                         continue;
3083
3084                 if (tb_wait_for_port(port, true) <= 0) {
3085                         tb_port_warn(port,
3086                                      "lost during suspend, disconnecting\n");
3087                         if (tb_port_has_remote(port))
3088                                 tb_sw_set_unplugged(port->remote->sw);
3089                         else if (port->xdomain)
3090                                 port->xdomain->is_unplugged = true;
3091                 } else {
3092                         /*
3093                          * Always unlock the port so the downstream
3094                          * switch/domain is accessible.
3095                          */
3096                         if (tb_port_unlock(port))
3097                                 tb_port_warn(port, "failed to unlock port\n");
3098                         if (port->remote && tb_switch_resume(port->remote->sw)) {
3099                                 tb_port_warn(port,
3100                                              "lost during suspend, disconnecting\n");
3101                                 tb_sw_set_unplugged(port->remote->sw);
3102                         }
3103                 }
3104         }
3105         return 0;
3106 }
3107
3108 /**
3109  * tb_switch_suspend() - Put a switch to sleep
3110  * @sw: Switch to suspend
3111  * @runtime: Is this runtime suspend or system sleep
3112  *
3113  * Suspends router and all its children. Enables wakes according to
3114  * value of @runtime and then sets sleep bit for the router. If @sw is
3115  * host router the domain is ready to go to sleep once this function
3116  * returns.
3117  */
3118 void tb_switch_suspend(struct tb_switch *sw, bool runtime)
3119 {
3120         unsigned int flags = 0;
3121         struct tb_port *port;
3122         int err;
3123
3124         tb_sw_dbg(sw, "suspending switch\n");
3125
3126         /*
3127          * Actually only needed for Titan Ridge but for simplicity can be
3128          * done for USB4 device too as CLx is re-enabled at resume.
3129          */
3130         if (tb_switch_disable_clx(sw, TB_CL0S))
3131                 tb_sw_warn(sw, "failed to disable CLx on upstream port\n");
3132
3133         err = tb_plug_events_active(sw, false);
3134         if (err)
3135                 return;
3136
3137         tb_switch_for_each_port(sw, port) {
3138                 if (tb_port_has_remote(port))
3139                         tb_switch_suspend(port->remote->sw, runtime);
3140         }
3141
3142         if (runtime) {
3143                 /* Trigger wake when something is plugged in/out */
3144                 flags |= TB_WAKE_ON_CONNECT | TB_WAKE_ON_DISCONNECT;
3145                 flags |= TB_WAKE_ON_USB4;
3146                 flags |= TB_WAKE_ON_USB3 | TB_WAKE_ON_PCIE | TB_WAKE_ON_DP;
3147         } else if (device_may_wakeup(&sw->dev)) {
3148                 flags |= TB_WAKE_ON_USB4 | TB_WAKE_ON_USB3 | TB_WAKE_ON_PCIE;
3149         }
3150
3151         tb_switch_set_wake(sw, flags);
3152
3153         if (tb_switch_is_usb4(sw))
3154                 usb4_switch_set_sleep(sw);
3155         else
3156                 tb_lc_set_sleep(sw);
3157 }
3158
3159 /**
3160  * tb_switch_query_dp_resource() - Query availability of DP resource
3161  * @sw: Switch whose DP resource is queried
3162  * @in: DP IN port
3163  *
3164  * Queries availability of DP resource for DP tunneling using switch
3165  * specific means. Returns %true if resource is available.
3166  */
3167 bool tb_switch_query_dp_resource(struct tb_switch *sw, struct tb_port *in)
3168 {
3169         if (tb_switch_is_usb4(sw))
3170                 return usb4_switch_query_dp_resource(sw, in);
3171         return tb_lc_dp_sink_query(sw, in);
3172 }
3173
3174 /**
3175  * tb_switch_alloc_dp_resource() - Allocate available DP resource
3176  * @sw: Switch whose DP resource is allocated
3177  * @in: DP IN port
3178  *
3179  * Allocates DP resource for DP tunneling. The resource must be
3180  * available for this to succeed (see tb_switch_query_dp_resource()).
3181  * Returns %0 in success and negative errno otherwise.
3182  */
3183 int tb_switch_alloc_dp_resource(struct tb_switch *sw, struct tb_port *in)
3184 {
3185         int ret;
3186
3187         if (tb_switch_is_usb4(sw))
3188                 ret = usb4_switch_alloc_dp_resource(sw, in);
3189         else
3190                 ret = tb_lc_dp_sink_alloc(sw, in);
3191
3192         if (ret)
3193                 tb_sw_warn(sw, "failed to allocate DP resource for port %d\n",
3194                            in->port);
3195         else
3196                 tb_sw_dbg(sw, "allocated DP resource for port %d\n", in->port);
3197
3198         return ret;
3199 }
3200
3201 /**
3202  * tb_switch_dealloc_dp_resource() - De-allocate DP resource
3203  * @sw: Switch whose DP resource is de-allocated
3204  * @in: DP IN port
3205  *
3206  * De-allocates DP resource that was previously allocated for DP
3207  * tunneling.
3208  */
3209 void tb_switch_dealloc_dp_resource(struct tb_switch *sw, struct tb_port *in)
3210 {
3211         int ret;
3212
3213         if (tb_switch_is_usb4(sw))
3214                 ret = usb4_switch_dealloc_dp_resource(sw, in);
3215         else
3216                 ret = tb_lc_dp_sink_dealloc(sw, in);
3217
3218         if (ret)
3219                 tb_sw_warn(sw, "failed to de-allocate DP resource for port %d\n",
3220                            in->port);
3221         else
3222                 tb_sw_dbg(sw, "released DP resource for port %d\n", in->port);
3223 }
3224
3225 struct tb_sw_lookup {
3226         struct tb *tb;
3227         u8 link;
3228         u8 depth;
3229         const uuid_t *uuid;
3230         u64 route;
3231 };
3232
3233 static int tb_switch_match(struct device *dev, const void *data)
3234 {
3235         struct tb_switch *sw = tb_to_switch(dev);
3236         const struct tb_sw_lookup *lookup = data;
3237
3238         if (!sw)
3239                 return 0;
3240         if (sw->tb != lookup->tb)
3241                 return 0;
3242
3243         if (lookup->uuid)
3244                 return !memcmp(sw->uuid, lookup->uuid, sizeof(*lookup->uuid));
3245
3246         if (lookup->route) {
3247                 return sw->config.route_lo == lower_32_bits(lookup->route) &&
3248                        sw->config.route_hi == upper_32_bits(lookup->route);
3249         }
3250
3251         /* Root switch is matched only by depth */
3252         if (!lookup->depth)
3253                 return !sw->depth;
3254
3255         return sw->link == lookup->link && sw->depth == lookup->depth;
3256 }
3257
3258 /**
3259  * tb_switch_find_by_link_depth() - Find switch by link and depth
3260  * @tb: Domain the switch belongs
3261  * @link: Link number the switch is connected
3262  * @depth: Depth of the switch in link
3263  *
3264  * Returned switch has reference count increased so the caller needs to
3265  * call tb_switch_put() when done with the switch.
3266  */
3267 struct tb_switch *tb_switch_find_by_link_depth(struct tb *tb, u8 link, u8 depth)
3268 {
3269         struct tb_sw_lookup lookup;
3270         struct device *dev;
3271
3272         memset(&lookup, 0, sizeof(lookup));
3273         lookup.tb = tb;
3274         lookup.link = link;
3275         lookup.depth = depth;
3276
3277         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
3278         if (dev)
3279                 return tb_to_switch(dev);
3280
3281         return NULL;
3282 }
3283
3284 /**
3285  * tb_switch_find_by_uuid() - Find switch by UUID
3286  * @tb: Domain the switch belongs
3287  * @uuid: UUID to look for
3288  *
3289  * Returned switch has reference count increased so the caller needs to
3290  * call tb_switch_put() when done with the switch.
3291  */
3292 struct tb_switch *tb_switch_find_by_uuid(struct tb *tb, const uuid_t *uuid)
3293 {
3294         struct tb_sw_lookup lookup;
3295         struct device *dev;
3296
3297         memset(&lookup, 0, sizeof(lookup));
3298         lookup.tb = tb;
3299         lookup.uuid = uuid;
3300
3301         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
3302         if (dev)
3303                 return tb_to_switch(dev);
3304
3305         return NULL;
3306 }
3307
3308 /**
3309  * tb_switch_find_by_route() - Find switch by route string
3310  * @tb: Domain the switch belongs
3311  * @route: Route string to look for
3312  *
3313  * Returned switch has reference count increased so the caller needs to
3314  * call tb_switch_put() when done with the switch.
3315  */
3316 struct tb_switch *tb_switch_find_by_route(struct tb *tb, u64 route)
3317 {
3318         struct tb_sw_lookup lookup;
3319         struct device *dev;
3320
3321         if (!route)
3322                 return tb_switch_get(tb->root_switch);
3323
3324         memset(&lookup, 0, sizeof(lookup));
3325         lookup.tb = tb;
3326         lookup.route = route;
3327
3328         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
3329         if (dev)
3330                 return tb_to_switch(dev);
3331
3332         return NULL;
3333 }
3334
3335 /**
3336  * tb_switch_find_port() - return the first port of @type on @sw or NULL
3337  * @sw: Switch to find the port from
3338  * @type: Port type to look for
3339  */
3340 struct tb_port *tb_switch_find_port(struct tb_switch *sw,
3341                                     enum tb_port_type type)
3342 {
3343         struct tb_port *port;
3344
3345         tb_switch_for_each_port(sw, port) {
3346                 if (port->config.type == type)
3347                         return port;
3348         }
3349
3350         return NULL;
3351 }
3352
3353 static int __tb_port_pm_secondary_set(struct tb_port *port, bool secondary)
3354 {
3355         u32 phy;
3356         int ret;
3357
3358         ret = tb_port_read(port, &phy, TB_CFG_PORT,
3359                            port->cap_phy + LANE_ADP_CS_1, 1);
3360         if (ret)
3361                 return ret;
3362
3363         if (secondary)
3364                 phy |= LANE_ADP_CS_1_PMS;
3365         else
3366                 phy &= ~LANE_ADP_CS_1_PMS;
3367
3368         return tb_port_write(port, &phy, TB_CFG_PORT,
3369                              port->cap_phy + LANE_ADP_CS_1, 1);
3370 }
3371
3372 static int tb_port_pm_secondary_enable(struct tb_port *port)
3373 {
3374         return __tb_port_pm_secondary_set(port, true);
3375 }
3376
3377 static int tb_port_pm_secondary_disable(struct tb_port *port)
3378 {
3379         return __tb_port_pm_secondary_set(port, false);
3380 }
3381
3382 static int tb_switch_pm_secondary_resolve(struct tb_switch *sw)
3383 {
3384         struct tb_switch *parent = tb_switch_parent(sw);
3385         struct tb_port *up, *down;
3386         int ret;
3387
3388         if (!tb_route(sw))
3389                 return 0;
3390
3391         up = tb_upstream_port(sw);
3392         down = tb_port_at(tb_route(sw), parent);
3393         ret = tb_port_pm_secondary_enable(up);
3394         if (ret)
3395                 return ret;
3396
3397         return tb_port_pm_secondary_disable(down);
3398 }
3399
3400 /* Called for USB4 or Titan Ridge routers only */
3401 static bool tb_port_clx_supported(struct tb_port *port, enum tb_clx clx)
3402 {
3403         u32 mask, val;
3404         bool ret;
3405
3406         /* Don't enable CLx in case of two single-lane links */
3407         if (!port->bonded && port->dual_link_port)
3408                 return false;
3409
3410         /* Don't enable CLx in case of inter-domain link */
3411         if (port->xdomain)
3412                 return false;
3413
3414         if (tb_switch_is_usb4(port->sw)) {
3415                 if (!usb4_port_clx_supported(port))
3416                         return false;
3417         } else if (!tb_lc_is_clx_supported(port)) {
3418                 return false;
3419         }
3420
3421         switch (clx) {
3422         case TB_CL0S:
3423                 /* CL0s support requires also CL1 support */
3424                 mask = LANE_ADP_CS_0_CL0S_SUPPORT | LANE_ADP_CS_0_CL1_SUPPORT;
3425                 break;
3426
3427         /* For now we support only CL0s. Not CL1, CL2 */
3428         case TB_CL1:
3429         case TB_CL2:
3430         default:
3431                 return false;
3432         }
3433
3434         ret = tb_port_read(port, &val, TB_CFG_PORT,
3435                            port->cap_phy + LANE_ADP_CS_0, 1);
3436         if (ret)
3437                 return false;
3438
3439         return !!(val & mask);
3440 }
3441
3442 static inline bool tb_port_cl0s_supported(struct tb_port *port)
3443 {
3444         return tb_port_clx_supported(port, TB_CL0S);
3445 }
3446
3447 static int __tb_port_cl0s_set(struct tb_port *port, bool enable)
3448 {
3449         u32 phy, mask;
3450         int ret;
3451
3452         /* To enable CL0s also required to enable CL1 */
3453         mask = LANE_ADP_CS_1_CL0S_ENABLE | LANE_ADP_CS_1_CL1_ENABLE;
3454         ret = tb_port_read(port, &phy, TB_CFG_PORT,
3455                            port->cap_phy + LANE_ADP_CS_1, 1);
3456         if (ret)
3457                 return ret;
3458
3459         if (enable)
3460                 phy |= mask;
3461         else
3462                 phy &= ~mask;
3463
3464         return tb_port_write(port, &phy, TB_CFG_PORT,
3465                              port->cap_phy + LANE_ADP_CS_1, 1);
3466 }
3467
3468 static int tb_port_cl0s_disable(struct tb_port *port)
3469 {
3470         return __tb_port_cl0s_set(port, false);
3471 }
3472
3473 static int tb_port_cl0s_enable(struct tb_port *port)
3474 {
3475         return __tb_port_cl0s_set(port, true);
3476 }
3477
3478 static int tb_switch_enable_cl0s(struct tb_switch *sw)
3479 {
3480         struct tb_switch *parent = tb_switch_parent(sw);
3481         bool up_cl0s_support, down_cl0s_support;
3482         struct tb_port *up, *down;
3483         int ret;
3484
3485         if (!tb_switch_is_clx_supported(sw))
3486                 return 0;
3487
3488         /*
3489          * Enable CLx for host router's downstream port as part of the
3490          * downstream router enabling procedure.
3491          */
3492         if (!tb_route(sw))
3493                 return 0;
3494
3495         /* Enable CLx only for first hop router (depth = 1) */
3496         if (tb_route(parent))
3497                 return 0;
3498
3499         ret = tb_switch_pm_secondary_resolve(sw);
3500         if (ret)
3501                 return ret;
3502
3503         up = tb_upstream_port(sw);
3504         down = tb_port_at(tb_route(sw), parent);
3505
3506         up_cl0s_support = tb_port_cl0s_supported(up);
3507         down_cl0s_support = tb_port_cl0s_supported(down);
3508
3509         tb_port_dbg(up, "CL0s %ssupported\n",
3510                     up_cl0s_support ? "" : "not ");
3511         tb_port_dbg(down, "CL0s %ssupported\n",
3512                     down_cl0s_support ? "" : "not ");
3513
3514         if (!up_cl0s_support || !down_cl0s_support)
3515                 return -EOPNOTSUPP;
3516
3517         ret = tb_port_cl0s_enable(up);
3518         if (ret)
3519                 return ret;
3520
3521         ret = tb_port_cl0s_enable(down);
3522         if (ret) {
3523                 tb_port_cl0s_disable(up);
3524                 return ret;
3525         }
3526
3527         ret = tb_switch_mask_clx_objections(sw);
3528         if (ret) {
3529                 tb_port_cl0s_disable(up);
3530                 tb_port_cl0s_disable(down);
3531                 return ret;
3532         }
3533
3534         sw->clx = TB_CL0S;
3535
3536         tb_port_dbg(up, "CL0s enabled\n");
3537         return 0;
3538 }
3539
3540 /**
3541  * tb_switch_enable_clx() - Enable CLx on upstream port of specified router
3542  * @sw: Router to enable CLx for
3543  * @clx: The CLx state to enable
3544  *
3545  * Enable CLx state only for first hop router. That is the most common
3546  * use-case, that is intended for better thermal management, and so helps
3547  * to improve performance. CLx is enabled only if both sides of the link
3548  * support CLx, and if both sides of the link are not configured as two
3549  * single lane links and only if the link is not inter-domain link. The
3550  * complete set of conditions is descibed in CM Guide 1.0 section 8.1.
3551  *
3552  * Return: Returns 0 on success or an error code on failure.
3553  */
3554 int tb_switch_enable_clx(struct tb_switch *sw, enum tb_clx clx)
3555 {
3556         struct tb_switch *root_sw = sw->tb->root_switch;
3557
3558         if (!clx_enabled)
3559                 return 0;
3560
3561         /*
3562          * CLx is not enabled and validated on Intel USB4 platforms before
3563          * Alder Lake.
3564          */
3565         if (root_sw->generation < 4 || tb_switch_is_tiger_lake(root_sw))
3566                 return 0;
3567
3568         switch (clx) {
3569         case TB_CL0S:
3570                 return tb_switch_enable_cl0s(sw);
3571
3572         default:
3573                 return -EOPNOTSUPP;
3574         }
3575 }
3576
3577 static int tb_switch_disable_cl0s(struct tb_switch *sw)
3578 {
3579         struct tb_switch *parent = tb_switch_parent(sw);
3580         struct tb_port *up, *down;
3581         int ret;
3582
3583         if (!tb_switch_is_clx_supported(sw))
3584                 return 0;
3585
3586         /*
3587          * Disable CLx for host router's downstream port as part of the
3588          * downstream router enabling procedure.
3589          */
3590         if (!tb_route(sw))
3591                 return 0;
3592
3593         /* Disable CLx only for first hop router (depth = 1) */
3594         if (tb_route(parent))
3595                 return 0;
3596
3597         up = tb_upstream_port(sw);
3598         down = tb_port_at(tb_route(sw), parent);
3599         ret = tb_port_cl0s_disable(up);
3600         if (ret)
3601                 return ret;
3602
3603         ret = tb_port_cl0s_disable(down);
3604         if (ret)
3605                 return ret;
3606
3607         sw->clx = TB_CLX_DISABLE;
3608
3609         tb_port_dbg(up, "CL0s disabled\n");
3610         return 0;
3611 }
3612
3613 /**
3614  * tb_switch_disable_clx() - Disable CLx on upstream port of specified router
3615  * @sw: Router to disable CLx for
3616  * @clx: The CLx state to disable
3617  *
3618  * Return: Returns 0 on success or an error code on failure.
3619  */
3620 int tb_switch_disable_clx(struct tb_switch *sw, enum tb_clx clx)
3621 {
3622         if (!clx_enabled)
3623                 return 0;
3624
3625         switch (clx) {
3626         case TB_CL0S:
3627                 return tb_switch_disable_cl0s(sw);
3628
3629         default:
3630                 return -EOPNOTSUPP;
3631         }
3632 }
3633
3634 /**
3635  * tb_switch_mask_clx_objections() - Mask CLx objections for a router
3636  * @sw: Router to mask objections for
3637  *
3638  * Mask the objections coming from the second depth routers in order to
3639  * stop these objections from interfering with the CLx states of the first
3640  * depth link.
3641  */
3642 int tb_switch_mask_clx_objections(struct tb_switch *sw)
3643 {
3644         int up_port = sw->config.upstream_port_number;
3645         u32 offset, val[2], mask_obj, unmask_obj;
3646         int ret, i;
3647
3648         /* Only Titan Ridge of pre-USB4 devices support CLx states */
3649         if (!tb_switch_is_titan_ridge(sw))
3650                 return 0;
3651
3652         if (!tb_route(sw))
3653                 return 0;
3654
3655         /*
3656          * In Titan Ridge there are only 2 dual-lane Thunderbolt ports:
3657          * Port A consists of lane adapters 1,2 and
3658          * Port B consists of lane adapters 3,4
3659          * If upstream port is A, (lanes are 1,2), we mask objections from
3660          * port B (lanes 3,4) and unmask objections from Port A and vice-versa.
3661          */
3662         if (up_port == 1) {
3663                 mask_obj = TB_LOW_PWR_C0_PORT_B_MASK;
3664                 unmask_obj = TB_LOW_PWR_C1_PORT_A_MASK;
3665                 offset = TB_LOW_PWR_C1_CL1;
3666         } else {
3667                 mask_obj = TB_LOW_PWR_C1_PORT_A_MASK;
3668                 unmask_obj = TB_LOW_PWR_C0_PORT_B_MASK;
3669                 offset = TB_LOW_PWR_C3_CL1;
3670         }
3671
3672         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH,
3673                          sw->cap_lp + offset, ARRAY_SIZE(val));
3674         if (ret)
3675                 return ret;
3676
3677         for (i = 0; i < ARRAY_SIZE(val); i++) {
3678                 val[i] |= mask_obj;
3679                 val[i] &= ~unmask_obj;
3680         }
3681
3682         return tb_sw_write(sw, &val, TB_CFG_SWITCH,
3683                            sw->cap_lp + offset, ARRAY_SIZE(val));
3684 }
3685
3686 /*
3687  * Can be used for read/write a specified PCIe bridge for any Thunderbolt 3
3688  * device. For now used only for Titan Ridge.
3689  */
3690 static int tb_switch_pcie_bridge_write(struct tb_switch *sw, unsigned int bridge,
3691                                        unsigned int pcie_offset, u32 value)
3692 {
3693         u32 offset, command, val;
3694         int ret;
3695
3696         if (sw->generation != 3)
3697                 return -EOPNOTSUPP;
3698
3699         offset = sw->cap_plug_events + TB_PLUG_EVENTS_PCIE_WR_DATA;
3700         ret = tb_sw_write(sw, &value, TB_CFG_SWITCH, offset, 1);
3701         if (ret)
3702                 return ret;
3703
3704         command = pcie_offset & TB_PLUG_EVENTS_PCIE_CMD_DW_OFFSET_MASK;
3705         command |= BIT(bridge + TB_PLUG_EVENTS_PCIE_CMD_BR_SHIFT);
3706         command |= TB_PLUG_EVENTS_PCIE_CMD_RD_WR_MASK;
3707         command |= TB_PLUG_EVENTS_PCIE_CMD_COMMAND_VAL
3708                         << TB_PLUG_EVENTS_PCIE_CMD_COMMAND_SHIFT;
3709         command |= TB_PLUG_EVENTS_PCIE_CMD_REQ_ACK_MASK;
3710
3711         offset = sw->cap_plug_events + TB_PLUG_EVENTS_PCIE_CMD;
3712
3713         ret = tb_sw_write(sw, &command, TB_CFG_SWITCH, offset, 1);
3714         if (ret)
3715                 return ret;
3716
3717         ret = tb_switch_wait_for_bit(sw, offset,
3718                                      TB_PLUG_EVENTS_PCIE_CMD_REQ_ACK_MASK, 0, 100);
3719         if (ret)
3720                 return ret;
3721
3722         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, offset, 1);
3723         if (ret)
3724                 return ret;
3725
3726         if (val & TB_PLUG_EVENTS_PCIE_CMD_TIMEOUT_MASK)
3727                 return -ETIMEDOUT;
3728
3729         return 0;
3730 }
3731
3732 /**
3733  * tb_switch_pcie_l1_enable() - Enable PCIe link to enter L1 state
3734  * @sw: Router to enable PCIe L1
3735  *
3736  * For Titan Ridge switch to enter CLx state, its PCIe bridges shall enable
3737  * entry to PCIe L1 state. Shall be called after the upstream PCIe tunnel
3738  * was configured. Due to Intel platforms limitation, shall be called only
3739  * for first hop switch.
3740  */
3741 int tb_switch_pcie_l1_enable(struct tb_switch *sw)
3742 {
3743         struct tb_switch *parent = tb_switch_parent(sw);
3744         int ret;
3745
3746         if (!tb_route(sw))
3747                 return 0;
3748
3749         if (!tb_switch_is_titan_ridge(sw))
3750                 return 0;
3751
3752         /* Enable PCIe L1 enable only for first hop router (depth = 1) */
3753         if (tb_route(parent))
3754                 return 0;
3755
3756         /* Write to downstream PCIe bridge #5 aka Dn4 */
3757         ret = tb_switch_pcie_bridge_write(sw, 5, 0x143, 0x0c7806b1);
3758         if (ret)
3759                 return ret;
3760
3761         /* Write to Upstream PCIe bridge #0 aka Up0 */
3762         return tb_switch_pcie_bridge_write(sw, 0, 0x143, 0x0c5806b1);
3763 }
3764
3765 /**
3766  * tb_switch_xhci_connect() - Connect internal xHCI
3767  * @sw: Router whose xHCI to connect
3768  *
3769  * Can be called to any router. For Alpine Ridge and Titan Ridge
3770  * performs special flows that bring the xHCI functional for any device
3771  * connected to the type-C port. Call only after PCIe tunnel has been
3772  * established. The function only does the connect if not done already
3773  * so can be called several times for the same router.
3774  */
3775 int tb_switch_xhci_connect(struct tb_switch *sw)
3776 {
3777         bool usb_port1, usb_port3, xhci_port1, xhci_port3;
3778         struct tb_port *port1, *port3;
3779         int ret;
3780
3781         port1 = &sw->ports[1];
3782         port3 = &sw->ports[3];
3783
3784         if (tb_switch_is_alpine_ridge(sw)) {
3785                 usb_port1 = tb_lc_is_usb_plugged(port1);
3786                 usb_port3 = tb_lc_is_usb_plugged(port3);
3787                 xhci_port1 = tb_lc_is_xhci_connected(port1);
3788                 xhci_port3 = tb_lc_is_xhci_connected(port3);
3789
3790                 /* Figure out correct USB port to connect */
3791                 if (usb_port1 && !xhci_port1) {
3792                         ret = tb_lc_xhci_connect(port1);
3793                         if (ret)
3794                                 return ret;
3795                 }
3796                 if (usb_port3 && !xhci_port3)
3797                         return tb_lc_xhci_connect(port3);
3798         } else if (tb_switch_is_titan_ridge(sw)) {
3799                 ret = tb_lc_xhci_connect(port1);
3800                 if (ret)
3801                         return ret;
3802                 return tb_lc_xhci_connect(port3);
3803         }
3804
3805         return 0;
3806 }
3807
3808 /**
3809  * tb_switch_xhci_disconnect() - Disconnect internal xHCI
3810  * @sw: Router whose xHCI to disconnect
3811  *
3812  * The opposite of tb_switch_xhci_connect(). Disconnects xHCI on both
3813  * ports.
3814  */
3815 void tb_switch_xhci_disconnect(struct tb_switch *sw)
3816 {
3817         if (sw->generation == 3) {
3818                 struct tb_port *port1 = &sw->ports[1];
3819                 struct tb_port *port3 = &sw->ports[3];
3820
3821                 tb_lc_xhci_disconnect(port1);
3822                 tb_port_dbg(port1, "disconnected xHCI\n");
3823                 tb_lc_xhci_disconnect(port3);
3824                 tb_port_dbg(port3, "disconnected xHCI\n");
3825         }
3826 }