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