• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
__nvm_get_auth_status(const struct tb_switch * sw)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 
nvm_get_auth_status(const struct tb_switch * sw,u32 * status)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 
nvm_set_auth_status(const struct tb_switch * sw,u32 status)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 
nvm_clear_auth_status(const struct tb_switch * sw)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 
nvm_validate_and_write(struct tb_switch * sw)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 
nvm_authenticate_host(struct tb_switch * sw)169 static int nvm_authenticate_host(struct tb_switch *sw)
170 {
171 	int ret = 0;
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 		u32 status;
180 
181 		ret = tb_domain_disconnect_all_paths(sw->tb);
182 		if (ret)
183 			return ret;
184 		/*
185 		 * The host controller goes away pretty soon after this if
186 		 * everything goes well so getting timeout is expected.
187 		 */
188 		ret = dma_port_flash_update_auth(sw->dma_port);
189 		if (!ret || ret == -ETIMEDOUT)
190 			return 0;
191 
192 		/*
193 		 * Any error from update auth operation requires power
194 		 * cycling of the host router.
195 		 */
196 		tb_sw_warn(sw, "failed to authenticate NVM, power cycling\n");
197 		if (dma_port_flash_update_auth_status(sw->dma_port, &status) > 0)
198 			nvm_set_auth_status(sw, status);
199 	}
200 
201 	/*
202 	 * From safe mode we can get out by just power cycling the
203 	 * switch.
204 	 */
205 	dma_port_power_cycle(sw->dma_port);
206 	return ret;
207 }
208 
nvm_authenticate_device(struct tb_switch * sw)209 static int nvm_authenticate_device(struct tb_switch *sw)
210 {
211 	int ret, retries = 10;
212 
213 	ret = dma_port_flash_update_auth(sw->dma_port);
214 	switch (ret) {
215 	case 0:
216 	case -ETIMEDOUT:
217 	case -EACCES:
218 	case -EINVAL:
219 		/* Power cycle is required */
220 		break;
221 	default:
222 		return ret;
223 	}
224 
225 	/*
226 	 * Poll here for the authentication status. It takes some time
227 	 * for the device to respond (we get timeout for a while). Once
228 	 * we get response the device needs to be power cycled in order
229 	 * to the new NVM to be taken into use.
230 	 */
231 	do {
232 		u32 status;
233 
234 		ret = dma_port_flash_update_auth_status(sw->dma_port, &status);
235 		if (ret < 0 && ret != -ETIMEDOUT)
236 			return ret;
237 		if (ret > 0) {
238 			if (status) {
239 				tb_sw_warn(sw, "failed to authenticate NVM\n");
240 				nvm_set_auth_status(sw, status);
241 			}
242 
243 			tb_sw_info(sw, "power cycling the switch now\n");
244 			dma_port_power_cycle(sw->dma_port);
245 			return 0;
246 		}
247 
248 		msleep(500);
249 	} while (--retries);
250 
251 	return -ETIMEDOUT;
252 }
253 
tb_switch_nvm_read(void * priv,unsigned int offset,void * val,size_t bytes)254 static int tb_switch_nvm_read(void *priv, unsigned int offset, void *val,
255 			      size_t bytes)
256 {
257 	struct tb_switch *sw = priv;
258 	int ret;
259 
260 	pm_runtime_get_sync(&sw->dev);
261 
262 	if (!mutex_trylock(&sw->tb->lock)) {
263 		ret = restart_syscall();
264 		goto out;
265 	}
266 
267 	ret = dma_port_flash_read(sw->dma_port, offset, val, bytes);
268 	mutex_unlock(&sw->tb->lock);
269 
270 out:
271 	pm_runtime_mark_last_busy(&sw->dev);
272 	pm_runtime_put_autosuspend(&sw->dev);
273 
274 	return ret;
275 }
276 
tb_switch_nvm_write(void * priv,unsigned int offset,void * val,size_t bytes)277 static int tb_switch_nvm_write(void *priv, unsigned int offset, void *val,
278 			       size_t bytes)
279 {
280 	struct tb_switch *sw = priv;
281 	int ret = 0;
282 
283 	if (!mutex_trylock(&sw->tb->lock))
284 		return restart_syscall();
285 
286 	/*
287 	 * Since writing the NVM image might require some special steps,
288 	 * for example when CSS headers are written, we cache the image
289 	 * locally here and handle the special cases when the user asks
290 	 * us to authenticate the image.
291 	 */
292 	if (!sw->nvm->buf) {
293 		sw->nvm->buf = vmalloc(NVM_MAX_SIZE);
294 		if (!sw->nvm->buf) {
295 			ret = -ENOMEM;
296 			goto unlock;
297 		}
298 	}
299 
300 	sw->nvm->buf_data_size = offset + bytes;
301 	memcpy(sw->nvm->buf + offset, val, bytes);
302 
303 unlock:
304 	mutex_unlock(&sw->tb->lock);
305 
306 	return ret;
307 }
308 
register_nvmem(struct tb_switch * sw,int id,size_t size,bool active)309 static struct nvmem_device *register_nvmem(struct tb_switch *sw, int id,
310 					   size_t size, bool active)
311 {
312 	struct nvmem_config config;
313 
314 	memset(&config, 0, sizeof(config));
315 
316 	if (active) {
317 		config.name = "nvm_active";
318 		config.reg_read = tb_switch_nvm_read;
319 		config.read_only = true;
320 	} else {
321 		config.name = "nvm_non_active";
322 		config.reg_write = tb_switch_nvm_write;
323 		config.root_only = true;
324 	}
325 
326 	config.id = id;
327 	config.stride = 4;
328 	config.word_size = 4;
329 	config.size = size;
330 	config.dev = &sw->dev;
331 	config.owner = THIS_MODULE;
332 	config.priv = sw;
333 
334 	return nvmem_register(&config);
335 }
336 
tb_switch_nvm_add(struct tb_switch * sw)337 static int tb_switch_nvm_add(struct tb_switch *sw)
338 {
339 	struct nvmem_device *nvm_dev;
340 	struct tb_switch_nvm *nvm;
341 	u32 val;
342 	int ret;
343 
344 	if (!sw->dma_port)
345 		return 0;
346 
347 	nvm = kzalloc(sizeof(*nvm), GFP_KERNEL);
348 	if (!nvm)
349 		return -ENOMEM;
350 
351 	nvm->id = ida_simple_get(&nvm_ida, 0, 0, GFP_KERNEL);
352 
353 	/*
354 	 * If the switch is in safe-mode the only accessible portion of
355 	 * the NVM is the non-active one where userspace is expected to
356 	 * write new functional NVM.
357 	 */
358 	if (!sw->safe_mode) {
359 		u32 nvm_size, hdr_size;
360 
361 		ret = dma_port_flash_read(sw->dma_port, NVM_FLASH_SIZE, &val,
362 					  sizeof(val));
363 		if (ret)
364 			goto err_ida;
365 
366 		hdr_size = sw->generation < 3 ? SZ_8K : SZ_16K;
367 		nvm_size = (SZ_1M << (val & 7)) / 8;
368 		nvm_size = (nvm_size - hdr_size) / 2;
369 
370 		ret = dma_port_flash_read(sw->dma_port, NVM_VERSION, &val,
371 					  sizeof(val));
372 		if (ret)
373 			goto err_ida;
374 
375 		nvm->major = val >> 16;
376 		nvm->minor = val >> 8;
377 
378 		nvm_dev = register_nvmem(sw, nvm->id, nvm_size, true);
379 		if (IS_ERR(nvm_dev)) {
380 			ret = PTR_ERR(nvm_dev);
381 			goto err_ida;
382 		}
383 		nvm->active = nvm_dev;
384 	}
385 
386 	if (!sw->no_nvm_upgrade) {
387 		nvm_dev = register_nvmem(sw, nvm->id, NVM_MAX_SIZE, false);
388 		if (IS_ERR(nvm_dev)) {
389 			ret = PTR_ERR(nvm_dev);
390 			goto err_nvm_active;
391 		}
392 		nvm->non_active = nvm_dev;
393 	}
394 
395 	sw->nvm = nvm;
396 	return 0;
397 
398 err_nvm_active:
399 	if (nvm->active)
400 		nvmem_unregister(nvm->active);
401 err_ida:
402 	ida_simple_remove(&nvm_ida, nvm->id);
403 	kfree(nvm);
404 
405 	return ret;
406 }
407 
tb_switch_nvm_remove(struct tb_switch * sw)408 static void tb_switch_nvm_remove(struct tb_switch *sw)
409 {
410 	struct tb_switch_nvm *nvm;
411 
412 	nvm = sw->nvm;
413 	sw->nvm = NULL;
414 
415 	if (!nvm)
416 		return;
417 
418 	/* Remove authentication status in case the switch is unplugged */
419 	if (!nvm->authenticating)
420 		nvm_clear_auth_status(sw);
421 
422 	if (nvm->non_active)
423 		nvmem_unregister(nvm->non_active);
424 	if (nvm->active)
425 		nvmem_unregister(nvm->active);
426 	ida_simple_remove(&nvm_ida, nvm->id);
427 	vfree(nvm->buf);
428 	kfree(nvm);
429 }
430 
431 /* port utility functions */
432 
tb_port_type(struct tb_regs_port_header * port)433 static const char *tb_port_type(struct tb_regs_port_header *port)
434 {
435 	switch (port->type >> 16) {
436 	case 0:
437 		switch ((u8) port->type) {
438 		case 0:
439 			return "Inactive";
440 		case 1:
441 			return "Port";
442 		case 2:
443 			return "NHI";
444 		default:
445 			return "unknown";
446 		}
447 	case 0x2:
448 		return "Ethernet";
449 	case 0x8:
450 		return "SATA";
451 	case 0xe:
452 		return "DP/HDMI";
453 	case 0x10:
454 		return "PCIe";
455 	case 0x20:
456 		return "USB";
457 	default:
458 		return "unknown";
459 	}
460 }
461 
tb_dump_port(struct tb * tb,struct tb_regs_port_header * port)462 static void tb_dump_port(struct tb *tb, struct tb_regs_port_header *port)
463 {
464 	tb_dbg(tb,
465 	       " Port %d: %x:%x (Revision: %d, TB Version: %d, Type: %s (%#x))\n",
466 	       port->port_number, port->vendor_id, port->device_id,
467 	       port->revision, port->thunderbolt_version, tb_port_type(port),
468 	       port->type);
469 	tb_dbg(tb, "  Max hop id (in/out): %d/%d\n",
470 	       port->max_in_hop_id, port->max_out_hop_id);
471 	tb_dbg(tb, "  Max counters: %d\n", port->max_counters);
472 	tb_dbg(tb, "  NFC Credits: %#x\n", port->nfc_credits);
473 }
474 
475 /**
476  * tb_port_state() - get connectedness state of a port
477  *
478  * The port must have a TB_CAP_PHY (i.e. it should be a real port).
479  *
480  * Return: Returns an enum tb_port_state on success or an error code on failure.
481  */
tb_port_state(struct tb_port * port)482 static int tb_port_state(struct tb_port *port)
483 {
484 	struct tb_cap_phy phy;
485 	int res;
486 	if (port->cap_phy == 0) {
487 		tb_port_WARN(port, "does not have a PHY\n");
488 		return -EINVAL;
489 	}
490 	res = tb_port_read(port, &phy, TB_CFG_PORT, port->cap_phy, 2);
491 	if (res)
492 		return res;
493 	return phy.state;
494 }
495 
496 /**
497  * tb_wait_for_port() - wait for a port to become ready
498  *
499  * Wait up to 1 second for a port to reach state TB_PORT_UP. If
500  * wait_if_unplugged is set then we also wait if the port is in state
501  * TB_PORT_UNPLUGGED (it takes a while for the device to be registered after
502  * switch resume). Otherwise we only wait if a device is registered but the link
503  * has not yet been established.
504  *
505  * Return: Returns an error code on failure. Returns 0 if the port is not
506  * connected or failed to reach state TB_PORT_UP within one second. Returns 1
507  * if the port is connected and in state TB_PORT_UP.
508  */
tb_wait_for_port(struct tb_port * port,bool wait_if_unplugged)509 int tb_wait_for_port(struct tb_port *port, bool wait_if_unplugged)
510 {
511 	int retries = 10;
512 	int state;
513 	if (!port->cap_phy) {
514 		tb_port_WARN(port, "does not have PHY\n");
515 		return -EINVAL;
516 	}
517 	if (tb_is_upstream_port(port)) {
518 		tb_port_WARN(port, "is the upstream port\n");
519 		return -EINVAL;
520 	}
521 
522 	while (retries--) {
523 		state = tb_port_state(port);
524 		if (state < 0)
525 			return state;
526 		if (state == TB_PORT_DISABLED) {
527 			tb_port_dbg(port, "is disabled (state: 0)\n");
528 			return 0;
529 		}
530 		if (state == TB_PORT_UNPLUGGED) {
531 			if (wait_if_unplugged) {
532 				/* used during resume */
533 				tb_port_dbg(port,
534 					    "is unplugged (state: 7), retrying...\n");
535 				msleep(100);
536 				continue;
537 			}
538 			tb_port_dbg(port, "is unplugged (state: 7)\n");
539 			return 0;
540 		}
541 		if (state == TB_PORT_UP) {
542 			tb_port_dbg(port, "is connected, link is up (state: 2)\n");
543 			return 1;
544 		}
545 
546 		/*
547 		 * After plug-in the state is TB_PORT_CONNECTING. Give it some
548 		 * time.
549 		 */
550 		tb_port_dbg(port,
551 			    "is connected, link is not up (state: %d), retrying...\n",
552 			    state);
553 		msleep(100);
554 	}
555 	tb_port_warn(port,
556 		     "failed to reach state TB_PORT_UP. Ignoring port...\n");
557 	return 0;
558 }
559 
560 /**
561  * tb_port_add_nfc_credits() - add/remove non flow controlled credits to port
562  *
563  * Change the number of NFC credits allocated to @port by @credits. To remove
564  * NFC credits pass a negative amount of credits.
565  *
566  * Return: Returns 0 on success or an error code on failure.
567  */
tb_port_add_nfc_credits(struct tb_port * port,int credits)568 int tb_port_add_nfc_credits(struct tb_port *port, int credits)
569 {
570 	u32 nfc_credits;
571 
572 	if (credits == 0 || port->sw->is_unplugged)
573 		return 0;
574 
575 	nfc_credits = port->config.nfc_credits & TB_PORT_NFC_CREDITS_MASK;
576 	nfc_credits += credits;
577 
578 	tb_port_dbg(port, "adding %d NFC credits to %lu",
579 		    credits, port->config.nfc_credits & TB_PORT_NFC_CREDITS_MASK);
580 
581 	port->config.nfc_credits &= ~TB_PORT_NFC_CREDITS_MASK;
582 	port->config.nfc_credits |= nfc_credits;
583 
584 	return tb_port_write(port, &port->config.nfc_credits,
585 			     TB_CFG_PORT, 4, 1);
586 }
587 
588 /**
589  * tb_port_set_initial_credits() - Set initial port link credits allocated
590  * @port: Port to set the initial credits
591  * @credits: Number of credits to to allocate
592  *
593  * Set initial credits value to be used for ingress shared buffering.
594  */
tb_port_set_initial_credits(struct tb_port * port,u32 credits)595 int tb_port_set_initial_credits(struct tb_port *port, u32 credits)
596 {
597 	u32 data;
598 	int ret;
599 
600 	ret = tb_port_read(port, &data, TB_CFG_PORT, 5, 1);
601 	if (ret)
602 		return ret;
603 
604 	data &= ~TB_PORT_LCA_MASK;
605 	data |= (credits << TB_PORT_LCA_SHIFT) & TB_PORT_LCA_MASK;
606 
607 	return tb_port_write(port, &data, TB_CFG_PORT, 5, 1);
608 }
609 
610 /**
611  * tb_port_clear_counter() - clear a counter in TB_CFG_COUNTER
612  *
613  * Return: Returns 0 on success or an error code on failure.
614  */
tb_port_clear_counter(struct tb_port * port,int counter)615 int tb_port_clear_counter(struct tb_port *port, int counter)
616 {
617 	u32 zero[3] = { 0, 0, 0 };
618 	tb_port_dbg(port, "clearing counter %d\n", counter);
619 	return tb_port_write(port, zero, TB_CFG_COUNTERS, 3 * counter, 3);
620 }
621 
622 /**
623  * tb_init_port() - initialize a port
624  *
625  * This is a helper method for tb_switch_alloc. Does not check or initialize
626  * any downstream switches.
627  *
628  * Return: Returns 0 on success or an error code on failure.
629  */
tb_init_port(struct tb_port * port)630 static int tb_init_port(struct tb_port *port)
631 {
632 	int res;
633 	int cap;
634 
635 	res = tb_port_read(port, &port->config, TB_CFG_PORT, 0, 8);
636 	if (res) {
637 		if (res == -ENODEV) {
638 			tb_dbg(port->sw->tb, " Port %d: not implemented\n",
639 			       port->port);
640 			return 0;
641 		}
642 		return res;
643 	}
644 
645 	/* Port 0 is the switch itself and has no PHY. */
646 	if (port->config.type == TB_TYPE_PORT && port->port != 0) {
647 		cap = tb_port_find_cap(port, TB_PORT_CAP_PHY);
648 
649 		if (cap > 0)
650 			port->cap_phy = cap;
651 		else
652 			tb_port_WARN(port, "non switch port without a PHY\n");
653 	} else if (port->port != 0) {
654 		cap = tb_port_find_cap(port, TB_PORT_CAP_ADAP);
655 		if (cap > 0)
656 			port->cap_adap = cap;
657 	}
658 
659 	tb_dump_port(port->sw->tb, &port->config);
660 
661 	/* Control port does not need HopID allocation */
662 	if (port->port) {
663 		ida_init(&port->in_hopids);
664 		ida_init(&port->out_hopids);
665 	}
666 
667 	return 0;
668 
669 }
670 
tb_port_alloc_hopid(struct tb_port * port,bool in,int min_hopid,int max_hopid)671 static int tb_port_alloc_hopid(struct tb_port *port, bool in, int min_hopid,
672 			       int max_hopid)
673 {
674 	int port_max_hopid;
675 	struct ida *ida;
676 
677 	if (in) {
678 		port_max_hopid = port->config.max_in_hop_id;
679 		ida = &port->in_hopids;
680 	} else {
681 		port_max_hopid = port->config.max_out_hop_id;
682 		ida = &port->out_hopids;
683 	}
684 
685 	/* HopIDs 0-7 are reserved */
686 	if (min_hopid < TB_PATH_MIN_HOPID)
687 		min_hopid = TB_PATH_MIN_HOPID;
688 
689 	if (max_hopid < 0 || max_hopid > port_max_hopid)
690 		max_hopid = port_max_hopid;
691 
692 	return ida_simple_get(ida, min_hopid, max_hopid + 1, GFP_KERNEL);
693 }
694 
695 /**
696  * tb_port_alloc_in_hopid() - Allocate input HopID from port
697  * @port: Port to allocate HopID for
698  * @min_hopid: Minimum acceptable input HopID
699  * @max_hopid: Maximum acceptable input HopID
700  *
701  * Return: HopID between @min_hopid and @max_hopid or negative errno in
702  * case of error.
703  */
tb_port_alloc_in_hopid(struct tb_port * port,int min_hopid,int max_hopid)704 int tb_port_alloc_in_hopid(struct tb_port *port, int min_hopid, int max_hopid)
705 {
706 	return tb_port_alloc_hopid(port, true, min_hopid, max_hopid);
707 }
708 
709 /**
710  * tb_port_alloc_out_hopid() - Allocate output HopID from port
711  * @port: Port to allocate HopID for
712  * @min_hopid: Minimum acceptable output HopID
713  * @max_hopid: Maximum acceptable output HopID
714  *
715  * Return: HopID between @min_hopid and @max_hopid or negative errno in
716  * case of error.
717  */
tb_port_alloc_out_hopid(struct tb_port * port,int min_hopid,int max_hopid)718 int tb_port_alloc_out_hopid(struct tb_port *port, int min_hopid, int max_hopid)
719 {
720 	return tb_port_alloc_hopid(port, false, min_hopid, max_hopid);
721 }
722 
723 /**
724  * tb_port_release_in_hopid() - Release allocated input HopID from port
725  * @port: Port whose HopID to release
726  * @hopid: HopID to release
727  */
tb_port_release_in_hopid(struct tb_port * port,int hopid)728 void tb_port_release_in_hopid(struct tb_port *port, int hopid)
729 {
730 	ida_simple_remove(&port->in_hopids, hopid);
731 }
732 
733 /**
734  * tb_port_release_out_hopid() - Release allocated output HopID from port
735  * @port: Port whose HopID to release
736  * @hopid: HopID to release
737  */
tb_port_release_out_hopid(struct tb_port * port,int hopid)738 void tb_port_release_out_hopid(struct tb_port *port, int hopid)
739 {
740 	ida_simple_remove(&port->out_hopids, hopid);
741 }
742 
743 /**
744  * tb_next_port_on_path() - Return next port for given port on a path
745  * @start: Start port of the walk
746  * @end: End port of the walk
747  * @prev: Previous port (%NULL if this is the first)
748  *
749  * This function can be used to walk from one port to another if they
750  * are connected through zero or more switches. If the @prev is dual
751  * link port, the function follows that link and returns another end on
752  * that same link.
753  *
754  * If the @end port has been reached, return %NULL.
755  *
756  * Domain tb->lock must be held when this function is called.
757  */
tb_next_port_on_path(struct tb_port * start,struct tb_port * end,struct tb_port * prev)758 struct tb_port *tb_next_port_on_path(struct tb_port *start, struct tb_port *end,
759 				     struct tb_port *prev)
760 {
761 	struct tb_port *next;
762 
763 	if (!prev)
764 		return start;
765 
766 	if (prev->sw == end->sw) {
767 		if (prev == end)
768 			return NULL;
769 		return end;
770 	}
771 
772 	if (start->sw->config.depth < end->sw->config.depth) {
773 		if (prev->remote &&
774 		    prev->remote->sw->config.depth > prev->sw->config.depth)
775 			next = prev->remote;
776 		else
777 			next = tb_port_at(tb_route(end->sw), prev->sw);
778 	} else {
779 		if (tb_is_upstream_port(prev)) {
780 			next = prev->remote;
781 		} else {
782 			next = tb_upstream_port(prev->sw);
783 			/*
784 			 * Keep the same link if prev and next are both
785 			 * dual link ports.
786 			 */
787 			if (next->dual_link_port &&
788 			    next->link_nr != prev->link_nr) {
789 				next = next->dual_link_port;
790 			}
791 		}
792 	}
793 
794 	return next;
795 }
796 
797 /**
798  * tb_port_is_enabled() - Is the adapter port enabled
799  * @port: Port to check
800  */
tb_port_is_enabled(struct tb_port * port)801 bool tb_port_is_enabled(struct tb_port *port)
802 {
803 	switch (port->config.type) {
804 	case TB_TYPE_PCIE_UP:
805 	case TB_TYPE_PCIE_DOWN:
806 		return tb_pci_port_is_enabled(port);
807 
808 	case TB_TYPE_DP_HDMI_IN:
809 	case TB_TYPE_DP_HDMI_OUT:
810 		return tb_dp_port_is_enabled(port);
811 
812 	default:
813 		return false;
814 	}
815 }
816 
817 /**
818  * tb_pci_port_is_enabled() - Is the PCIe adapter port enabled
819  * @port: PCIe port to check
820  */
tb_pci_port_is_enabled(struct tb_port * port)821 bool tb_pci_port_is_enabled(struct tb_port *port)
822 {
823 	u32 data;
824 
825 	if (tb_port_read(port, &data, TB_CFG_PORT, port->cap_adap, 1))
826 		return false;
827 
828 	return !!(data & TB_PCI_EN);
829 }
830 
831 /**
832  * tb_pci_port_enable() - Enable PCIe adapter port
833  * @port: PCIe port to enable
834  * @enable: Enable/disable the PCIe adapter
835  */
tb_pci_port_enable(struct tb_port * port,bool enable)836 int tb_pci_port_enable(struct tb_port *port, bool enable)
837 {
838 	u32 word = enable ? TB_PCI_EN : 0x0;
839 	if (!port->cap_adap)
840 		return -ENXIO;
841 	return tb_port_write(port, &word, TB_CFG_PORT, port->cap_adap, 1);
842 }
843 
844 /**
845  * tb_dp_port_hpd_is_active() - Is HPD already active
846  * @port: DP out port to check
847  *
848  * Checks if the DP OUT adapter port has HDP bit already set.
849  */
tb_dp_port_hpd_is_active(struct tb_port * port)850 int tb_dp_port_hpd_is_active(struct tb_port *port)
851 {
852 	u32 data;
853 	int ret;
854 
855 	ret = tb_port_read(port, &data, TB_CFG_PORT, port->cap_adap + 2, 1);
856 	if (ret)
857 		return ret;
858 
859 	return !!(data & TB_DP_HDP);
860 }
861 
862 /**
863  * tb_dp_port_hpd_clear() - Clear HPD from DP IN port
864  * @port: Port to clear HPD
865  *
866  * If the DP IN port has HDP set, this function can be used to clear it.
867  */
tb_dp_port_hpd_clear(struct tb_port * port)868 int tb_dp_port_hpd_clear(struct tb_port *port)
869 {
870 	u32 data;
871 	int ret;
872 
873 	ret = tb_port_read(port, &data, TB_CFG_PORT, port->cap_adap + 3, 1);
874 	if (ret)
875 		return ret;
876 
877 	data |= TB_DP_HPDC;
878 	return tb_port_write(port, &data, TB_CFG_PORT, port->cap_adap + 3, 1);
879 }
880 
881 /**
882  * tb_dp_port_set_hops() - Set video/aux Hop IDs for DP port
883  * @port: DP IN/OUT port to set hops
884  * @video: Video Hop ID
885  * @aux_tx: AUX TX Hop ID
886  * @aux_rx: AUX RX Hop ID
887  *
888  * Programs specified Hop IDs for DP IN/OUT port.
889  */
tb_dp_port_set_hops(struct tb_port * port,unsigned int video,unsigned int aux_tx,unsigned int aux_rx)890 int tb_dp_port_set_hops(struct tb_port *port, unsigned int video,
891 			unsigned int aux_tx, unsigned int aux_rx)
892 {
893 	u32 data[2];
894 	int ret;
895 
896 	ret = tb_port_read(port, data, TB_CFG_PORT, port->cap_adap,
897 			   ARRAY_SIZE(data));
898 	if (ret)
899 		return ret;
900 
901 	data[0] &= ~TB_DP_VIDEO_HOPID_MASK;
902 	data[1] &= ~(TB_DP_AUX_RX_HOPID_MASK | TB_DP_AUX_TX_HOPID_MASK);
903 
904 	data[0] |= (video << TB_DP_VIDEO_HOPID_SHIFT) & TB_DP_VIDEO_HOPID_MASK;
905 	data[1] |= aux_tx & TB_DP_AUX_TX_HOPID_MASK;
906 	data[1] |= (aux_rx << TB_DP_AUX_RX_HOPID_SHIFT) & TB_DP_AUX_RX_HOPID_MASK;
907 
908 	return tb_port_write(port, data, TB_CFG_PORT, port->cap_adap,
909 			     ARRAY_SIZE(data));
910 }
911 
912 /**
913  * tb_dp_port_is_enabled() - Is DP adapter port enabled
914  * @port: DP adapter port to check
915  */
tb_dp_port_is_enabled(struct tb_port * port)916 bool tb_dp_port_is_enabled(struct tb_port *port)
917 {
918 	u32 data[2];
919 
920 	if (tb_port_read(port, data, TB_CFG_PORT, port->cap_adap,
921 			 ARRAY_SIZE(data)))
922 		return false;
923 
924 	return !!(data[0] & (TB_DP_VIDEO_EN | TB_DP_AUX_EN));
925 }
926 
927 /**
928  * tb_dp_port_enable() - Enables/disables DP paths of a port
929  * @port: DP IN/OUT port
930  * @enable: Enable/disable DP path
931  *
932  * Once Hop IDs are programmed DP paths can be enabled or disabled by
933  * calling this function.
934  */
tb_dp_port_enable(struct tb_port * port,bool enable)935 int tb_dp_port_enable(struct tb_port *port, bool enable)
936 {
937 	u32 data[2];
938 	int ret;
939 
940 	ret = tb_port_read(port, data, TB_CFG_PORT, port->cap_adap,
941 			   ARRAY_SIZE(data));
942 	if (ret)
943 		return ret;
944 
945 	if (enable)
946 		data[0] |= TB_DP_VIDEO_EN | TB_DP_AUX_EN;
947 	else
948 		data[0] &= ~(TB_DP_VIDEO_EN | TB_DP_AUX_EN);
949 
950 	return tb_port_write(port, data, TB_CFG_PORT, port->cap_adap,
951 			     ARRAY_SIZE(data));
952 }
953 
954 /* switch utility functions */
955 
tb_dump_switch(struct tb * tb,struct tb_regs_switch_header * sw)956 static void tb_dump_switch(struct tb *tb, struct tb_regs_switch_header *sw)
957 {
958 	tb_dbg(tb, " Switch: %x:%x (Revision: %d, TB Version: %d)\n",
959 	       sw->vendor_id, sw->device_id, sw->revision,
960 	       sw->thunderbolt_version);
961 	tb_dbg(tb, "  Max Port Number: %d\n", sw->max_port_number);
962 	tb_dbg(tb, "  Config:\n");
963 	tb_dbg(tb,
964 		"   Upstream Port Number: %d Depth: %d Route String: %#llx Enabled: %d, PlugEventsDelay: %dms\n",
965 	       sw->upstream_port_number, sw->depth,
966 	       (((u64) sw->route_hi) << 32) | sw->route_lo,
967 	       sw->enabled, sw->plug_events_delay);
968 	tb_dbg(tb, "   unknown1: %#x unknown4: %#x\n",
969 	       sw->__unknown1, sw->__unknown4);
970 }
971 
972 /**
973  * reset_switch() - reconfigure route, enable and send TB_CFG_PKG_RESET
974  *
975  * Return: Returns 0 on success or an error code on failure.
976  */
tb_switch_reset(struct tb * tb,u64 route)977 int tb_switch_reset(struct tb *tb, u64 route)
978 {
979 	struct tb_cfg_result res;
980 	struct tb_regs_switch_header header = {
981 		header.route_hi = route >> 32,
982 		header.route_lo = route,
983 		header.enabled = true,
984 	};
985 	tb_dbg(tb, "resetting switch at %llx\n", route);
986 	res.err = tb_cfg_write(tb->ctl, ((u32 *) &header) + 2, route,
987 			0, 2, 2, 2);
988 	if (res.err)
989 		return res.err;
990 	res = tb_cfg_reset(tb->ctl, route, TB_CFG_DEFAULT_TIMEOUT);
991 	if (res.err > 0)
992 		return -EIO;
993 	return res.err;
994 }
995 
996 /**
997  * tb_plug_events_active() - enable/disable plug events on a switch
998  *
999  * Also configures a sane plug_events_delay of 255ms.
1000  *
1001  * Return: Returns 0 on success or an error code on failure.
1002  */
tb_plug_events_active(struct tb_switch * sw,bool active)1003 static int tb_plug_events_active(struct tb_switch *sw, bool active)
1004 {
1005 	u32 data;
1006 	int res;
1007 
1008 	if (!sw->config.enabled)
1009 		return 0;
1010 
1011 	sw->config.plug_events_delay = 0xff;
1012 	res = tb_sw_write(sw, ((u32 *) &sw->config) + 4, TB_CFG_SWITCH, 4, 1);
1013 	if (res)
1014 		return res;
1015 
1016 	res = tb_sw_read(sw, &data, TB_CFG_SWITCH, sw->cap_plug_events + 1, 1);
1017 	if (res)
1018 		return res;
1019 
1020 	if (active) {
1021 		data = data & 0xFFFFFF83;
1022 		switch (sw->config.device_id) {
1023 		case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
1024 		case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
1025 		case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
1026 			break;
1027 		default:
1028 			data |= 4;
1029 		}
1030 	} else {
1031 		data = data | 0x7c;
1032 	}
1033 	return tb_sw_write(sw, &data, TB_CFG_SWITCH,
1034 			   sw->cap_plug_events + 1, 1);
1035 }
1036 
authorized_show(struct device * dev,struct device_attribute * attr,char * buf)1037 static ssize_t authorized_show(struct device *dev,
1038 			       struct device_attribute *attr,
1039 			       char *buf)
1040 {
1041 	struct tb_switch *sw = tb_to_switch(dev);
1042 
1043 	return sprintf(buf, "%u\n", sw->authorized);
1044 }
1045 
tb_switch_set_authorized(struct tb_switch * sw,unsigned int val)1046 static int tb_switch_set_authorized(struct tb_switch *sw, unsigned int val)
1047 {
1048 	int ret = -EINVAL;
1049 
1050 	if (!mutex_trylock(&sw->tb->lock))
1051 		return restart_syscall();
1052 
1053 	if (sw->authorized)
1054 		goto unlock;
1055 
1056 	switch (val) {
1057 	/* Approve switch */
1058 	case 1:
1059 		if (sw->key)
1060 			ret = tb_domain_approve_switch_key(sw->tb, sw);
1061 		else
1062 			ret = tb_domain_approve_switch(sw->tb, sw);
1063 		break;
1064 
1065 	/* Challenge switch */
1066 	case 2:
1067 		if (sw->key)
1068 			ret = tb_domain_challenge_switch_key(sw->tb, sw);
1069 		break;
1070 
1071 	default:
1072 		break;
1073 	}
1074 
1075 	if (!ret) {
1076 		sw->authorized = val;
1077 		/* Notify status change to the userspace */
1078 		kobject_uevent(&sw->dev.kobj, KOBJ_CHANGE);
1079 	}
1080 
1081 unlock:
1082 	mutex_unlock(&sw->tb->lock);
1083 	return ret;
1084 }
1085 
authorized_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1086 static ssize_t authorized_store(struct device *dev,
1087 				struct device_attribute *attr,
1088 				const char *buf, size_t count)
1089 {
1090 	struct tb_switch *sw = tb_to_switch(dev);
1091 	unsigned int val;
1092 	ssize_t ret;
1093 
1094 	ret = kstrtouint(buf, 0, &val);
1095 	if (ret)
1096 		return ret;
1097 	if (val > 2)
1098 		return -EINVAL;
1099 
1100 	pm_runtime_get_sync(&sw->dev);
1101 	ret = tb_switch_set_authorized(sw, val);
1102 	pm_runtime_mark_last_busy(&sw->dev);
1103 	pm_runtime_put_autosuspend(&sw->dev);
1104 
1105 	return ret ? ret : count;
1106 }
1107 static DEVICE_ATTR_RW(authorized);
1108 
boot_show(struct device * dev,struct device_attribute * attr,char * buf)1109 static ssize_t boot_show(struct device *dev, struct device_attribute *attr,
1110 			 char *buf)
1111 {
1112 	struct tb_switch *sw = tb_to_switch(dev);
1113 
1114 	return sprintf(buf, "%u\n", sw->boot);
1115 }
1116 static DEVICE_ATTR_RO(boot);
1117 
device_show(struct device * dev,struct device_attribute * attr,char * buf)1118 static ssize_t device_show(struct device *dev, struct device_attribute *attr,
1119 			   char *buf)
1120 {
1121 	struct tb_switch *sw = tb_to_switch(dev);
1122 
1123 	return sprintf(buf, "%#x\n", sw->device);
1124 }
1125 static DEVICE_ATTR_RO(device);
1126 
1127 static ssize_t
device_name_show(struct device * dev,struct device_attribute * attr,char * buf)1128 device_name_show(struct device *dev, struct device_attribute *attr, char *buf)
1129 {
1130 	struct tb_switch *sw = tb_to_switch(dev);
1131 
1132 	return sprintf(buf, "%s\n", sw->device_name ? sw->device_name : "");
1133 }
1134 static DEVICE_ATTR_RO(device_name);
1135 
key_show(struct device * dev,struct device_attribute * attr,char * buf)1136 static ssize_t key_show(struct device *dev, struct device_attribute *attr,
1137 			char *buf)
1138 {
1139 	struct tb_switch *sw = tb_to_switch(dev);
1140 	ssize_t ret;
1141 
1142 	if (!mutex_trylock(&sw->tb->lock))
1143 		return restart_syscall();
1144 
1145 	if (sw->key)
1146 		ret = sprintf(buf, "%*phN\n", TB_SWITCH_KEY_SIZE, sw->key);
1147 	else
1148 		ret = sprintf(buf, "\n");
1149 
1150 	mutex_unlock(&sw->tb->lock);
1151 	return ret;
1152 }
1153 
key_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1154 static ssize_t key_store(struct device *dev, struct device_attribute *attr,
1155 			 const char *buf, size_t count)
1156 {
1157 	struct tb_switch *sw = tb_to_switch(dev);
1158 	u8 key[TB_SWITCH_KEY_SIZE];
1159 	ssize_t ret = count;
1160 	bool clear = false;
1161 
1162 	if (!strcmp(buf, "\n"))
1163 		clear = true;
1164 	else if (hex2bin(key, buf, sizeof(key)))
1165 		return -EINVAL;
1166 
1167 	if (!mutex_trylock(&sw->tb->lock))
1168 		return restart_syscall();
1169 
1170 	if (sw->authorized) {
1171 		ret = -EBUSY;
1172 	} else {
1173 		kfree(sw->key);
1174 		if (clear) {
1175 			sw->key = NULL;
1176 		} else {
1177 			sw->key = kmemdup(key, sizeof(key), GFP_KERNEL);
1178 			if (!sw->key)
1179 				ret = -ENOMEM;
1180 		}
1181 	}
1182 
1183 	mutex_unlock(&sw->tb->lock);
1184 	return ret;
1185 }
1186 static DEVICE_ATTR(key, 0600, key_show, key_store);
1187 
nvm_authenticate_start(struct tb_switch * sw)1188 static void nvm_authenticate_start(struct tb_switch *sw)
1189 {
1190 	struct pci_dev *root_port;
1191 
1192 	/*
1193 	 * During host router NVM upgrade we should not allow root port to
1194 	 * go into D3cold because some root ports cannot trigger PME
1195 	 * itself. To be on the safe side keep the root port in D0 during
1196 	 * the whole upgrade process.
1197 	 */
1198 	root_port = pci_find_pcie_root_port(sw->tb->nhi->pdev);
1199 	if (root_port)
1200 		pm_runtime_get_noresume(&root_port->dev);
1201 }
1202 
nvm_authenticate_complete(struct tb_switch * sw)1203 static void nvm_authenticate_complete(struct tb_switch *sw)
1204 {
1205 	struct pci_dev *root_port;
1206 
1207 	root_port = pci_find_pcie_root_port(sw->tb->nhi->pdev);
1208 	if (root_port)
1209 		pm_runtime_put(&root_port->dev);
1210 }
1211 
nvm_authenticate_show(struct device * dev,struct device_attribute * attr,char * buf)1212 static ssize_t nvm_authenticate_show(struct device *dev,
1213 	struct device_attribute *attr, char *buf)
1214 {
1215 	struct tb_switch *sw = tb_to_switch(dev);
1216 	u32 status;
1217 
1218 	nvm_get_auth_status(sw, &status);
1219 	return sprintf(buf, "%#x\n", status);
1220 }
1221 
nvm_authenticate_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)1222 static ssize_t nvm_authenticate_store(struct device *dev,
1223 	struct device_attribute *attr, const char *buf, size_t count)
1224 {
1225 	struct tb_switch *sw = tb_to_switch(dev);
1226 	bool val;
1227 	int ret;
1228 
1229 	pm_runtime_get_sync(&sw->dev);
1230 
1231 	if (!mutex_trylock(&sw->tb->lock)) {
1232 		ret = restart_syscall();
1233 		goto exit_rpm;
1234 	}
1235 
1236 	/* If NVMem devices are not yet added */
1237 	if (!sw->nvm) {
1238 		ret = -EAGAIN;
1239 		goto exit_unlock;
1240 	}
1241 
1242 	ret = kstrtobool(buf, &val);
1243 	if (ret)
1244 		goto exit_unlock;
1245 
1246 	/* Always clear the authentication status */
1247 	nvm_clear_auth_status(sw);
1248 
1249 	if (val) {
1250 		if (!sw->nvm->buf) {
1251 			ret = -EINVAL;
1252 			goto exit_unlock;
1253 		}
1254 
1255 		ret = nvm_validate_and_write(sw);
1256 		if (ret)
1257 			goto exit_unlock;
1258 
1259 		sw->nvm->authenticating = true;
1260 
1261 		if (!tb_route(sw)) {
1262 			/*
1263 			 * Keep root port from suspending as long as the
1264 			 * NVM upgrade process is running.
1265 			 */
1266 			nvm_authenticate_start(sw);
1267 			ret = nvm_authenticate_host(sw);
1268 		} else {
1269 			ret = nvm_authenticate_device(sw);
1270 		}
1271 	}
1272 
1273 exit_unlock:
1274 	mutex_unlock(&sw->tb->lock);
1275 exit_rpm:
1276 	pm_runtime_mark_last_busy(&sw->dev);
1277 	pm_runtime_put_autosuspend(&sw->dev);
1278 
1279 	if (ret)
1280 		return ret;
1281 	return count;
1282 }
1283 static DEVICE_ATTR_RW(nvm_authenticate);
1284 
nvm_version_show(struct device * dev,struct device_attribute * attr,char * buf)1285 static ssize_t nvm_version_show(struct device *dev,
1286 				struct device_attribute *attr, char *buf)
1287 {
1288 	struct tb_switch *sw = tb_to_switch(dev);
1289 	int ret;
1290 
1291 	if (!mutex_trylock(&sw->tb->lock))
1292 		return restart_syscall();
1293 
1294 	if (sw->safe_mode)
1295 		ret = -ENODATA;
1296 	else if (!sw->nvm)
1297 		ret = -EAGAIN;
1298 	else
1299 		ret = sprintf(buf, "%x.%x\n", sw->nvm->major, sw->nvm->minor);
1300 
1301 	mutex_unlock(&sw->tb->lock);
1302 
1303 	return ret;
1304 }
1305 static DEVICE_ATTR_RO(nvm_version);
1306 
vendor_show(struct device * dev,struct device_attribute * attr,char * buf)1307 static ssize_t vendor_show(struct device *dev, struct device_attribute *attr,
1308 			   char *buf)
1309 {
1310 	struct tb_switch *sw = tb_to_switch(dev);
1311 
1312 	return sprintf(buf, "%#x\n", sw->vendor);
1313 }
1314 static DEVICE_ATTR_RO(vendor);
1315 
1316 static ssize_t
vendor_name_show(struct device * dev,struct device_attribute * attr,char * buf)1317 vendor_name_show(struct device *dev, struct device_attribute *attr, char *buf)
1318 {
1319 	struct tb_switch *sw = tb_to_switch(dev);
1320 
1321 	return sprintf(buf, "%s\n", sw->vendor_name ? sw->vendor_name : "");
1322 }
1323 static DEVICE_ATTR_RO(vendor_name);
1324 
unique_id_show(struct device * dev,struct device_attribute * attr,char * buf)1325 static ssize_t unique_id_show(struct device *dev, struct device_attribute *attr,
1326 			      char *buf)
1327 {
1328 	struct tb_switch *sw = tb_to_switch(dev);
1329 
1330 	return sprintf(buf, "%pUb\n", sw->uuid);
1331 }
1332 static DEVICE_ATTR_RO(unique_id);
1333 
1334 static struct attribute *switch_attrs[] = {
1335 	&dev_attr_authorized.attr,
1336 	&dev_attr_boot.attr,
1337 	&dev_attr_device.attr,
1338 	&dev_attr_device_name.attr,
1339 	&dev_attr_key.attr,
1340 	&dev_attr_nvm_authenticate.attr,
1341 	&dev_attr_nvm_version.attr,
1342 	&dev_attr_vendor.attr,
1343 	&dev_attr_vendor_name.attr,
1344 	&dev_attr_unique_id.attr,
1345 	NULL,
1346 };
1347 
switch_attr_is_visible(struct kobject * kobj,struct attribute * attr,int n)1348 static umode_t switch_attr_is_visible(struct kobject *kobj,
1349 				      struct attribute *attr, int n)
1350 {
1351 	struct device *dev = container_of(kobj, struct device, kobj);
1352 	struct tb_switch *sw = tb_to_switch(dev);
1353 
1354 	if (attr == &dev_attr_device.attr) {
1355 		if (!sw->device)
1356 			return 0;
1357 	} else if (attr == &dev_attr_device_name.attr) {
1358 		if (!sw->device_name)
1359 			return 0;
1360 	} else if (attr == &dev_attr_vendor.attr)  {
1361 		if (!sw->vendor)
1362 			return 0;
1363 	} else if (attr == &dev_attr_vendor_name.attr)  {
1364 		if (!sw->vendor_name)
1365 			return 0;
1366 	} else if (attr == &dev_attr_key.attr) {
1367 		if (tb_route(sw) &&
1368 		    sw->tb->security_level == TB_SECURITY_SECURE &&
1369 		    sw->security_level == TB_SECURITY_SECURE)
1370 			return attr->mode;
1371 		return 0;
1372 	} else if (attr == &dev_attr_nvm_authenticate.attr) {
1373 		if (sw->dma_port && !sw->no_nvm_upgrade)
1374 			return attr->mode;
1375 		return 0;
1376 	} else if (attr == &dev_attr_nvm_version.attr) {
1377 		if (sw->dma_port)
1378 			return attr->mode;
1379 		return 0;
1380 	} else if (attr == &dev_attr_boot.attr) {
1381 		if (tb_route(sw))
1382 			return attr->mode;
1383 		return 0;
1384 	}
1385 
1386 	return sw->safe_mode ? 0 : attr->mode;
1387 }
1388 
1389 static struct attribute_group switch_group = {
1390 	.is_visible = switch_attr_is_visible,
1391 	.attrs = switch_attrs,
1392 };
1393 
1394 static const struct attribute_group *switch_groups[] = {
1395 	&switch_group,
1396 	NULL,
1397 };
1398 
tb_switch_release(struct device * dev)1399 static void tb_switch_release(struct device *dev)
1400 {
1401 	struct tb_switch *sw = tb_to_switch(dev);
1402 	int i;
1403 
1404 	dma_port_free(sw->dma_port);
1405 
1406 	for (i = 1; i <= sw->config.max_port_number; i++) {
1407 		if (!sw->ports[i].disabled) {
1408 			ida_destroy(&sw->ports[i].in_hopids);
1409 			ida_destroy(&sw->ports[i].out_hopids);
1410 		}
1411 	}
1412 
1413 	kfree(sw->uuid);
1414 	kfree(sw->device_name);
1415 	kfree(sw->vendor_name);
1416 	kfree(sw->ports);
1417 	kfree(sw->drom);
1418 	kfree(sw->key);
1419 	kfree(sw);
1420 }
1421 
1422 /*
1423  * Currently only need to provide the callbacks. Everything else is handled
1424  * in the connection manager.
1425  */
tb_switch_runtime_suspend(struct device * dev)1426 static int __maybe_unused tb_switch_runtime_suspend(struct device *dev)
1427 {
1428 	struct tb_switch *sw = tb_to_switch(dev);
1429 	const struct tb_cm_ops *cm_ops = sw->tb->cm_ops;
1430 
1431 	if (cm_ops->runtime_suspend_switch)
1432 		return cm_ops->runtime_suspend_switch(sw);
1433 
1434 	return 0;
1435 }
1436 
tb_switch_runtime_resume(struct device * dev)1437 static int __maybe_unused tb_switch_runtime_resume(struct device *dev)
1438 {
1439 	struct tb_switch *sw = tb_to_switch(dev);
1440 	const struct tb_cm_ops *cm_ops = sw->tb->cm_ops;
1441 
1442 	if (cm_ops->runtime_resume_switch)
1443 		return cm_ops->runtime_resume_switch(sw);
1444 	return 0;
1445 }
1446 
1447 static const struct dev_pm_ops tb_switch_pm_ops = {
1448 	SET_RUNTIME_PM_OPS(tb_switch_runtime_suspend, tb_switch_runtime_resume,
1449 			   NULL)
1450 };
1451 
1452 struct device_type tb_switch_type = {
1453 	.name = "thunderbolt_device",
1454 	.release = tb_switch_release,
1455 	.pm = &tb_switch_pm_ops,
1456 };
1457 
tb_switch_get_generation(struct tb_switch * sw)1458 static int tb_switch_get_generation(struct tb_switch *sw)
1459 {
1460 	switch (sw->config.device_id) {
1461 	case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
1462 	case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
1463 	case PCI_DEVICE_ID_INTEL_LIGHT_PEAK:
1464 	case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_2C:
1465 	case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C:
1466 	case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
1467 	case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_2C_BRIDGE:
1468 	case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_4C_BRIDGE:
1469 		return 1;
1470 
1471 	case PCI_DEVICE_ID_INTEL_WIN_RIDGE_2C_BRIDGE:
1472 	case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_BRIDGE:
1473 	case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_BRIDGE:
1474 		return 2;
1475 
1476 	case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_LP_BRIDGE:
1477 	case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_2C_BRIDGE:
1478 	case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_4C_BRIDGE:
1479 	case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_2C_BRIDGE:
1480 	case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_4C_BRIDGE:
1481 	case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_2C_BRIDGE:
1482 	case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_4C_BRIDGE:
1483 	case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_DD_BRIDGE:
1484 	case PCI_DEVICE_ID_INTEL_ICL_NHI0:
1485 	case PCI_DEVICE_ID_INTEL_ICL_NHI1:
1486 		return 3;
1487 
1488 	default:
1489 		/*
1490 		 * For unknown switches assume generation to be 1 to be
1491 		 * on the safe side.
1492 		 */
1493 		tb_sw_warn(sw, "unsupported switch device id %#x\n",
1494 			   sw->config.device_id);
1495 		return 1;
1496 	}
1497 }
1498 
1499 /**
1500  * tb_switch_alloc() - allocate a switch
1501  * @tb: Pointer to the owning domain
1502  * @parent: Parent device for this switch
1503  * @route: Route string for this switch
1504  *
1505  * Allocates and initializes a switch. Will not upload configuration to
1506  * the switch. For that you need to call tb_switch_configure()
1507  * separately. The returned switch should be released by calling
1508  * tb_switch_put().
1509  *
1510  * Return: Pointer to the allocated switch or ERR_PTR() in case of
1511  * failure.
1512  */
tb_switch_alloc(struct tb * tb,struct device * parent,u64 route)1513 struct tb_switch *tb_switch_alloc(struct tb *tb, struct device *parent,
1514 				  u64 route)
1515 {
1516 	struct tb_switch *sw;
1517 	int upstream_port;
1518 	int i, ret, depth;
1519 
1520 	/* Make sure we do not exceed maximum topology limit */
1521 	depth = tb_route_length(route);
1522 	if (depth > TB_SWITCH_MAX_DEPTH)
1523 		return ERR_PTR(-EADDRNOTAVAIL);
1524 
1525 	upstream_port = tb_cfg_get_upstream_port(tb->ctl, route);
1526 	if (upstream_port < 0)
1527 		return ERR_PTR(upstream_port);
1528 
1529 	sw = kzalloc(sizeof(*sw), GFP_KERNEL);
1530 	if (!sw)
1531 		return ERR_PTR(-ENOMEM);
1532 
1533 	sw->tb = tb;
1534 	ret = tb_cfg_read(tb->ctl, &sw->config, route, 0, TB_CFG_SWITCH, 0, 5);
1535 	if (ret)
1536 		goto err_free_sw_ports;
1537 
1538 	tb_dbg(tb, "current switch config:\n");
1539 	tb_dump_switch(tb, &sw->config);
1540 
1541 	/* configure switch */
1542 	sw->config.upstream_port_number = upstream_port;
1543 	sw->config.depth = depth;
1544 	sw->config.route_hi = upper_32_bits(route);
1545 	sw->config.route_lo = lower_32_bits(route);
1546 	sw->config.enabled = 0;
1547 
1548 	/* initialize ports */
1549 	sw->ports = kcalloc(sw->config.max_port_number + 1, sizeof(*sw->ports),
1550 				GFP_KERNEL);
1551 	if (!sw->ports) {
1552 		ret = -ENOMEM;
1553 		goto err_free_sw_ports;
1554 	}
1555 
1556 	for (i = 0; i <= sw->config.max_port_number; i++) {
1557 		/* minimum setup for tb_find_cap and tb_drom_read to work */
1558 		sw->ports[i].sw = sw;
1559 		sw->ports[i].port = i;
1560 	}
1561 
1562 	sw->generation = tb_switch_get_generation(sw);
1563 
1564 	ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_PLUG_EVENTS);
1565 	if (ret < 0) {
1566 		tb_sw_warn(sw, "cannot find TB_VSE_CAP_PLUG_EVENTS aborting\n");
1567 		goto err_free_sw_ports;
1568 	}
1569 	sw->cap_plug_events = ret;
1570 
1571 	ret = tb_switch_find_vse_cap(sw, TB_VSE_CAP_LINK_CONTROLLER);
1572 	if (ret > 0)
1573 		sw->cap_lc = ret;
1574 
1575 	/* Root switch is always authorized */
1576 	if (!route)
1577 		sw->authorized = true;
1578 
1579 	device_initialize(&sw->dev);
1580 	sw->dev.parent = parent;
1581 	sw->dev.bus = &tb_bus_type;
1582 	sw->dev.type = &tb_switch_type;
1583 	sw->dev.groups = switch_groups;
1584 	dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
1585 
1586 	return sw;
1587 
1588 err_free_sw_ports:
1589 	kfree(sw->ports);
1590 	kfree(sw);
1591 
1592 	return ERR_PTR(ret);
1593 }
1594 
1595 /**
1596  * tb_switch_alloc_safe_mode() - allocate a switch that is in safe mode
1597  * @tb: Pointer to the owning domain
1598  * @parent: Parent device for this switch
1599  * @route: Route string for this switch
1600  *
1601  * This creates a switch in safe mode. This means the switch pretty much
1602  * lacks all capabilities except DMA configuration port before it is
1603  * flashed with a valid NVM firmware.
1604  *
1605  * The returned switch must be released by calling tb_switch_put().
1606  *
1607  * Return: Pointer to the allocated switch or ERR_PTR() in case of failure
1608  */
1609 struct tb_switch *
tb_switch_alloc_safe_mode(struct tb * tb,struct device * parent,u64 route)1610 tb_switch_alloc_safe_mode(struct tb *tb, struct device *parent, u64 route)
1611 {
1612 	struct tb_switch *sw;
1613 
1614 	sw = kzalloc(sizeof(*sw), GFP_KERNEL);
1615 	if (!sw)
1616 		return ERR_PTR(-ENOMEM);
1617 
1618 	sw->tb = tb;
1619 	sw->config.depth = tb_route_length(route);
1620 	sw->config.route_hi = upper_32_bits(route);
1621 	sw->config.route_lo = lower_32_bits(route);
1622 	sw->safe_mode = true;
1623 
1624 	device_initialize(&sw->dev);
1625 	sw->dev.parent = parent;
1626 	sw->dev.bus = &tb_bus_type;
1627 	sw->dev.type = &tb_switch_type;
1628 	sw->dev.groups = switch_groups;
1629 	dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
1630 
1631 	return sw;
1632 }
1633 
1634 /**
1635  * tb_switch_configure() - Uploads configuration to the switch
1636  * @sw: Switch to configure
1637  *
1638  * Call this function before the switch is added to the system. It will
1639  * upload configuration to the switch and makes it available for the
1640  * connection manager to use.
1641  *
1642  * Return: %0 in case of success and negative errno in case of failure
1643  */
tb_switch_configure(struct tb_switch * sw)1644 int tb_switch_configure(struct tb_switch *sw)
1645 {
1646 	struct tb *tb = sw->tb;
1647 	u64 route;
1648 	int ret;
1649 
1650 	route = tb_route(sw);
1651 	tb_dbg(tb, "initializing Switch at %#llx (depth: %d, up port: %d)\n",
1652 	       route, tb_route_length(route), sw->config.upstream_port_number);
1653 
1654 	if (sw->config.vendor_id != PCI_VENDOR_ID_INTEL)
1655 		tb_sw_warn(sw, "unknown switch vendor id %#x\n",
1656 			   sw->config.vendor_id);
1657 
1658 	sw->config.enabled = 1;
1659 
1660 	/* upload configuration */
1661 	ret = tb_sw_write(sw, 1 + (u32 *)&sw->config, TB_CFG_SWITCH, 1, 3);
1662 	if (ret)
1663 		return ret;
1664 
1665 	ret = tb_lc_configure_link(sw);
1666 	if (ret)
1667 		return ret;
1668 
1669 	return tb_plug_events_active(sw, true);
1670 }
1671 
tb_switch_set_uuid(struct tb_switch * sw)1672 static int tb_switch_set_uuid(struct tb_switch *sw)
1673 {
1674 	u32 uuid[4];
1675 	int ret;
1676 
1677 	if (sw->uuid)
1678 		return 0;
1679 
1680 	/*
1681 	 * The newer controllers include fused UUID as part of link
1682 	 * controller specific registers
1683 	 */
1684 	ret = tb_lc_read_uuid(sw, uuid);
1685 	if (ret) {
1686 		/*
1687 		 * ICM generates UUID based on UID and fills the upper
1688 		 * two words with ones. This is not strictly following
1689 		 * UUID format but we want to be compatible with it so
1690 		 * we do the same here.
1691 		 */
1692 		uuid[0] = sw->uid & 0xffffffff;
1693 		uuid[1] = (sw->uid >> 32) & 0xffffffff;
1694 		uuid[2] = 0xffffffff;
1695 		uuid[3] = 0xffffffff;
1696 	}
1697 
1698 	sw->uuid = kmemdup(uuid, sizeof(uuid), GFP_KERNEL);
1699 	if (!sw->uuid)
1700 		return -ENOMEM;
1701 	return 0;
1702 }
1703 
tb_switch_add_dma_port(struct tb_switch * sw)1704 static int tb_switch_add_dma_port(struct tb_switch *sw)
1705 {
1706 	u32 status;
1707 	int ret;
1708 
1709 	switch (sw->generation) {
1710 	case 2:
1711 		/* Only root switch can be upgraded */
1712 		if (tb_route(sw))
1713 			return 0;
1714 
1715 		/* fallthrough */
1716 	case 3:
1717 		ret = tb_switch_set_uuid(sw);
1718 		if (ret)
1719 			return ret;
1720 		break;
1721 
1722 	default:
1723 		/*
1724 		 * DMA port is the only thing available when the switch
1725 		 * is in safe mode.
1726 		 */
1727 		if (!sw->safe_mode)
1728 			return 0;
1729 		break;
1730 	}
1731 
1732 	/* Root switch DMA port requires running firmware */
1733 	if (!tb_route(sw) && sw->config.enabled)
1734 		return 0;
1735 
1736 	sw->dma_port = dma_port_alloc(sw);
1737 	if (!sw->dma_port)
1738 		return 0;
1739 
1740 	if (sw->no_nvm_upgrade)
1741 		return 0;
1742 
1743 	/*
1744 	 * If there is status already set then authentication failed
1745 	 * when the dma_port_flash_update_auth() returned. Power cycling
1746 	 * is not needed (it was done already) so only thing we do here
1747 	 * is to unblock runtime PM of the root port.
1748 	 */
1749 	nvm_get_auth_status(sw, &status);
1750 	if (status) {
1751 		if (!tb_route(sw))
1752 			nvm_authenticate_complete(sw);
1753 		return 0;
1754 	}
1755 
1756 	/*
1757 	 * Check status of the previous flash authentication. If there
1758 	 * is one we need to power cycle the switch in any case to make
1759 	 * it functional again.
1760 	 */
1761 	ret = dma_port_flash_update_auth_status(sw->dma_port, &status);
1762 	if (ret <= 0)
1763 		return ret;
1764 
1765 	/* Now we can allow root port to suspend again */
1766 	if (!tb_route(sw))
1767 		nvm_authenticate_complete(sw);
1768 
1769 	if (status) {
1770 		tb_sw_info(sw, "switch flash authentication failed\n");
1771 		nvm_set_auth_status(sw, status);
1772 	}
1773 
1774 	tb_sw_info(sw, "power cycling the switch now\n");
1775 	dma_port_power_cycle(sw->dma_port);
1776 
1777 	/*
1778 	 * We return error here which causes the switch adding failure.
1779 	 * It should appear back after power cycle is complete.
1780 	 */
1781 	return -ESHUTDOWN;
1782 }
1783 
1784 /**
1785  * tb_switch_add() - Add a switch to the domain
1786  * @sw: Switch to add
1787  *
1788  * This is the last step in adding switch to the domain. It will read
1789  * identification information from DROM and initializes ports so that
1790  * they can be used to connect other switches. The switch will be
1791  * exposed to the userspace when this function successfully returns. To
1792  * remove and release the switch, call tb_switch_remove().
1793  *
1794  * Return: %0 in case of success and negative errno in case of failure
1795  */
tb_switch_add(struct tb_switch * sw)1796 int tb_switch_add(struct tb_switch *sw)
1797 {
1798 	int i, ret;
1799 
1800 	/*
1801 	 * Initialize DMA control port now before we read DROM. Recent
1802 	 * host controllers have more complete DROM on NVM that includes
1803 	 * vendor and model identification strings which we then expose
1804 	 * to the userspace. NVM can be accessed through DMA
1805 	 * configuration based mailbox.
1806 	 */
1807 	ret = tb_switch_add_dma_port(sw);
1808 	if (ret)
1809 		return ret;
1810 
1811 	if (!sw->safe_mode) {
1812 		/* read drom */
1813 		ret = tb_drom_read(sw);
1814 		if (ret) {
1815 			tb_sw_warn(sw, "tb_eeprom_read_rom failed\n");
1816 			return ret;
1817 		}
1818 		tb_sw_dbg(sw, "uid: %#llx\n", sw->uid);
1819 
1820 		ret = tb_switch_set_uuid(sw);
1821 		if (ret)
1822 			return ret;
1823 
1824 		for (i = 0; i <= sw->config.max_port_number; i++) {
1825 			if (sw->ports[i].disabled) {
1826 				tb_port_dbg(&sw->ports[i], "disabled by eeprom\n");
1827 				continue;
1828 			}
1829 			ret = tb_init_port(&sw->ports[i]);
1830 			if (ret)
1831 				return ret;
1832 		}
1833 	}
1834 
1835 	ret = device_add(&sw->dev);
1836 	if (ret)
1837 		return ret;
1838 
1839 	if (tb_route(sw)) {
1840 		dev_info(&sw->dev, "new device found, vendor=%#x device=%#x\n",
1841 			 sw->vendor, sw->device);
1842 		if (sw->vendor_name && sw->device_name)
1843 			dev_info(&sw->dev, "%s %s\n", sw->vendor_name,
1844 				 sw->device_name);
1845 	}
1846 
1847 	ret = tb_switch_nvm_add(sw);
1848 	if (ret) {
1849 		device_del(&sw->dev);
1850 		return ret;
1851 	}
1852 
1853 	pm_runtime_set_active(&sw->dev);
1854 	if (sw->rpm) {
1855 		pm_runtime_set_autosuspend_delay(&sw->dev, TB_AUTOSUSPEND_DELAY);
1856 		pm_runtime_use_autosuspend(&sw->dev);
1857 		pm_runtime_mark_last_busy(&sw->dev);
1858 		pm_runtime_enable(&sw->dev);
1859 		pm_request_autosuspend(&sw->dev);
1860 	}
1861 
1862 	return 0;
1863 }
1864 
1865 /**
1866  * tb_switch_remove() - Remove and release a switch
1867  * @sw: Switch to remove
1868  *
1869  * This will remove the switch from the domain and release it after last
1870  * reference count drops to zero. If there are switches connected below
1871  * this switch, they will be removed as well.
1872  */
tb_switch_remove(struct tb_switch * sw)1873 void tb_switch_remove(struct tb_switch *sw)
1874 {
1875 	int i;
1876 
1877 	if (sw->rpm) {
1878 		pm_runtime_get_sync(&sw->dev);
1879 		pm_runtime_disable(&sw->dev);
1880 	}
1881 
1882 	/* port 0 is the switch itself and never has a remote */
1883 	for (i = 1; i <= sw->config.max_port_number; i++) {
1884 		if (tb_port_has_remote(&sw->ports[i])) {
1885 			tb_switch_remove(sw->ports[i].remote->sw);
1886 			sw->ports[i].remote = NULL;
1887 		} else if (sw->ports[i].xdomain) {
1888 			tb_xdomain_remove(sw->ports[i].xdomain);
1889 			sw->ports[i].xdomain = NULL;
1890 		}
1891 	}
1892 
1893 	if (!sw->is_unplugged)
1894 		tb_plug_events_active(sw, false);
1895 	tb_lc_unconfigure_link(sw);
1896 
1897 	tb_switch_nvm_remove(sw);
1898 
1899 	if (tb_route(sw))
1900 		dev_info(&sw->dev, "device disconnected\n");
1901 	device_unregister(&sw->dev);
1902 }
1903 
1904 /**
1905  * tb_sw_set_unplugged() - set is_unplugged on switch and downstream switches
1906  */
tb_sw_set_unplugged(struct tb_switch * sw)1907 void tb_sw_set_unplugged(struct tb_switch *sw)
1908 {
1909 	int i;
1910 	if (sw == sw->tb->root_switch) {
1911 		tb_sw_WARN(sw, "cannot unplug root switch\n");
1912 		return;
1913 	}
1914 	if (sw->is_unplugged) {
1915 		tb_sw_WARN(sw, "is_unplugged already set\n");
1916 		return;
1917 	}
1918 	sw->is_unplugged = true;
1919 	for (i = 0; i <= sw->config.max_port_number; i++) {
1920 		if (tb_port_has_remote(&sw->ports[i]))
1921 			tb_sw_set_unplugged(sw->ports[i].remote->sw);
1922 		else if (sw->ports[i].xdomain)
1923 			sw->ports[i].xdomain->is_unplugged = true;
1924 	}
1925 }
1926 
tb_switch_resume(struct tb_switch * sw)1927 int tb_switch_resume(struct tb_switch *sw)
1928 {
1929 	int i, err;
1930 	tb_sw_dbg(sw, "resuming switch\n");
1931 
1932 	/*
1933 	 * Check for UID of the connected switches except for root
1934 	 * switch which we assume cannot be removed.
1935 	 */
1936 	if (tb_route(sw)) {
1937 		u64 uid;
1938 
1939 		/*
1940 		 * Check first that we can still read the switch config
1941 		 * space. It may be that there is now another domain
1942 		 * connected.
1943 		 */
1944 		err = tb_cfg_get_upstream_port(sw->tb->ctl, tb_route(sw));
1945 		if (err < 0) {
1946 			tb_sw_info(sw, "switch not present anymore\n");
1947 			return err;
1948 		}
1949 
1950 		err = tb_drom_read_uid_only(sw, &uid);
1951 		if (err) {
1952 			tb_sw_warn(sw, "uid read failed\n");
1953 			return err;
1954 		}
1955 		if (sw->uid != uid) {
1956 			tb_sw_info(sw,
1957 				"changed while suspended (uid %#llx -> %#llx)\n",
1958 				sw->uid, uid);
1959 			return -ENODEV;
1960 		}
1961 	}
1962 
1963 	/* upload configuration */
1964 	err = tb_sw_write(sw, 1 + (u32 *) &sw->config, TB_CFG_SWITCH, 1, 3);
1965 	if (err)
1966 		return err;
1967 
1968 	err = tb_lc_configure_link(sw);
1969 	if (err)
1970 		return err;
1971 
1972 	err = tb_plug_events_active(sw, true);
1973 	if (err)
1974 		return err;
1975 
1976 	/* check for surviving downstream switches */
1977 	for (i = 1; i <= sw->config.max_port_number; i++) {
1978 		struct tb_port *port = &sw->ports[i];
1979 
1980 		if (!tb_port_has_remote(port) && !port->xdomain)
1981 			continue;
1982 
1983 		if (tb_wait_for_port(port, true) <= 0) {
1984 			tb_port_warn(port,
1985 				     "lost during suspend, disconnecting\n");
1986 			if (tb_port_has_remote(port))
1987 				tb_sw_set_unplugged(port->remote->sw);
1988 			else if (port->xdomain)
1989 				port->xdomain->is_unplugged = true;
1990 		} else if (tb_port_has_remote(port)) {
1991 			if (tb_switch_resume(port->remote->sw)) {
1992 				tb_port_warn(port,
1993 					     "lost during suspend, disconnecting\n");
1994 				tb_sw_set_unplugged(port->remote->sw);
1995 			}
1996 		}
1997 	}
1998 	return 0;
1999 }
2000 
tb_switch_suspend(struct tb_switch * sw)2001 void tb_switch_suspend(struct tb_switch *sw)
2002 {
2003 	int i, err;
2004 	err = tb_plug_events_active(sw, false);
2005 	if (err)
2006 		return;
2007 
2008 	for (i = 1; i <= sw->config.max_port_number; i++) {
2009 		if (tb_port_has_remote(&sw->ports[i]))
2010 			tb_switch_suspend(sw->ports[i].remote->sw);
2011 	}
2012 
2013 	tb_lc_set_sleep(sw);
2014 }
2015 
2016 struct tb_sw_lookup {
2017 	struct tb *tb;
2018 	u8 link;
2019 	u8 depth;
2020 	const uuid_t *uuid;
2021 	u64 route;
2022 };
2023 
tb_switch_match(struct device * dev,const void * data)2024 static int tb_switch_match(struct device *dev, const void *data)
2025 {
2026 	struct tb_switch *sw = tb_to_switch(dev);
2027 	const struct tb_sw_lookup *lookup = data;
2028 
2029 	if (!sw)
2030 		return 0;
2031 	if (sw->tb != lookup->tb)
2032 		return 0;
2033 
2034 	if (lookup->uuid)
2035 		return !memcmp(sw->uuid, lookup->uuid, sizeof(*lookup->uuid));
2036 
2037 	if (lookup->route) {
2038 		return sw->config.route_lo == lower_32_bits(lookup->route) &&
2039 		       sw->config.route_hi == upper_32_bits(lookup->route);
2040 	}
2041 
2042 	/* Root switch is matched only by depth */
2043 	if (!lookup->depth)
2044 		return !sw->depth;
2045 
2046 	return sw->link == lookup->link && sw->depth == lookup->depth;
2047 }
2048 
2049 /**
2050  * tb_switch_find_by_link_depth() - Find switch by link and depth
2051  * @tb: Domain the switch belongs
2052  * @link: Link number the switch is connected
2053  * @depth: Depth of the switch in link
2054  *
2055  * Returned switch has reference count increased so the caller needs to
2056  * call tb_switch_put() when done with the switch.
2057  */
tb_switch_find_by_link_depth(struct tb * tb,u8 link,u8 depth)2058 struct tb_switch *tb_switch_find_by_link_depth(struct tb *tb, u8 link, u8 depth)
2059 {
2060 	struct tb_sw_lookup lookup;
2061 	struct device *dev;
2062 
2063 	memset(&lookup, 0, sizeof(lookup));
2064 	lookup.tb = tb;
2065 	lookup.link = link;
2066 	lookup.depth = depth;
2067 
2068 	dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
2069 	if (dev)
2070 		return tb_to_switch(dev);
2071 
2072 	return NULL;
2073 }
2074 
2075 /**
2076  * tb_switch_find_by_uuid() - Find switch by UUID
2077  * @tb: Domain the switch belongs
2078  * @uuid: UUID to look for
2079  *
2080  * Returned switch has reference count increased so the caller needs to
2081  * call tb_switch_put() when done with the switch.
2082  */
tb_switch_find_by_uuid(struct tb * tb,const uuid_t * uuid)2083 struct tb_switch *tb_switch_find_by_uuid(struct tb *tb, const uuid_t *uuid)
2084 {
2085 	struct tb_sw_lookup lookup;
2086 	struct device *dev;
2087 
2088 	memset(&lookup, 0, sizeof(lookup));
2089 	lookup.tb = tb;
2090 	lookup.uuid = uuid;
2091 
2092 	dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
2093 	if (dev)
2094 		return tb_to_switch(dev);
2095 
2096 	return NULL;
2097 }
2098 
2099 /**
2100  * tb_switch_find_by_route() - Find switch by route string
2101  * @tb: Domain the switch belongs
2102  * @route: Route string to look for
2103  *
2104  * Returned switch has reference count increased so the caller needs to
2105  * call tb_switch_put() when done with the switch.
2106  */
tb_switch_find_by_route(struct tb * tb,u64 route)2107 struct tb_switch *tb_switch_find_by_route(struct tb *tb, u64 route)
2108 {
2109 	struct tb_sw_lookup lookup;
2110 	struct device *dev;
2111 
2112 	if (!route)
2113 		return tb_switch_get(tb->root_switch);
2114 
2115 	memset(&lookup, 0, sizeof(lookup));
2116 	lookup.tb = tb;
2117 	lookup.route = route;
2118 
2119 	dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
2120 	if (dev)
2121 		return tb_to_switch(dev);
2122 
2123 	return NULL;
2124 }
2125 
tb_switch_exit(void)2126 void tb_switch_exit(void)
2127 {
2128 	ida_destroy(&nvm_ida);
2129 }
2130