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