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