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