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