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