xref: /linux/drivers/thunderbolt/xdomain.c (revision 2a31b5378c6db9c4a8d399e5d10d32cd4b732bef)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Thunderbolt XDomain discovery protocol support
4  *
5  * Copyright (C) 2017, Intel Corporation
6  * Authors: Michael Jamet <michael.jamet@intel.com>
7  *          Mika Westerberg <mika.westerberg@linux.intel.com>
8  */
9 
10 #include <linux/device.h>
11 #include <linux/delay.h>
12 #include <linux/kmod.h>
13 #include <linux/module.h>
14 #include <linux/pm_runtime.h>
15 #include <linux/prandom.h>
16 #include <linux/string_helpers.h>
17 #include <linux/utsname.h>
18 #include <linux/uuid.h>
19 #include <linux/workqueue.h>
20 
21 #include "tb.h"
22 
23 #define XDOMAIN_SHORT_TIMEOUT			100	/* ms */
24 #define XDOMAIN_DEFAULT_TIMEOUT			1000	/* ms */
25 #define XDOMAIN_BONDING_TIMEOUT			10000	/* ms */
26 #define XDOMAIN_RETRIES				10
27 #define XDOMAIN_DEFAULT_MAX_HOPID		15
28 
29 enum {
30 	XDOMAIN_STATE_INIT,
31 	XDOMAIN_STATE_UUID,
32 	XDOMAIN_STATE_LINK_STATUS,
33 	XDOMAIN_STATE_LINK_STATE_CHANGE,
34 	XDOMAIN_STATE_LINK_STATUS2,
35 	XDOMAIN_STATE_BONDING_UUID_LOW,
36 	XDOMAIN_STATE_BONDING_UUID_HIGH,
37 	XDOMAIN_STATE_PROPERTIES,
38 	XDOMAIN_STATE_ENUMERATED,
39 	XDOMAIN_STATE_ERROR,
40 };
41 
42 static const char * const state_names[] = {
43 	[XDOMAIN_STATE_INIT] = "INIT",
44 	[XDOMAIN_STATE_UUID] = "UUID",
45 	[XDOMAIN_STATE_LINK_STATUS] = "LINK_STATUS",
46 	[XDOMAIN_STATE_LINK_STATE_CHANGE] = "LINK_STATE_CHANGE",
47 	[XDOMAIN_STATE_LINK_STATUS2] = "LINK_STATUS2",
48 	[XDOMAIN_STATE_BONDING_UUID_LOW] = "BONDING_UUID_LOW",
49 	[XDOMAIN_STATE_BONDING_UUID_HIGH] = "BONDING_UUID_HIGH",
50 	[XDOMAIN_STATE_PROPERTIES] = "PROPERTIES",
51 	[XDOMAIN_STATE_ENUMERATED] = "ENUMERATED",
52 	[XDOMAIN_STATE_ERROR] = "ERROR",
53 };
54 
55 struct xdomain_request_work {
56 	struct work_struct work;
57 	struct tb_xdp_header *pkg;
58 	size_t pkg_len;
59 	struct tb *tb;
60 };
61 
62 static bool tb_xdomain_enabled = true;
63 module_param_named(xdomain, tb_xdomain_enabled, bool, 0444);
64 MODULE_PARM_DESC(xdomain, "allow XDomain protocol (default: true)");
65 
66 /*
67  * Serializes access to the properties and protocol handlers below. If
68  * you need to take both this lock and the struct tb_xdomain lock, take
69  * this one first.
70  */
71 static DEFINE_MUTEX(xdomain_lock);
72 
73 /* Properties exposed to the remote domains */
74 static struct tb_property_dir *xdomain_property_dir;
75 static u32 xdomain_property_block_gen;
76 
77 /* Additional protocol handlers */
78 static LIST_HEAD(protocol_handlers);
79 
80 /* UUID for XDomain discovery protocol: b638d70e-42ff-40bb-97c2-90e2c0b2ff07 */
81 static const uuid_t tb_xdp_uuid =
82 	UUID_INIT(0xb638d70e, 0x42ff, 0x40bb,
83 		  0x97, 0xc2, 0x90, 0xe2, 0xc0, 0xb2, 0xff, 0x07);
84 
85 bool tb_is_xdomain_enabled(void)
86 {
87 	return tb_xdomain_enabled && tb_acpi_is_xdomain_allowed();
88 }
89 
90 static bool tb_xdomain_match(const struct tb_cfg_request *req,
91 			     const struct ctl_pkg *pkg)
92 {
93 	switch (pkg->frame.eof) {
94 	case TB_CFG_PKG_ERROR:
95 		return true;
96 
97 	case TB_CFG_PKG_XDOMAIN_RESP: {
98 		const struct tb_xdp_header *res_hdr = pkg->buffer;
99 		const struct tb_xdp_header *req_hdr = req->request;
100 
101 		if (pkg->frame.size < req->response_size / 4)
102 			return false;
103 
104 		/* Make sure route matches */
105 		if ((res_hdr->xd_hdr.route_hi & ~BIT(31)) !=
106 		     req_hdr->xd_hdr.route_hi)
107 			return false;
108 		if ((res_hdr->xd_hdr.route_lo) != req_hdr->xd_hdr.route_lo)
109 			return false;
110 
111 		/* Check that the XDomain protocol matches */
112 		if (!uuid_equal(&res_hdr->uuid, &req_hdr->uuid))
113 			return false;
114 
115 		return true;
116 	}
117 
118 	default:
119 		return false;
120 	}
121 }
122 
123 static bool tb_xdomain_copy(struct tb_cfg_request *req,
124 			    const struct ctl_pkg *pkg)
125 {
126 	size_t len = min_t(size_t, pkg->frame.size, req->response_size);
127 
128 	memcpy(req->response, pkg->buffer, len);
129 	req->result.err = 0;
130 	return true;
131 }
132 
133 static void response_ready(void *data)
134 {
135 	tb_cfg_request_put(data);
136 }
137 
138 static int __tb_xdomain_response(struct tb_ctl *ctl, const void *response,
139 				 size_t size, enum tb_cfg_pkg_type type)
140 {
141 	struct tb_cfg_request *req;
142 	int ret;
143 
144 	req = tb_cfg_request_alloc();
145 	if (!req)
146 		return -ENOMEM;
147 
148 	req->match = tb_xdomain_match;
149 	req->copy = tb_xdomain_copy;
150 	req->request = response;
151 	req->request_size = size;
152 	req->request_type = type;
153 
154 	ret = tb_cfg_request(ctl, req, response_ready, req);
155 	if (ret)
156 		tb_cfg_request_put(req);
157 
158 	return ret;
159 }
160 
161 /**
162  * tb_xdomain_response() - Send a XDomain response message
163  * @xd: XDomain to send the message
164  * @response: Response to send
165  * @size: Size of the response
166  * @type: PDF type of the response
167  *
168  * This can be used to send a XDomain response message to the other
169  * domain. No response for the message is expected.
170  *
171  * Return: %0 on success, negative errno otherwise.
172  */
173 int tb_xdomain_response(struct tb_xdomain *xd, const void *response,
174 			size_t size, enum tb_cfg_pkg_type type)
175 {
176 	return __tb_xdomain_response(xd->tb->ctl, response, size, type);
177 }
178 EXPORT_SYMBOL_GPL(tb_xdomain_response);
179 
180 static int __tb_xdomain_request(struct tb_ctl *ctl, const void *request,
181 	size_t request_size, enum tb_cfg_pkg_type request_type, void *response,
182 	size_t response_size, enum tb_cfg_pkg_type response_type,
183 	unsigned int timeout_msec)
184 {
185 	struct tb_cfg_request *req;
186 	struct tb_cfg_result res;
187 
188 	req = tb_cfg_request_alloc();
189 	if (!req)
190 		return -ENOMEM;
191 
192 	req->match = tb_xdomain_match;
193 	req->copy = tb_xdomain_copy;
194 	req->request = request;
195 	req->request_size = request_size;
196 	req->request_type = request_type;
197 	req->response = response;
198 	req->response_size = response_size;
199 	req->response_type = response_type;
200 
201 	res = tb_cfg_request_sync(ctl, req, timeout_msec);
202 
203 	tb_cfg_request_put(req);
204 
205 	return res.err == 1 ? -EIO : res.err;
206 }
207 
208 /**
209  * tb_xdomain_request() - Send a XDomain request
210  * @xd: XDomain to send the request
211  * @request: Request to send
212  * @request_size: Size of the request in bytes
213  * @request_type: PDF type of the request
214  * @response: Response is copied here
215  * @response_size: Expected size of the response in bytes
216  * @response_type: Expected PDF type of the response
217  * @timeout_msec: Timeout in milliseconds to wait for the response
218  *
219  * This function can be used to send XDomain control channel messages to
220  * the other domain. The function waits until the response is received
221  * or when timeout triggers. Whichever comes first.
222  *
223  * Return: %0 on success, negative errno otherwise.
224  */
225 int tb_xdomain_request(struct tb_xdomain *xd, const void *request,
226 	size_t request_size, enum tb_cfg_pkg_type request_type,
227 	void *response, size_t response_size,
228 	enum tb_cfg_pkg_type response_type, unsigned int timeout_msec)
229 {
230 	return __tb_xdomain_request(xd->tb->ctl, request, request_size,
231 				    request_type, response, response_size,
232 				    response_type, timeout_msec);
233 }
234 EXPORT_SYMBOL_GPL(tb_xdomain_request);
235 
236 static inline void tb_xdp_fill_header(struct tb_xdp_header *hdr, u64 route,
237 	u8 sequence, enum tb_xdp_type type, size_t size)
238 {
239 	u32 length_sn;
240 
241 	length_sn = (size - sizeof(hdr->xd_hdr)) / 4;
242 	length_sn |= (sequence << TB_XDOMAIN_SN_SHIFT) & TB_XDOMAIN_SN_MASK;
243 
244 	hdr->xd_hdr.route_hi = upper_32_bits(route);
245 	hdr->xd_hdr.route_lo = lower_32_bits(route);
246 	hdr->xd_hdr.length_sn = length_sn;
247 	hdr->type = type;
248 	memcpy(&hdr->uuid, &tb_xdp_uuid, sizeof(tb_xdp_uuid));
249 }
250 
251 static int tb_xdp_handle_error(const struct tb_xdp_error_response *res)
252 {
253 	if (res->hdr.type != ERROR_RESPONSE)
254 		return 0;
255 
256 	switch (res->error) {
257 	case ERROR_UNKNOWN_PACKET:
258 	case ERROR_UNKNOWN_DOMAIN:
259 		return -EIO;
260 	case ERROR_NOT_SUPPORTED:
261 		return -EOPNOTSUPP;
262 	case ERROR_NOT_READY:
263 		return -EAGAIN;
264 	default:
265 		break;
266 	}
267 
268 	return 0;
269 }
270 
271 static int tb_xdp_uuid_request(struct tb_ctl *ctl, u64 route, int retry,
272 			       uuid_t *uuid, u64 *remote_route)
273 {
274 	struct tb_xdp_uuid_response res;
275 	struct tb_xdp_uuid req;
276 	int ret;
277 
278 	memset(&req, 0, sizeof(req));
279 	tb_xdp_fill_header(&req.hdr, route, retry % 4, UUID_REQUEST,
280 			   sizeof(req));
281 
282 	memset(&res, 0, sizeof(res));
283 	ret = __tb_xdomain_request(ctl, &req, sizeof(req),
284 				   TB_CFG_PKG_XDOMAIN_REQ, &res, sizeof(res),
285 				   TB_CFG_PKG_XDOMAIN_RESP,
286 				   XDOMAIN_DEFAULT_TIMEOUT);
287 	if (ret)
288 		return ret;
289 
290 	ret = tb_xdp_handle_error(&res.err);
291 	if (ret)
292 		return ret;
293 
294 	uuid_copy(uuid, &res.src_uuid);
295 	*remote_route = (u64)res.src_route_hi << 32 | res.src_route_lo;
296 
297 	return 0;
298 }
299 
300 static int tb_xdp_uuid_response(struct tb_ctl *ctl, u64 route, u8 sequence,
301 				const uuid_t *uuid)
302 {
303 	struct tb_xdp_uuid_response res;
304 
305 	memset(&res, 0, sizeof(res));
306 	tb_xdp_fill_header(&res.hdr, route, sequence, UUID_RESPONSE,
307 			   sizeof(res));
308 
309 	uuid_copy(&res.src_uuid, uuid);
310 	res.src_route_hi = upper_32_bits(route);
311 	res.src_route_lo = lower_32_bits(route);
312 
313 	return __tb_xdomain_response(ctl, &res, sizeof(res),
314 				     TB_CFG_PKG_XDOMAIN_RESP);
315 }
316 
317 static int tb_xdp_error_response(struct tb_ctl *ctl, u64 route, u8 sequence,
318 				 enum tb_xdp_error error)
319 {
320 	struct tb_xdp_error_response res;
321 
322 	memset(&res, 0, sizeof(res));
323 	tb_xdp_fill_header(&res.hdr, route, sequence, ERROR_RESPONSE,
324 			   sizeof(res));
325 	res.error = error;
326 
327 	return __tb_xdomain_response(ctl, &res, sizeof(res),
328 				     TB_CFG_PKG_XDOMAIN_RESP);
329 }
330 
331 static int tb_xdp_properties_request(struct tb_ctl *ctl, u64 route,
332 	const uuid_t *src_uuid, const uuid_t *dst_uuid, int retry,
333 	u32 **block, u32 *generation)
334 {
335 	struct tb_xdp_properties_response *res;
336 	struct tb_xdp_properties req;
337 	u16 data_len, len;
338 	size_t total_size;
339 	u32 *data = NULL;
340 	int ret;
341 
342 	total_size = sizeof(*res) + TB_XDP_PROPERTIES_MAX_DATA_LENGTH * 4;
343 	res = kzalloc(total_size, GFP_KERNEL);
344 	if (!res)
345 		return -ENOMEM;
346 
347 	memset(&req, 0, sizeof(req));
348 	tb_xdp_fill_header(&req.hdr, route, retry % 4, PROPERTIES_REQUEST,
349 			   sizeof(req));
350 	memcpy(&req.src_uuid, src_uuid, sizeof(*src_uuid));
351 	memcpy(&req.dst_uuid, dst_uuid, sizeof(*dst_uuid));
352 
353 	data_len = 0;
354 
355 	do {
356 		ret = __tb_xdomain_request(ctl, &req, sizeof(req),
357 					   TB_CFG_PKG_XDOMAIN_REQ, res,
358 					   total_size, TB_CFG_PKG_XDOMAIN_RESP,
359 					   XDOMAIN_DEFAULT_TIMEOUT);
360 		if (ret)
361 			goto err;
362 
363 		ret = tb_xdp_handle_error(&res->err);
364 		if (ret)
365 			goto err;
366 
367 		/*
368 		 * Package length includes the whole payload without the
369 		 * XDomain header. Validate first that the package is at
370 		 * least size of the response structure.
371 		 */
372 		len = res->hdr.xd_hdr.length_sn & TB_XDOMAIN_LENGTH_MASK;
373 		if (len < sizeof(*res) / 4) {
374 			ret = -EINVAL;
375 			goto err;
376 		}
377 
378 		len += sizeof(res->hdr.xd_hdr) / 4;
379 		len -= sizeof(*res) / 4;
380 		if (len > TB_XDP_PROPERTIES_MAX_DATA_LENGTH) {
381 			ret = -EINVAL;
382 			goto err;
383 		}
384 
385 		if (res->offset != req.offset) {
386 			ret = -EINVAL;
387 			goto err;
388 		}
389 
390 		/*
391 		 * First time allocate block that has enough space for
392 		 * the whole properties block.
393 		 */
394 		if (!data) {
395 			data_len = res->data_length;
396 			if (data_len > TB_XDP_PROPERTIES_MAX_LENGTH) {
397 				ret = -E2BIG;
398 				goto err;
399 			}
400 
401 			data = kcalloc(data_len, sizeof(u32), GFP_KERNEL);
402 			if (!data) {
403 				ret = -ENOMEM;
404 				goto err;
405 			}
406 		}
407 
408 		if (req.offset + len > data_len)
409 			len = data_len - req.offset;
410 		memcpy(data + req.offset, res->data, len * 4);
411 		req.offset += len;
412 	} while (!data_len || req.offset < data_len);
413 
414 	*block = data;
415 	*generation = res->generation;
416 
417 	kfree(res);
418 
419 	return data_len;
420 
421 err:
422 	kfree(data);
423 	kfree(res);
424 
425 	return ret;
426 }
427 
428 static int tb_xdp_properties_response(struct tb *tb, struct tb_ctl *ctl,
429 	struct tb_xdomain *xd, u8 sequence, const struct tb_xdp_properties *req)
430 {
431 	struct tb_xdp_properties_response *res;
432 	size_t total_size;
433 	u16 len;
434 	int ret;
435 
436 	/*
437 	 * Currently we expect all requests to be directed to us. The
438 	 * protocol supports forwarding, though which we might add
439 	 * support later on.
440 	 */
441 	if (!uuid_equal(xd->local_uuid, &req->dst_uuid)) {
442 		tb_xdp_error_response(ctl, xd->route, sequence,
443 				      ERROR_UNKNOWN_DOMAIN);
444 		return 0;
445 	}
446 
447 	mutex_lock(&xd->lock);
448 
449 	if (req->offset >= xd->local_property_block_len) {
450 		mutex_unlock(&xd->lock);
451 		return -EINVAL;
452 	}
453 
454 	len = xd->local_property_block_len - req->offset;
455 	len = min_t(u16, len, TB_XDP_PROPERTIES_MAX_DATA_LENGTH);
456 	total_size = sizeof(*res) + len * 4;
457 
458 	res = kzalloc(total_size, GFP_KERNEL);
459 	if (!res) {
460 		mutex_unlock(&xd->lock);
461 		return -ENOMEM;
462 	}
463 
464 	tb_xdp_fill_header(&res->hdr, xd->route, sequence, PROPERTIES_RESPONSE,
465 			   total_size);
466 	res->generation = xd->local_property_block_gen;
467 	res->data_length = xd->local_property_block_len;
468 	res->offset = req->offset;
469 	uuid_copy(&res->src_uuid, xd->local_uuid);
470 	uuid_copy(&res->dst_uuid, &req->src_uuid);
471 	memcpy(res->data, &xd->local_property_block[req->offset], len * 4);
472 
473 	mutex_unlock(&xd->lock);
474 
475 	ret = __tb_xdomain_response(ctl, res, total_size,
476 				    TB_CFG_PKG_XDOMAIN_RESP);
477 
478 	kfree(res);
479 	return ret;
480 }
481 
482 static int tb_xdp_properties_changed_request(struct tb_ctl *ctl, u64 route,
483 					     int retry, const uuid_t *uuid)
484 {
485 	struct tb_xdp_properties_changed_response res;
486 	struct tb_xdp_properties_changed req;
487 	int ret;
488 
489 	memset(&req, 0, sizeof(req));
490 	tb_xdp_fill_header(&req.hdr, route, retry % 4,
491 			   PROPERTIES_CHANGED_REQUEST, sizeof(req));
492 	uuid_copy(&req.src_uuid, uuid);
493 
494 	memset(&res, 0, sizeof(res));
495 	ret = __tb_xdomain_request(ctl, &req, sizeof(req),
496 				   TB_CFG_PKG_XDOMAIN_REQ, &res, sizeof(res),
497 				   TB_CFG_PKG_XDOMAIN_RESP,
498 				   XDOMAIN_DEFAULT_TIMEOUT);
499 	if (ret)
500 		return ret;
501 
502 	return tb_xdp_handle_error(&res.err);
503 }
504 
505 static int
506 tb_xdp_properties_changed_response(struct tb_ctl *ctl, u64 route, u8 sequence)
507 {
508 	struct tb_xdp_properties_changed_response res;
509 
510 	memset(&res, 0, sizeof(res));
511 	tb_xdp_fill_header(&res.hdr, route, sequence,
512 			   PROPERTIES_CHANGED_RESPONSE, sizeof(res));
513 	return __tb_xdomain_response(ctl, &res, sizeof(res),
514 				     TB_CFG_PKG_XDOMAIN_RESP);
515 }
516 
517 static int tb_xdp_link_state_status_request(struct tb_ctl *ctl, u64 route,
518 					    u8 sequence, u8 *slw, u8 *tlw,
519 					    u8 *sls, u8 *tls)
520 {
521 	struct tb_xdp_link_state_status_response res;
522 	struct tb_xdp_link_state_status req;
523 	int ret;
524 
525 	memset(&req, 0, sizeof(req));
526 	tb_xdp_fill_header(&req.hdr, route, sequence, LINK_STATE_STATUS_REQUEST,
527 			   sizeof(req));
528 
529 	memset(&res, 0, sizeof(res));
530 	ret = __tb_xdomain_request(ctl, &req, sizeof(req), TB_CFG_PKG_XDOMAIN_REQ,
531 				   &res, sizeof(res), TB_CFG_PKG_XDOMAIN_RESP,
532 				   XDOMAIN_DEFAULT_TIMEOUT);
533 	if (ret)
534 		return ret;
535 
536 	ret = tb_xdp_handle_error(&res.err);
537 	if (ret)
538 		return ret;
539 
540 	if (res.status != 0)
541 		return -EREMOTEIO;
542 
543 	*slw = res.slw;
544 	*tlw = res.tlw;
545 	*sls = res.sls;
546 	*tls = res.tls;
547 
548 	return 0;
549 }
550 
551 static int tb_xdp_link_state_status_response(struct tb *tb, struct tb_ctl *ctl,
552 					     struct tb_xdomain *xd, u8 sequence,
553 					     u8 slw, u8 sls, u8 tls, u8 tlw)
554 {
555 	struct tb_xdp_link_state_status_response res;
556 
557 	memset(&res, 0, sizeof(res));
558 	tb_xdp_fill_header(&res.hdr, xd->route, sequence,
559 			   LINK_STATE_STATUS_RESPONSE, sizeof(res));
560 
561 	res.slw = slw;
562 	res.sls = sls;
563 	res.tls = tls;
564 	res.tlw = tlw;
565 
566 	return __tb_xdomain_response(ctl, &res, sizeof(res),
567 				     TB_CFG_PKG_XDOMAIN_RESP);
568 }
569 
570 static int tb_xdp_link_state_change_request(struct tb_ctl *ctl, u64 route,
571 					    u8 sequence, u8 tlw, u8 tls)
572 {
573 	struct tb_xdp_link_state_change_response res;
574 	struct tb_xdp_link_state_change req;
575 	int ret;
576 
577 	memset(&req, 0, sizeof(req));
578 	tb_xdp_fill_header(&req.hdr, route, sequence, LINK_STATE_CHANGE_REQUEST,
579 			   sizeof(req));
580 	req.tlw = tlw;
581 	req.tls = tls;
582 
583 	memset(&res, 0, sizeof(res));
584 	ret = __tb_xdomain_request(ctl, &req, sizeof(req), TB_CFG_PKG_XDOMAIN_REQ,
585 				   &res, sizeof(res), TB_CFG_PKG_XDOMAIN_RESP,
586 				   XDOMAIN_DEFAULT_TIMEOUT);
587 	if (ret)
588 		return ret;
589 
590 	ret = tb_xdp_handle_error(&res.err);
591 	if (ret)
592 		return ret;
593 
594 	return res.status != 0 ? -EREMOTEIO : 0;
595 }
596 
597 static int tb_xdp_link_state_change_response(struct tb_ctl *ctl, u64 route,
598 					     u8 sequence, u32 status)
599 {
600 	struct tb_xdp_link_state_change_response res;
601 
602 	memset(&res, 0, sizeof(res));
603 	tb_xdp_fill_header(&res.hdr, route, sequence, LINK_STATE_CHANGE_RESPONSE,
604 			   sizeof(res));
605 
606 	res.status = status;
607 
608 	return __tb_xdomain_response(ctl, &res, sizeof(res),
609 				     TB_CFG_PKG_XDOMAIN_RESP);
610 }
611 
612 /**
613  * tb_register_protocol_handler() - Register protocol handler
614  * @handler: Handler to register
615  *
616  * This allows XDomain service drivers to hook into incoming XDomain
617  * messages. After this function is called the service driver needs to
618  * be able to handle calls to callback whenever a package with the
619  * registered protocol is received.
620  *
621  * Return: %0 on success, negative errno otherwise.
622  */
623 int tb_register_protocol_handler(struct tb_protocol_handler *handler)
624 {
625 	if (!handler->uuid || !handler->callback)
626 		return -EINVAL;
627 	if (uuid_equal(handler->uuid, &tb_xdp_uuid))
628 		return -EINVAL;
629 
630 	mutex_lock(&xdomain_lock);
631 	list_add_tail(&handler->list, &protocol_handlers);
632 	mutex_unlock(&xdomain_lock);
633 
634 	return 0;
635 }
636 EXPORT_SYMBOL_GPL(tb_register_protocol_handler);
637 
638 /**
639  * tb_unregister_protocol_handler() - Unregister protocol handler
640  * @handler: Handler to unregister
641  *
642  * Removes the previously registered protocol handler.
643  */
644 void tb_unregister_protocol_handler(struct tb_protocol_handler *handler)
645 {
646 	mutex_lock(&xdomain_lock);
647 	list_del_init(&handler->list);
648 	mutex_unlock(&xdomain_lock);
649 }
650 EXPORT_SYMBOL_GPL(tb_unregister_protocol_handler);
651 
652 static int update_service_properties(struct device *dev, void *data)
653 {
654 	struct tb_property_dir *root = data;
655 	struct tb_service *svc;
656 	struct tb_property *p;
657 
658 	svc = tb_to_service(dev);
659 	if (!svc)
660 		return 0;
661 
662 	guard(mutex)(&svc->lock);
663 
664 	/*
665 	 * Replace the static service properties with the dynamic one.
666 	 * Typically this is the same but service drivers can add their
667 	 * own dynamic properties here too.
668 	 */
669 	p = tb_property_find(root, svc->key, TB_PROPERTY_TYPE_DIRECTORY);
670 	if (!p)
671 		return 0;
672 	if (svc->local_properties)
673 		return tb_property_merge_dir(p->value.dir,
674 					     svc->local_properties, false);
675 	return 0;
676 }
677 
678 static void update_property_block(struct tb_xdomain *xd)
679 {
680 	mutex_lock(&xdomain_lock);
681 	mutex_lock(&xd->lock);
682 	/*
683 	 * If the local property block is not up-to-date, rebuild it now
684 	 * based on the global property template.
685 	 */
686 	if (!xd->local_property_block ||
687 	    xd->local_property_block_gen < xdomain_property_block_gen) {
688 		struct tb_property_dir *dir;
689 		int ret, block_len;
690 		u32 *block;
691 
692 		dir = tb_property_copy_dir(xdomain_property_dir);
693 		if (!dir) {
694 			dev_warn(&xd->dev, "failed to copy properties\n");
695 			goto out_unlock;
696 		}
697 
698 		/* Fill in non-static properties now */
699 		tb_property_add_text(dir, "deviceid", utsname()->nodename);
700 		tb_property_add_immediate(dir, "maxhopid", xd->local_max_hopid);
701 
702 		/* Add service specific dynamic properties */
703 		device_for_each_child(&xd->dev, dir, update_service_properties);
704 
705 		ret = tb_property_format_dir(dir, NULL, 0);
706 		if (ret < 0) {
707 			dev_warn(&xd->dev, "local property block creation failed\n");
708 			tb_property_free_dir(dir);
709 			goto out_unlock;
710 		}
711 
712 		block_len = ret;
713 		block = kcalloc(block_len, sizeof(*block), GFP_KERNEL);
714 		if (!block) {
715 			tb_property_free_dir(dir);
716 			goto out_unlock;
717 		}
718 
719 		ret = tb_property_format_dir(dir, block, block_len);
720 		if (ret) {
721 			dev_warn(&xd->dev, "property block generation failed\n");
722 			tb_property_free_dir(dir);
723 			kfree(block);
724 			goto out_unlock;
725 		}
726 
727 		tb_property_free_dir(dir);
728 		/* Release the previous block */
729 		kfree(xd->local_property_block);
730 		/* Assign new one */
731 		xd->local_property_block = block;
732 		xd->local_property_block_len = block_len;
733 		xd->local_property_block_gen = xdomain_property_block_gen;
734 	}
735 
736 out_unlock:
737 	mutex_unlock(&xd->lock);
738 	mutex_unlock(&xdomain_lock);
739 }
740 
741 static void start_handshake(struct tb_xdomain *xd)
742 {
743 	xd->state = XDOMAIN_STATE_INIT;
744 	queue_delayed_work(xd->tb->wq, &xd->state_work,
745 			   msecs_to_jiffies(XDOMAIN_SHORT_TIMEOUT));
746 }
747 
748 /* Can be called from state_work */
749 static void __stop_handshake(struct tb_xdomain *xd)
750 {
751 	cancel_delayed_work_sync(&xd->properties_changed_work);
752 	xd->properties_changed_retries = 0;
753 	xd->state_retries = 0;
754 }
755 
756 static void stop_handshake(struct tb_xdomain *xd)
757 {
758 	cancel_delayed_work_sync(&xd->state_work);
759 	__stop_handshake(xd);
760 }
761 
762 static void tb_xdp_handle_request(struct work_struct *work)
763 {
764 	struct xdomain_request_work *xw = container_of(work, typeof(*xw), work);
765 	const struct tb_xdp_header *pkg = xw->pkg;
766 	const struct tb_xdomain_header *xhdr = &pkg->xd_hdr;
767 	size_t pkg_len = xw->pkg_len;
768 	struct tb *tb = xw->tb;
769 	struct tb_ctl *ctl = tb->ctl;
770 	struct tb_xdomain *xd;
771 	const uuid_t *uuid;
772 	int ret = 0;
773 	u32 sequence;
774 	u64 route;
775 
776 	route = ((u64)xhdr->route_hi << 32 | xhdr->route_lo) & ~BIT_ULL(63);
777 	sequence = xhdr->length_sn & TB_XDOMAIN_SN_MASK;
778 	sequence >>= TB_XDOMAIN_SN_SHIFT;
779 
780 	mutex_lock(&tb->lock);
781 	if (tb->root_switch)
782 		uuid = kmemdup(tb->root_switch->uuid, sizeof(*uuid), GFP_KERNEL);
783 	else
784 		uuid = NULL;
785 	mutex_unlock(&tb->lock);
786 
787 	if (!uuid) {
788 		tb_xdp_error_response(ctl, route, sequence, ERROR_NOT_READY);
789 		goto out;
790 	}
791 
792 	xd = tb_xdomain_find_by_route_locked(tb, route);
793 	if (xd)
794 		update_property_block(xd);
795 
796 	switch (pkg->type) {
797 	case PROPERTIES_REQUEST:
798 		tb_dbg(tb, "%llx: received XDomain properties request\n", route);
799 		if (xd && pkg_len >= sizeof(struct tb_xdp_properties)) {
800 			ret = tb_xdp_properties_response(tb, ctl, xd, sequence,
801 				(const struct tb_xdp_properties *)pkg);
802 		}
803 		break;
804 
805 	case PROPERTIES_CHANGED_REQUEST:
806 		tb_dbg(tb, "%llx: received XDomain properties changed request\n",
807 		       route);
808 
809 		ret = tb_xdp_properties_changed_response(ctl, route, sequence);
810 
811 		/*
812 		 * Since the properties have been changed, let's update
813 		 * the xdomain related to this connection as well in
814 		 * case there is a change in services it offers.
815 		 */
816 		if (xd) {
817 			mutex_lock(&xd->lock);
818 			if (!xd->removing && device_is_registered(&xd->dev))
819 				queue_delayed_work(tb->wq, &xd->state_work,
820 						   msecs_to_jiffies(XDOMAIN_SHORT_TIMEOUT));
821 			mutex_unlock(&xd->lock);
822 		}
823 		break;
824 
825 	case UUID_REQUEST_OLD:
826 	case UUID_REQUEST:
827 		tb_dbg(tb, "%llx: received XDomain UUID request\n", route);
828 		ret = tb_xdp_uuid_response(ctl, route, sequence, uuid);
829 		/*
830 		 * If we've stopped the discovery with an error such as
831 		 * timing out, we will restart the handshake now that we
832 		 * received UUID request from the remote host.
833 		 */
834 		if (!ret && xd && xd->state == XDOMAIN_STATE_ERROR) {
835 			mutex_lock(&xd->lock);
836 			if (!xd->removing) {
837 				dev_dbg(&xd->dev, "restarting handshake\n");
838 				start_handshake(xd);
839 			}
840 			mutex_unlock(&xd->lock);
841 		}
842 		break;
843 
844 	case LINK_STATE_STATUS_REQUEST:
845 		tb_dbg(tb, "%llx: received XDomain link state status request\n",
846 		       route);
847 
848 		if (xd) {
849 			struct tb_port *port = tb_xdomain_downstream_port(xd);
850 			u8 slw, sls, tls, tlw;
851 			u32 val[2];
852 
853 			/*
854 			 * Read the adapter supported and target widths
855 			 * and speeds.
856 			 */
857 			ret = tb_port_read(port, val, TB_CFG_PORT,
858 					   port->cap_phy + LANE_ADP_CS_0,
859 					   ARRAY_SIZE(val));
860 			if (ret)
861 				break;
862 
863 			slw = (val[0] & LANE_ADP_CS_0_SUPPORTED_WIDTH_MASK) >>
864 				LANE_ADP_CS_0_SUPPORTED_WIDTH_SHIFT;
865 			sls = (val[0] & LANE_ADP_CS_0_SUPPORTED_SPEED_MASK) >>
866 				LANE_ADP_CS_0_SUPPORTED_SPEED_SHIFT;
867 			tls = val[1] & LANE_ADP_CS_1_TARGET_SPEED_MASK;
868 			tlw = (val[1] & LANE_ADP_CS_1_TARGET_WIDTH_MASK) >>
869 				LANE_ADP_CS_1_TARGET_WIDTH_SHIFT;
870 
871 			/*
872 			 * When we have higher UUID, we are supposed to
873 			 * return ERROR_NOT_READY if the tlw is not yet
874 			 * set according to the Inter-Domain spec for
875 			 * USB4 v2.
876 			 */
877 			if (xd->state == XDOMAIN_STATE_BONDING_UUID_HIGH &&
878 			    xd->target_link_width &&
879 			    xd->target_link_width != tlw) {
880 				tb_dbg(tb, "%llx: target link width not yet set %#x != %#x\n",
881 				       route, tlw, xd->target_link_width);
882 				tb_xdp_error_response(ctl, route, sequence,
883 						      ERROR_NOT_READY);
884 			} else {
885 				tb_dbg(tb, "%llx: replying with target link width set to %#x\n",
886 				       route, tlw);
887 				ret = tb_xdp_link_state_status_response(tb, ctl,
888 					xd, sequence, slw, sls, tls, tlw);
889 			}
890 		} else {
891 			tb_xdp_error_response(ctl, route, sequence,
892 					      ERROR_NOT_READY);
893 		}
894 		break;
895 
896 	case LINK_STATE_CHANGE_REQUEST:
897 		tb_dbg(tb, "%llx: received XDomain link state change request\n",
898 		       route);
899 
900 		if (xd && xd->state == XDOMAIN_STATE_BONDING_UUID_HIGH &&
901 		    pkg_len >= sizeof(struct tb_xdp_link_state_change)) {
902 			const struct tb_xdp_link_state_change *lsc =
903 				(const struct tb_xdp_link_state_change *)pkg;
904 
905 			ret = tb_xdp_link_state_change_response(ctl, route,
906 								sequence, 0);
907 			mutex_lock(&xd->lock);
908 			if (!xd->removing) {
909 				xd->target_link_width = lsc->tlw;
910 				queue_delayed_work(tb->wq, &xd->state_work,
911 						   msecs_to_jiffies(XDOMAIN_SHORT_TIMEOUT));
912 			}
913 			mutex_unlock(&xd->lock);
914 		} else {
915 			tb_xdp_error_response(ctl, route, sequence,
916 					      ERROR_NOT_READY);
917 		}
918 		break;
919 
920 	default:
921 		tb_dbg(tb, "%llx: unknown XDomain request %#x\n", route, pkg->type);
922 		tb_xdp_error_response(ctl, route, sequence,
923 				      ERROR_NOT_SUPPORTED);
924 		break;
925 	}
926 
927 	tb_xdomain_put(xd);
928 
929 	if (ret) {
930 		tb_warn(tb, "failed to send XDomain response for %#x\n",
931 			pkg->type);
932 	}
933 
934 out:
935 	kfree(uuid);
936 	kfree(xw->pkg);
937 	kfree(xw);
938 
939 	tb_domain_put(tb);
940 }
941 
942 static bool
943 tb_xdp_schedule_request(struct tb *tb, const struct tb_xdp_header *hdr,
944 			size_t size)
945 {
946 	struct xdomain_request_work *xw;
947 
948 	xw = kmalloc_obj(*xw);
949 	if (!xw)
950 		return false;
951 
952 	INIT_WORK(&xw->work, tb_xdp_handle_request);
953 	xw->pkg = kmemdup(hdr, size, GFP_KERNEL);
954 	if (!xw->pkg) {
955 		kfree(xw);
956 		return false;
957 	}
958 	xw->pkg_len = size;
959 	xw->tb = tb_domain_get(tb);
960 
961 	schedule_work(&xw->work);
962 	return true;
963 }
964 
965 /**
966  * tb_register_service_driver() - Register XDomain service driver
967  * @drv: Driver to register
968  *
969  * Registers new service driver from @drv to the bus.
970  *
971  * Return: %0 on success, negative errno otherwise.
972  */
973 int tb_register_service_driver(struct tb_service_driver *drv)
974 {
975 	if (!drv->probe)
976 		return -EINVAL;
977 
978 	drv->driver.bus = &tb_bus_type;
979 	return driver_register(&drv->driver);
980 }
981 EXPORT_SYMBOL_GPL(tb_register_service_driver);
982 
983 /**
984  * tb_unregister_service_driver() - Unregister XDomain service driver
985  * @drv: Driver to unregister
986  *
987  * Unregisters XDomain service driver from the bus.
988  */
989 void tb_unregister_service_driver(struct tb_service_driver *drv)
990 {
991 	driver_unregister(&drv->driver);
992 }
993 EXPORT_SYMBOL_GPL(tb_unregister_service_driver);
994 
995 static int update_xdomain(struct device *dev, void *data)
996 {
997 	struct tb_xdomain *xd;
998 
999 	xd = tb_to_xdomain(dev);
1000 	if (xd) {
1001 		mutex_lock(&xd->lock);
1002 		if (!xd->removing)
1003 			queue_delayed_work(xd->tb->wq,
1004 					   &xd->properties_changed_work,
1005 					   msecs_to_jiffies(50));
1006 		mutex_unlock(&xd->lock);
1007 	}
1008 
1009 	return 0;
1010 }
1011 
1012 /**
1013  * tb_service_properties_changed() - Notify the other host about changes
1014  * @svc: Service whose properties changed
1015  *
1016  * Notifies the other host that service properties may have been
1017  * changed. This should be called whenever @svc->local_properties is
1018  * updated.
1019  */
1020 void tb_service_properties_changed(struct tb_service *svc)
1021 {
1022 	struct tb_xdomain *xd = tb_service_parent(svc);
1023 
1024 	if (xd->is_unplugged)
1025 		return;
1026 
1027 	scoped_guard(mutex, &xdomain_lock)
1028 		xdomain_property_block_gen++;
1029 	update_xdomain(&xd->dev, NULL);
1030 }
1031 EXPORT_SYMBOL_GPL(tb_service_properties_changed);
1032 
1033 static ssize_t key_show(struct device *dev, struct device_attribute *attr,
1034 			char *buf)
1035 {
1036 	struct tb_service *svc = container_of(dev, struct tb_service, dev);
1037 
1038 	/*
1039 	 * It should be null terminated but anything else is pretty much
1040 	 * allowed.
1041 	 */
1042 	return sysfs_emit(buf, "%*pE\n", (int)strlen(svc->key), svc->key);
1043 }
1044 static DEVICE_ATTR_RO(key);
1045 
1046 static int get_modalias(const struct tb_service *svc, char *buf, size_t size)
1047 {
1048 	return snprintf(buf, size, "tbsvc:k%sp%08Xv%08Xr%08X", svc->key,
1049 			svc->prtcid, svc->prtcvers, svc->prtcrevs);
1050 }
1051 
1052 static ssize_t modalias_show(struct device *dev, struct device_attribute *attr,
1053 			     char *buf)
1054 {
1055 	struct tb_service *svc = container_of(dev, struct tb_service, dev);
1056 
1057 	/* Full buffer size except new line and null termination */
1058 	get_modalias(svc, buf, PAGE_SIZE - 2);
1059 	return strlen(strcat(buf, "\n"));
1060 }
1061 static DEVICE_ATTR_RO(modalias);
1062 
1063 static ssize_t prtcid_show(struct device *dev, struct device_attribute *attr,
1064 			   char *buf)
1065 {
1066 	struct tb_service *svc = container_of(dev, struct tb_service, dev);
1067 
1068 	return sysfs_emit(buf, "%u\n", svc->prtcid);
1069 }
1070 static DEVICE_ATTR_RO(prtcid);
1071 
1072 static ssize_t prtcvers_show(struct device *dev, struct device_attribute *attr,
1073 			     char *buf)
1074 {
1075 	struct tb_service *svc = container_of(dev, struct tb_service, dev);
1076 
1077 	return sysfs_emit(buf, "%u\n", svc->prtcvers);
1078 }
1079 static DEVICE_ATTR_RO(prtcvers);
1080 
1081 static ssize_t prtcrevs_show(struct device *dev, struct device_attribute *attr,
1082 			     char *buf)
1083 {
1084 	struct tb_service *svc = container_of(dev, struct tb_service, dev);
1085 
1086 	return sysfs_emit(buf, "%u\n", svc->prtcrevs);
1087 }
1088 static DEVICE_ATTR_RO(prtcrevs);
1089 
1090 static ssize_t prtcstns_show(struct device *dev, struct device_attribute *attr,
1091 			     char *buf)
1092 {
1093 	struct tb_service *svc = container_of(dev, struct tb_service, dev);
1094 
1095 	return sysfs_emit(buf, "0x%08x\n", svc->prtcstns);
1096 }
1097 static DEVICE_ATTR_RO(prtcstns);
1098 
1099 static struct attribute *tb_service_attrs[] = {
1100 	&dev_attr_key.attr,
1101 	&dev_attr_modalias.attr,
1102 	&dev_attr_prtcid.attr,
1103 	&dev_attr_prtcvers.attr,
1104 	&dev_attr_prtcrevs.attr,
1105 	&dev_attr_prtcstns.attr,
1106 	NULL,
1107 };
1108 
1109 static const struct attribute_group tb_service_attr_group = {
1110 	.attrs = tb_service_attrs,
1111 };
1112 
1113 static const struct attribute_group *tb_service_attr_groups[] = {
1114 	&tb_service_attr_group,
1115 	NULL,
1116 };
1117 
1118 static int tb_service_uevent(const struct device *dev, struct kobj_uevent_env *env)
1119 {
1120 	const struct tb_service *svc = container_of_const(dev, struct tb_service, dev);
1121 	char modalias[64];
1122 
1123 	get_modalias(svc, modalias, sizeof(modalias));
1124 	return add_uevent_var(env, "MODALIAS=%s", modalias);
1125 }
1126 
1127 static void tb_service_release(struct device *dev)
1128 {
1129 	struct tb_service *svc = container_of(dev, struct tb_service, dev);
1130 	struct tb_xdomain *xd = tb_service_parent(svc);
1131 
1132 	tb_property_free_dir(svc->remote_properties);
1133 	ida_free(&xd->service_ids, svc->id);
1134 	kfree(svc->key);
1135 	kfree(svc);
1136 	tb_xdomain_put(xd);
1137 }
1138 
1139 const struct device_type tb_service_type = {
1140 	.name = "thunderbolt_service",
1141 	.groups = tb_service_attr_groups,
1142 	.uevent = tb_service_uevent,
1143 	.release = tb_service_release,
1144 };
1145 EXPORT_SYMBOL_GPL(tb_service_type);
1146 
1147 static void update_service(struct tb_service *svc, struct tb_property *property)
1148 {
1149 	struct tb_property_dir *dir = property->value.dir;
1150 
1151 	guard(mutex)(&svc->lock);
1152 	tb_property_free_dir(svc->remote_properties);
1153 	svc->remote_properties = tb_property_copy_dir(dir);
1154 	kobject_uevent(&svc->dev.kobj, KOBJ_CHANGE);
1155 }
1156 
1157 static void __unregister_service(struct device *dev)
1158 {
1159 	struct tb_service *svc = tb_to_service(dev);
1160 
1161 	tb_service_debugfs_remove(svc);
1162 	device_unregister(&svc->dev);
1163 }
1164 
1165 static int remove_missing_service(struct device *dev, void *data)
1166 {
1167 	struct tb_xdomain *xd = data;
1168 	struct tb_service *svc;
1169 
1170 	svc = tb_to_service(dev);
1171 	if (!svc)
1172 		return 0;
1173 
1174 	if (!tb_property_find(xd->remote_properties, svc->key,
1175 			      TB_PROPERTY_TYPE_DIRECTORY))
1176 		__unregister_service(dev);
1177 
1178 	return 0;
1179 }
1180 
1181 static int find_service(struct device *dev, const void *data)
1182 {
1183 	const struct tb_property *p = data;
1184 	struct tb_service *svc;
1185 
1186 	svc = tb_to_service(dev);
1187 	if (!svc)
1188 		return 0;
1189 
1190 	return !strcmp(svc->key, p->key);
1191 }
1192 
1193 static int populate_service(struct tb_service *svc,
1194 			    struct tb_property *property)
1195 {
1196 	struct tb_property_dir *dir = property->value.dir;
1197 	struct tb_property *p;
1198 
1199 	/* Fill in standard properties */
1200 	p = tb_property_find(dir, "prtcid", TB_PROPERTY_TYPE_VALUE);
1201 	if (p)
1202 		svc->prtcid = p->value.immediate;
1203 	p = tb_property_find(dir, "prtcvers", TB_PROPERTY_TYPE_VALUE);
1204 	if (p)
1205 		svc->prtcvers = p->value.immediate;
1206 	p = tb_property_find(dir, "prtcrevs", TB_PROPERTY_TYPE_VALUE);
1207 	if (p)
1208 		svc->prtcrevs = p->value.immediate;
1209 	p = tb_property_find(dir, "prtcstns", TB_PROPERTY_TYPE_VALUE);
1210 	if (p)
1211 		svc->prtcstns = p->value.immediate;
1212 
1213 	svc->key = kstrdup(property->key, GFP_KERNEL);
1214 	if (!svc->key)
1215 		return -ENOMEM;
1216 
1217 	svc->remote_properties = tb_property_copy_dir(dir);
1218 	if (!svc->remote_properties) {
1219 		kfree(svc->key);
1220 		return -ENOMEM;
1221 	}
1222 
1223 	return 0;
1224 }
1225 
1226 static void enumerate_services(struct tb_xdomain *xd)
1227 {
1228 	struct tb_service *svc;
1229 	struct tb_property *p;
1230 	struct device *dev;
1231 	int id;
1232 
1233 	/*
1234 	 * First remove all services that are not available anymore in
1235 	 * the updated property block.
1236 	 */
1237 	device_for_each_child_reverse(&xd->dev, xd, remove_missing_service);
1238 
1239 	/* Then re-enumerate properties creating new services as we go */
1240 	tb_property_for_each(xd->remote_properties, p) {
1241 		if (p->type != TB_PROPERTY_TYPE_DIRECTORY)
1242 			continue;
1243 
1244 		/* If the service exists already we are fine */
1245 		dev = device_find_child(&xd->dev, p, find_service);
1246 		if (dev) {
1247 			update_service(tb_to_service(dev), p);
1248 			put_device(dev);
1249 			continue;
1250 		}
1251 
1252 		svc = kzalloc_obj(*svc);
1253 		if (!svc)
1254 			break;
1255 
1256 		if (populate_service(svc, p)) {
1257 			kfree(svc);
1258 			break;
1259 		}
1260 
1261 		id = ida_alloc(&xd->service_ids, GFP_KERNEL);
1262 		if (id < 0) {
1263 			kfree(svc->key);
1264 			kfree(svc);
1265 			break;
1266 		}
1267 		svc->id = id;
1268 		svc->dev.bus = &tb_bus_type;
1269 		svc->dev.type = &tb_service_type;
1270 		svc->dev.parent = get_device(&xd->dev);
1271 		mutex_init(&svc->lock);
1272 		dev_set_name(&svc->dev, "%s.%d", dev_name(&xd->dev), svc->id);
1273 
1274 		tb_service_debugfs_init(svc);
1275 
1276 		if (device_register(&svc->dev)) {
1277 			tb_service_debugfs_remove(svc);
1278 			put_device(&svc->dev);
1279 			break;
1280 		}
1281 	}
1282 }
1283 
1284 static int populate_properties(struct tb_xdomain *xd,
1285 			       struct tb_property_dir *dir)
1286 {
1287 	const struct tb_property *p;
1288 
1289 	/* Required properties */
1290 	p = tb_property_find(dir, "deviceid", TB_PROPERTY_TYPE_VALUE);
1291 	if (!p)
1292 		return -EINVAL;
1293 	xd->device = p->value.immediate;
1294 
1295 	p = tb_property_find(dir, "vendorid", TB_PROPERTY_TYPE_VALUE);
1296 	if (!p)
1297 		return -EINVAL;
1298 	xd->vendor = p->value.immediate;
1299 
1300 	p = tb_property_find(dir, "maxhopid", TB_PROPERTY_TYPE_VALUE);
1301 	/*
1302 	 * USB4 inter-domain spec suggests using 15 as HopID if the
1303 	 * other end does not announce it in a property. This is for
1304 	 * TBT3 compatibility.
1305 	 */
1306 	xd->remote_max_hopid = p ? p->value.immediate : XDOMAIN_DEFAULT_MAX_HOPID;
1307 
1308 	kfree(xd->device_name);
1309 	xd->device_name = NULL;
1310 	kfree(xd->vendor_name);
1311 	xd->vendor_name = NULL;
1312 
1313 	/* Optional properties */
1314 	p = tb_property_find(dir, "deviceid", TB_PROPERTY_TYPE_TEXT);
1315 	if (p)
1316 		xd->device_name = kstrdup(p->value.text, GFP_KERNEL);
1317 	p = tb_property_find(dir, "vendorid", TB_PROPERTY_TYPE_TEXT);
1318 	if (p)
1319 		xd->vendor_name = kstrdup(p->value.text, GFP_KERNEL);
1320 
1321 	return 0;
1322 }
1323 
1324 static int tb_xdomain_update_link_attributes(struct tb_xdomain *xd)
1325 {
1326 	bool change = false;
1327 	struct tb_port *port;
1328 	int ret;
1329 
1330 	port = tb_xdomain_downstream_port(xd);
1331 
1332 	ret = tb_port_get_link_speed(port);
1333 	if (ret < 0)
1334 		return ret;
1335 
1336 	if (xd->link_speed != ret)
1337 		change = true;
1338 
1339 	xd->link_speed = ret;
1340 
1341 	ret = tb_port_get_link_width(port);
1342 	if (ret < 0)
1343 		return ret;
1344 
1345 	if (xd->link_width != ret)
1346 		change = true;
1347 
1348 	xd->link_width = ret;
1349 
1350 	if (change)
1351 		kobject_uevent(&xd->dev.kobj, KOBJ_CHANGE);
1352 
1353 	return 0;
1354 }
1355 
1356 static int tb_xdomain_get_uuid(struct tb_xdomain *xd)
1357 {
1358 	struct tb *tb = xd->tb;
1359 	uuid_t uuid;
1360 	u64 route;
1361 	int ret;
1362 
1363 	dev_dbg(&xd->dev, "requesting remote UUID\n");
1364 
1365 	ret = tb_xdp_uuid_request(tb->ctl, xd->route, xd->state_retries, &uuid,
1366 				  &route);
1367 	if (ret < 0) {
1368 		if (xd->state_retries-- > 0) {
1369 			dev_dbg(&xd->dev, "failed to request UUID, retrying\n");
1370 			return -EAGAIN;
1371 		}
1372 		dev_dbg(&xd->dev, "failed to read remote UUID\n");
1373 		return ret;
1374 	}
1375 
1376 	dev_dbg(&xd->dev, "got remote UUID %pUb\n", &uuid);
1377 
1378 	if (uuid_equal(&uuid, xd->local_uuid)) {
1379 		if (route == xd->route)
1380 			dev_dbg(&xd->dev, "loop back detected\n");
1381 		else
1382 			dev_dbg(&xd->dev, "intra-domain loop detected\n");
1383 
1384 		/* Don't bond lanes automatically for loops */
1385 		xd->bonding_possible = false;
1386 	}
1387 
1388 	/*
1389 	 * If the UUID is different, there is another domain connected
1390 	 * so mark this one unplugged and wait for the connection
1391 	 * manager to replace it.
1392 	 */
1393 	if (xd->remote_uuid && !uuid_equal(&uuid, xd->remote_uuid)) {
1394 		dev_dbg(&xd->dev, "remote UUID is different, unplugging\n");
1395 		xd->is_unplugged = true;
1396 		return -ENODEV;
1397 	}
1398 
1399 	/* First time fill in the missing UUID */
1400 	if (!xd->remote_uuid) {
1401 		xd->remote_uuid = kmemdup(&uuid, sizeof(uuid_t), GFP_KERNEL);
1402 		if (!xd->remote_uuid)
1403 			return -ENOMEM;
1404 	}
1405 
1406 	return 0;
1407 }
1408 
1409 static int tb_xdomain_get_link_status(struct tb_xdomain *xd)
1410 {
1411 	struct tb *tb = xd->tb;
1412 	u8 slw, tlw, sls, tls;
1413 	int ret;
1414 
1415 	dev_dbg(&xd->dev, "sending link state status request to %pUb\n",
1416 		xd->remote_uuid);
1417 
1418 	ret = tb_xdp_link_state_status_request(tb->ctl, xd->route,
1419 					       xd->state_retries, &slw, &tlw, &sls,
1420 					       &tls);
1421 	if (ret) {
1422 		if (ret != -EOPNOTSUPP && xd->state_retries-- > 0) {
1423 			dev_dbg(&xd->dev,
1424 				"failed to request remote link status, retrying\n");
1425 			return -EAGAIN;
1426 		}
1427 		dev_dbg(&xd->dev, "failed to receive remote link status\n");
1428 		return ret;
1429 	}
1430 
1431 	dev_dbg(&xd->dev, "remote link supports width %#x speed %#x\n", slw, sls);
1432 
1433 	if (slw < LANE_ADP_CS_0_SUPPORTED_WIDTH_DUAL) {
1434 		dev_dbg(&xd->dev, "remote adapter is single lane only\n");
1435 		return -EOPNOTSUPP;
1436 	}
1437 
1438 	return 0;
1439 }
1440 
1441 static int tb_xdomain_link_state_change(struct tb_xdomain *xd,
1442 					unsigned int width)
1443 {
1444 	struct tb_port *port = tb_xdomain_downstream_port(xd);
1445 	struct tb *tb = xd->tb;
1446 	u8 tlw, tls;
1447 	u32 val;
1448 	int ret;
1449 
1450 	if (width == 2)
1451 		tlw = LANE_ADP_CS_1_TARGET_WIDTH_DUAL;
1452 	else if (width == 1)
1453 		tlw = LANE_ADP_CS_1_TARGET_WIDTH_SINGLE;
1454 	else
1455 		return -EINVAL;
1456 
1457 	/* Use the current target speed */
1458 	ret = tb_port_read(port, &val, TB_CFG_PORT, port->cap_phy + LANE_ADP_CS_1, 1);
1459 	if (ret)
1460 		return ret;
1461 	tls = val & LANE_ADP_CS_1_TARGET_SPEED_MASK;
1462 
1463 	dev_dbg(&xd->dev, "sending link state change request with width %#x speed %#x\n",
1464 		tlw, tls);
1465 
1466 	ret = tb_xdp_link_state_change_request(tb->ctl, xd->route,
1467 					       xd->state_retries, tlw, tls);
1468 	if (ret) {
1469 		if (ret != -EOPNOTSUPP && xd->state_retries-- > 0) {
1470 			dev_dbg(&xd->dev,
1471 				"failed to change remote link state, retrying\n");
1472 			return -EAGAIN;
1473 		}
1474 		dev_err(&xd->dev, "failed request link state change, aborting\n");
1475 		return ret;
1476 	}
1477 
1478 	dev_dbg(&xd->dev, "received link state change response\n");
1479 	return 0;
1480 }
1481 
1482 static int tb_xdomain_bond_lanes_uuid_high(struct tb_xdomain *xd)
1483 {
1484 	unsigned int width, width_mask;
1485 	struct tb_port *port;
1486 	int ret;
1487 
1488 	if (xd->target_link_width == LANE_ADP_CS_1_TARGET_WIDTH_SINGLE) {
1489 		width = TB_LINK_WIDTH_SINGLE;
1490 		width_mask = width;
1491 	} else if (xd->target_link_width == LANE_ADP_CS_1_TARGET_WIDTH_DUAL) {
1492 		width = TB_LINK_WIDTH_DUAL;
1493 		width_mask = width | TB_LINK_WIDTH_ASYM_TX | TB_LINK_WIDTH_ASYM_RX;
1494 	} else {
1495 		if (xd->state_retries-- > 0) {
1496 			dev_dbg(&xd->dev,
1497 				"link state change request not received yet, retrying\n");
1498 			return -EAGAIN;
1499 		}
1500 		dev_dbg(&xd->dev, "timeout waiting for link change request\n");
1501 		return -ETIMEDOUT;
1502 	}
1503 
1504 	port = tb_xdomain_downstream_port(xd);
1505 
1506 	/*
1507 	 * We can't use tb_xdomain_lane_bonding_enable() here because it
1508 	 * is the other side that initiates lane bonding. So here we
1509 	 * just set the width to both lane adapters and wait for the
1510 	 * link to transition bonded.
1511 	 */
1512 	ret = tb_port_set_link_width(port->dual_link_port, width);
1513 	if (ret) {
1514 		tb_port_warn(port->dual_link_port,
1515 			     "failed to set link width to %d\n", width);
1516 		return ret;
1517 	}
1518 
1519 	ret = tb_port_set_link_width(port, width);
1520 	if (ret) {
1521 		tb_port_warn(port, "failed to set link width to %d\n", width);
1522 		return ret;
1523 	}
1524 
1525 	ret = tb_port_wait_for_link_width(port, width_mask,
1526 					  XDOMAIN_BONDING_TIMEOUT);
1527 	if (ret) {
1528 		dev_warn(&xd->dev, "error waiting for link width to become %d\n",
1529 			 width_mask);
1530 		return ret;
1531 	}
1532 
1533 	port->bonded = width > TB_LINK_WIDTH_SINGLE;
1534 	port->dual_link_port->bonded = width > TB_LINK_WIDTH_SINGLE;
1535 
1536 	tb_port_update_credits(port);
1537 	tb_xdomain_update_link_attributes(xd);
1538 
1539 	dev_dbg(&xd->dev, "lane bonding %s\n", str_enabled_disabled(width == 2));
1540 	return 0;
1541 }
1542 
1543 static int tb_xdomain_get_properties(struct tb_xdomain *xd)
1544 {
1545 	struct tb_property_dir *dir;
1546 	struct tb *tb = xd->tb;
1547 	bool update = false;
1548 	u32 *block = NULL;
1549 	u32 gen = 0;
1550 	int ret;
1551 
1552 	dev_dbg(&xd->dev, "requesting remote properties\n");
1553 
1554 	ret = tb_xdp_properties_request(tb->ctl, xd->route, xd->local_uuid,
1555 					xd->remote_uuid, xd->state_retries,
1556 					&block, &gen);
1557 	if (ret < 0) {
1558 		if (xd->state_retries-- > 0) {
1559 			dev_dbg(&xd->dev,
1560 				"failed to request remote properties, retrying\n");
1561 			return -EAGAIN;
1562 		}
1563 		/* Give up now */
1564 		dev_err(&xd->dev, "failed read XDomain properties from %pUb\n",
1565 			xd->remote_uuid);
1566 
1567 		return ret;
1568 	}
1569 
1570 	mutex_lock(&xd->lock);
1571 
1572 	/* Only accept newer generation properties */
1573 	if (xd->remote_properties && gen <= xd->remote_property_block_gen) {
1574 		ret = 0;
1575 		goto err_free_block;
1576 	}
1577 
1578 	dir = tb_property_parse_dir(block, ret);
1579 	if (!dir) {
1580 		dev_err(&xd->dev, "failed to parse XDomain properties\n");
1581 		ret = -ENOMEM;
1582 		goto err_free_block;
1583 	}
1584 
1585 	ret = populate_properties(xd, dir);
1586 	if (ret) {
1587 		dev_err(&xd->dev, "missing XDomain properties in response\n");
1588 		goto err_free_dir;
1589 	}
1590 
1591 	/* Release the existing one */
1592 	if (xd->remote_properties) {
1593 		tb_property_free_dir(xd->remote_properties);
1594 		update = true;
1595 	}
1596 
1597 	xd->remote_properties = dir;
1598 	xd->remote_property_block_gen = gen;
1599 
1600 	tb_xdomain_update_link_attributes(xd);
1601 
1602 	mutex_unlock(&xd->lock);
1603 
1604 	kfree(block);
1605 
1606 	/*
1607 	 * Now the device should be ready enough so we can add it to the
1608 	 * bus and let userspace know about it. If the device is already
1609 	 * registered, we notify the userspace that it has changed.
1610 	 */
1611 	if (!update) {
1612 		/*
1613 		 * Now disable lane 1 if bonding was not enabled. Do
1614 		 * this only if bonding was possible at the beginning
1615 		 * (that is we are the connection manager and there are
1616 		 * two lanes).
1617 		 */
1618 		if (xd->bonding_possible) {
1619 			struct tb_port *port;
1620 
1621 			port = tb_xdomain_downstream_port(xd);
1622 			if (!port->bonded)
1623 				tb_port_disable(port->dual_link_port);
1624 		}
1625 
1626 		dev_dbg(&xd->dev, "current link speed %u.0 Gb/s\n",
1627 			xd->link_speed);
1628 		dev_dbg(&xd->dev, "current link width %s\n",
1629 			tb_width_name(xd->link_width));
1630 
1631 		if (device_add(&xd->dev)) {
1632 			dev_err(&xd->dev, "failed to add XDomain device\n");
1633 			return -ENODEV;
1634 		}
1635 		dev_info(&xd->dev, "new host found, vendor=%#x device=%#x\n",
1636 			 xd->vendor, xd->device);
1637 		if (xd->vendor_name && xd->device_name)
1638 			dev_info(&xd->dev, "%s %s\n", xd->vendor_name,
1639 				 xd->device_name);
1640 
1641 		tb_xdomain_debugfs_init(xd);
1642 	} else {
1643 		kobject_uevent(&xd->dev.kobj, KOBJ_CHANGE);
1644 	}
1645 
1646 	enumerate_services(xd);
1647 	return 0;
1648 
1649 err_free_dir:
1650 	tb_property_free_dir(dir);
1651 err_free_block:
1652 	kfree(block);
1653 	mutex_unlock(&xd->lock);
1654 
1655 	return ret;
1656 }
1657 
1658 static void tb_xdomain_queue_uuid(struct tb_xdomain *xd)
1659 {
1660 	xd->state = XDOMAIN_STATE_UUID;
1661 	xd->state_retries = XDOMAIN_RETRIES;
1662 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1663 			   msecs_to_jiffies(XDOMAIN_SHORT_TIMEOUT));
1664 }
1665 
1666 static void tb_xdomain_queue_link_status(struct tb_xdomain *xd)
1667 {
1668 	xd->state = XDOMAIN_STATE_LINK_STATUS;
1669 	xd->state_retries = XDOMAIN_RETRIES;
1670 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1671 			   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1672 }
1673 
1674 static void tb_xdomain_queue_link_status2(struct tb_xdomain *xd)
1675 {
1676 	xd->state = XDOMAIN_STATE_LINK_STATUS2;
1677 	xd->state_retries = XDOMAIN_RETRIES;
1678 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1679 			   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1680 }
1681 
1682 static void tb_xdomain_queue_bonding(struct tb_xdomain *xd)
1683 {
1684 	if (memcmp(xd->local_uuid, xd->remote_uuid, UUID_SIZE) > 0) {
1685 		dev_dbg(&xd->dev, "we have higher UUID, other side bonds the lanes\n");
1686 		xd->state = XDOMAIN_STATE_BONDING_UUID_HIGH;
1687 	} else {
1688 		dev_dbg(&xd->dev, "we have lower UUID, bonding lanes\n");
1689 		xd->state = XDOMAIN_STATE_LINK_STATE_CHANGE;
1690 	}
1691 
1692 	xd->state_retries = XDOMAIN_RETRIES;
1693 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1694 			   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1695 }
1696 
1697 static void tb_xdomain_queue_bonding_uuid_low(struct tb_xdomain *xd)
1698 {
1699 	xd->state = XDOMAIN_STATE_BONDING_UUID_LOW;
1700 	xd->state_retries = XDOMAIN_RETRIES;
1701 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1702 			   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1703 }
1704 
1705 static void tb_xdomain_queue_properties(struct tb_xdomain *xd)
1706 {
1707 	xd->state = XDOMAIN_STATE_PROPERTIES;
1708 	xd->state_retries = XDOMAIN_RETRIES;
1709 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1710 			   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1711 }
1712 
1713 static void tb_xdomain_queue_properties_changed(struct tb_xdomain *xd)
1714 {
1715 	xd->properties_changed_retries = XDOMAIN_RETRIES;
1716 	queue_delayed_work(xd->tb->wq, &xd->properties_changed_work,
1717 			   msecs_to_jiffies(XDOMAIN_SHORT_TIMEOUT));
1718 }
1719 
1720 static void tb_xdomain_failed(struct tb_xdomain *xd)
1721 {
1722 	xd->state = XDOMAIN_STATE_ERROR;
1723 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1724 			   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1725 }
1726 
1727 static void tb_xdomain_state_work(struct work_struct *work)
1728 {
1729 	struct tb_xdomain *xd = container_of(work, typeof(*xd), state_work.work);
1730 	int ret, state = xd->state;
1731 
1732 	if (WARN_ON_ONCE(state < XDOMAIN_STATE_INIT ||
1733 			 state > XDOMAIN_STATE_ERROR))
1734 		return;
1735 
1736 	dev_dbg(&xd->dev, "running state %s\n", state_names[state]);
1737 
1738 	switch (state) {
1739 	case XDOMAIN_STATE_INIT:
1740 		if (xd->needs_uuid) {
1741 			tb_xdomain_queue_uuid(xd);
1742 		} else {
1743 			tb_xdomain_queue_properties_changed(xd);
1744 			tb_xdomain_queue_properties(xd);
1745 		}
1746 		break;
1747 
1748 	case XDOMAIN_STATE_UUID:
1749 		ret = tb_xdomain_get_uuid(xd);
1750 		if (ret) {
1751 			if (ret == -EAGAIN)
1752 				goto retry_state;
1753 			tb_xdomain_failed(xd);
1754 		} else {
1755 			tb_xdomain_queue_properties_changed(xd);
1756 			if (xd->bonding_possible)
1757 				tb_xdomain_queue_link_status(xd);
1758 			else
1759 				tb_xdomain_queue_properties(xd);
1760 		}
1761 		break;
1762 
1763 	case XDOMAIN_STATE_LINK_STATUS:
1764 		ret = tb_xdomain_get_link_status(xd);
1765 		if (ret) {
1766 			if (ret == -EAGAIN)
1767 				goto retry_state;
1768 
1769 			/*
1770 			 * If any of the lane bonding states fail we skip
1771 			 * bonding completely and try to continue from
1772 			 * reading properties.
1773 			 */
1774 			tb_xdomain_queue_properties(xd);
1775 		} else {
1776 			tb_xdomain_queue_bonding(xd);
1777 		}
1778 		break;
1779 
1780 	case XDOMAIN_STATE_LINK_STATE_CHANGE:
1781 		ret = tb_xdomain_link_state_change(xd, 2);
1782 		if (ret) {
1783 			if (ret == -EAGAIN)
1784 				goto retry_state;
1785 			tb_xdomain_queue_properties(xd);
1786 		} else {
1787 			tb_xdomain_queue_link_status2(xd);
1788 		}
1789 		break;
1790 
1791 	case XDOMAIN_STATE_LINK_STATUS2:
1792 		ret = tb_xdomain_get_link_status(xd);
1793 		if (ret) {
1794 			if (ret == -EAGAIN)
1795 				goto retry_state;
1796 			tb_xdomain_queue_properties(xd);
1797 		} else {
1798 			tb_xdomain_queue_bonding_uuid_low(xd);
1799 		}
1800 		break;
1801 
1802 	case XDOMAIN_STATE_BONDING_UUID_LOW:
1803 		tb_xdomain_lane_bonding_enable(xd);
1804 		tb_xdomain_queue_properties(xd);
1805 		break;
1806 
1807 	case XDOMAIN_STATE_BONDING_UUID_HIGH:
1808 		if (tb_xdomain_bond_lanes_uuid_high(xd) == -EAGAIN)
1809 			goto retry_state;
1810 		tb_xdomain_queue_properties(xd);
1811 		break;
1812 
1813 	case XDOMAIN_STATE_PROPERTIES:
1814 		ret = tb_xdomain_get_properties(xd);
1815 		if (ret) {
1816 			if (ret == -EAGAIN)
1817 				goto retry_state;
1818 			tb_xdomain_failed(xd);
1819 		} else {
1820 			xd->state = XDOMAIN_STATE_ENUMERATED;
1821 		}
1822 		break;
1823 
1824 	case XDOMAIN_STATE_ENUMERATED:
1825 		tb_xdomain_queue_properties(xd);
1826 		break;
1827 
1828 	case XDOMAIN_STATE_ERROR:
1829 		dev_dbg(&xd->dev, "discovery failed, stopping handshake\n");
1830 		__stop_handshake(xd);
1831 		break;
1832 
1833 	default:
1834 		dev_warn(&xd->dev, "unexpected state %d\n", state);
1835 		break;
1836 	}
1837 
1838 	return;
1839 
1840 retry_state:
1841 	queue_delayed_work(xd->tb->wq, &xd->state_work,
1842 			   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1843 }
1844 
1845 static void tb_xdomain_properties_changed(struct work_struct *work)
1846 {
1847 	struct tb_xdomain *xd = container_of(work, typeof(*xd),
1848 					     properties_changed_work.work);
1849 	int ret;
1850 
1851 	dev_dbg(&xd->dev, "sending properties changed notification\n");
1852 
1853 	ret = tb_xdp_properties_changed_request(xd->tb->ctl, xd->route,
1854 				xd->properties_changed_retries, xd->local_uuid);
1855 	if (ret) {
1856 		if (xd->properties_changed_retries-- > 0) {
1857 			dev_dbg(&xd->dev,
1858 				"failed to send properties changed notification, retrying\n");
1859 			queue_delayed_work(xd->tb->wq,
1860 					   &xd->properties_changed_work,
1861 					   msecs_to_jiffies(XDOMAIN_DEFAULT_TIMEOUT));
1862 		}
1863 		dev_err(&xd->dev, "failed to send properties changed notification\n");
1864 		return;
1865 	}
1866 
1867 	xd->properties_changed_retries = XDOMAIN_RETRIES;
1868 }
1869 
1870 static ssize_t device_show(struct device *dev, struct device_attribute *attr,
1871 			   char *buf)
1872 {
1873 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1874 
1875 	return sysfs_emit(buf, "%#x\n", xd->device);
1876 }
1877 static DEVICE_ATTR_RO(device);
1878 
1879 static ssize_t
1880 device_name_show(struct device *dev, struct device_attribute *attr, char *buf)
1881 {
1882 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1883 	int ret;
1884 
1885 	if (mutex_lock_interruptible(&xd->lock))
1886 		return -ERESTARTSYS;
1887 	ret = sysfs_emit(buf, "%s\n", xd->device_name ?: "");
1888 	mutex_unlock(&xd->lock);
1889 
1890 	return ret;
1891 }
1892 static DEVICE_ATTR_RO(device_name);
1893 
1894 static ssize_t maxhopid_show(struct device *dev, struct device_attribute *attr,
1895 			     char *buf)
1896 {
1897 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1898 
1899 	return sysfs_emit(buf, "%d\n", xd->remote_max_hopid);
1900 }
1901 static DEVICE_ATTR_RO(maxhopid);
1902 
1903 static ssize_t vendor_show(struct device *dev, struct device_attribute *attr,
1904 			   char *buf)
1905 {
1906 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1907 
1908 	return sysfs_emit(buf, "%#x\n", xd->vendor);
1909 }
1910 static DEVICE_ATTR_RO(vendor);
1911 
1912 static ssize_t
1913 vendor_name_show(struct device *dev, struct device_attribute *attr, char *buf)
1914 {
1915 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1916 	int ret;
1917 
1918 	if (mutex_lock_interruptible(&xd->lock))
1919 		return -ERESTARTSYS;
1920 	ret = sysfs_emit(buf, "%s\n", xd->vendor_name ?: "");
1921 	mutex_unlock(&xd->lock);
1922 
1923 	return ret;
1924 }
1925 static DEVICE_ATTR_RO(vendor_name);
1926 
1927 static ssize_t unique_id_show(struct device *dev, struct device_attribute *attr,
1928 			      char *buf)
1929 {
1930 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1931 
1932 	return sysfs_emit(buf, "%pUb\n", xd->remote_uuid);
1933 }
1934 static DEVICE_ATTR_RO(unique_id);
1935 
1936 static ssize_t speed_show(struct device *dev, struct device_attribute *attr,
1937 			  char *buf)
1938 {
1939 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1940 
1941 	return sysfs_emit(buf, "%u.0 Gb/s\n", xd->link_speed);
1942 }
1943 
1944 static DEVICE_ATTR(rx_speed, 0444, speed_show, NULL);
1945 static DEVICE_ATTR(tx_speed, 0444, speed_show, NULL);
1946 
1947 static ssize_t rx_lanes_show(struct device *dev, struct device_attribute *attr,
1948 			     char *buf)
1949 {
1950 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1951 	unsigned int width;
1952 
1953 	switch (xd->link_width) {
1954 	case TB_LINK_WIDTH_SINGLE:
1955 	case TB_LINK_WIDTH_ASYM_TX:
1956 		width = 1;
1957 		break;
1958 	case TB_LINK_WIDTH_DUAL:
1959 		width = 2;
1960 		break;
1961 	case TB_LINK_WIDTH_ASYM_RX:
1962 		width = 3;
1963 		break;
1964 	default:
1965 		WARN_ON_ONCE(1);
1966 		return -EINVAL;
1967 	}
1968 
1969 	return sysfs_emit(buf, "%u\n", width);
1970 }
1971 static DEVICE_ATTR(rx_lanes, 0444, rx_lanes_show, NULL);
1972 
1973 static ssize_t tx_lanes_show(struct device *dev, struct device_attribute *attr,
1974 			     char *buf)
1975 {
1976 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
1977 	unsigned int width;
1978 
1979 	switch (xd->link_width) {
1980 	case TB_LINK_WIDTH_SINGLE:
1981 	case TB_LINK_WIDTH_ASYM_RX:
1982 		width = 1;
1983 		break;
1984 	case TB_LINK_WIDTH_DUAL:
1985 		width = 2;
1986 		break;
1987 	case TB_LINK_WIDTH_ASYM_TX:
1988 		width = 3;
1989 		break;
1990 	default:
1991 		WARN_ON_ONCE(1);
1992 		return -EINVAL;
1993 	}
1994 
1995 	return sysfs_emit(buf, "%u\n", width);
1996 }
1997 static DEVICE_ATTR(tx_lanes, 0444, tx_lanes_show, NULL);
1998 
1999 static struct attribute *xdomain_attrs[] = {
2000 	&dev_attr_device.attr,
2001 	&dev_attr_device_name.attr,
2002 	&dev_attr_maxhopid.attr,
2003 	&dev_attr_rx_lanes.attr,
2004 	&dev_attr_rx_speed.attr,
2005 	&dev_attr_tx_lanes.attr,
2006 	&dev_attr_tx_speed.attr,
2007 	&dev_attr_unique_id.attr,
2008 	&dev_attr_vendor.attr,
2009 	&dev_attr_vendor_name.attr,
2010 	NULL,
2011 };
2012 
2013 static const struct attribute_group xdomain_attr_group = {
2014 	.attrs = xdomain_attrs,
2015 };
2016 
2017 static const struct attribute_group *xdomain_attr_groups[] = {
2018 	&xdomain_attr_group,
2019 	NULL,
2020 };
2021 
2022 static void tb_xdomain_release(struct device *dev)
2023 {
2024 	struct tb_xdomain *xd = container_of(dev, struct tb_xdomain, dev);
2025 
2026 	put_device(xd->dev.parent);
2027 
2028 	kfree(xd->local_property_block);
2029 	tb_property_free_dir(xd->remote_properties);
2030 	ida_destroy(&xd->out_hopids);
2031 	ida_destroy(&xd->in_hopids);
2032 	ida_destroy(&xd->service_ids);
2033 
2034 	kfree(xd->local_uuid);
2035 	kfree(xd->remote_uuid);
2036 	kfree(xd->device_name);
2037 	kfree(xd->vendor_name);
2038 	kfree(xd);
2039 }
2040 
2041 static int __maybe_unused tb_xdomain_suspend(struct device *dev)
2042 {
2043 	stop_handshake(tb_to_xdomain(dev));
2044 	return 0;
2045 }
2046 
2047 static int __maybe_unused tb_xdomain_resume(struct device *dev)
2048 {
2049 	start_handshake(tb_to_xdomain(dev));
2050 	return 0;
2051 }
2052 
2053 static const struct dev_pm_ops tb_xdomain_pm_ops = {
2054 	SET_SYSTEM_SLEEP_PM_OPS(tb_xdomain_suspend, tb_xdomain_resume)
2055 };
2056 
2057 const struct device_type tb_xdomain_type = {
2058 	.name = "thunderbolt_xdomain",
2059 	.release = tb_xdomain_release,
2060 	.pm = &tb_xdomain_pm_ops,
2061 };
2062 EXPORT_SYMBOL_GPL(tb_xdomain_type);
2063 
2064 static void tb_xdomain_link_init(struct tb_xdomain *xd, struct tb_port *down)
2065 {
2066 	if (!down->dual_link_port)
2067 		return;
2068 
2069 	/*
2070 	 * Gen 4 links come up already as bonded so only update the port
2071 	 * structures here.
2072 	 */
2073 	if (tb_port_get_link_generation(down) >= 4) {
2074 		down->bonded = true;
2075 		down->dual_link_port->bonded = true;
2076 	} else {
2077 		xd->bonding_possible = true;
2078 	}
2079 }
2080 
2081 static void tb_xdomain_link_exit(struct tb_xdomain *xd)
2082 {
2083 	struct tb_port *down = tb_xdomain_downstream_port(xd);
2084 
2085 	if (!down->dual_link_port)
2086 		return;
2087 
2088 	if (tb_port_get_link_generation(down) >= 4) {
2089 		down->bonded = false;
2090 		down->dual_link_port->bonded = false;
2091 		return;
2092 	}
2093 
2094 	if (!xd->bonding_possible)
2095 		return;
2096 
2097 	if (xd->link_width > TB_LINK_WIDTH_SINGLE) {
2098 		/*
2099 		 * Just return port structures back to way they were and
2100 		 * update credits. No need to update userspace because
2101 		 * the XDomain is removed soon anyway.
2102 		 */
2103 		tb_port_lane_bonding_disable(down);
2104 		tb_port_update_credits(down);
2105 	} else if (down->dual_link_port) {
2106 		/*
2107 		 * Re-enable the lane 1 adapter we disabled at the end
2108 		 * of tb_xdomain_get_properties().
2109 		 */
2110 		tb_port_enable(down->dual_link_port);
2111 	}
2112 }
2113 
2114 /**
2115  * tb_xdomain_alloc() - Allocate new XDomain object
2116  * @tb: Domain where the XDomain belongs
2117  * @parent: Parent device (the switch through which the other domain
2118  *	    is reached).
2119  * @route: Route string used to reach the other domain
2120  * @local_uuid: Our local domain UUID
2121  * @remote_uuid: UUID of the other domain (optional)
2122  *
2123  * Allocates new XDomain structure and returns pointer to that. The
2124  * object must be released by calling tb_xdomain_put().
2125  *
2126  * Return: Pointer to &struct tb_xdomain, %NULL in case of failure.
2127  */
2128 struct tb_xdomain *tb_xdomain_alloc(struct tb *tb, struct device *parent,
2129 				    u64 route, const uuid_t *local_uuid,
2130 				    const uuid_t *remote_uuid)
2131 {
2132 	struct tb_switch *parent_sw = tb_to_switch(parent);
2133 	struct tb_xdomain *xd;
2134 	struct tb_port *down;
2135 
2136 	/* Make sure the downstream domain is accessible */
2137 	down = tb_port_at(route, parent_sw);
2138 	tb_port_unlock(down);
2139 
2140 	xd = kzalloc_obj(*xd);
2141 	if (!xd)
2142 		return NULL;
2143 
2144 	xd->tb = tb;
2145 	xd->route = route;
2146 	xd->local_max_hopid = down->config.max_in_hop_id;
2147 	ida_init(&xd->service_ids);
2148 	ida_init(&xd->in_hopids);
2149 	ida_init(&xd->out_hopids);
2150 	mutex_init(&xd->lock);
2151 	INIT_DELAYED_WORK(&xd->state_work, tb_xdomain_state_work);
2152 	INIT_DELAYED_WORK(&xd->properties_changed_work,
2153 			  tb_xdomain_properties_changed);
2154 	atomic_set(&xd->ntunnels, 0);
2155 
2156 	xd->local_uuid = kmemdup(local_uuid, sizeof(uuid_t), GFP_KERNEL);
2157 	if (!xd->local_uuid)
2158 		goto err_free;
2159 
2160 	if (remote_uuid) {
2161 		xd->remote_uuid = kmemdup(remote_uuid, sizeof(uuid_t),
2162 					  GFP_KERNEL);
2163 		if (!xd->remote_uuid)
2164 			goto err_free_local_uuid;
2165 	} else {
2166 		xd->needs_uuid = true;
2167 
2168 		tb_xdomain_link_init(xd, down);
2169 	}
2170 
2171 	device_initialize(&xd->dev);
2172 	xd->dev.parent = get_device(parent);
2173 	xd->dev.bus = &tb_bus_type;
2174 	xd->dev.type = &tb_xdomain_type;
2175 	xd->dev.groups = xdomain_attr_groups;
2176 	dev_set_name(&xd->dev, "%u-%llx", tb->index, route);
2177 
2178 	dev_dbg(&xd->dev, "local UUID %pUb\n", local_uuid);
2179 	if (remote_uuid)
2180 		dev_dbg(&xd->dev, "remote UUID %pUb\n", remote_uuid);
2181 
2182 	/*
2183 	 * This keeps the DMA powered on as long as we have active
2184 	 * connection to another host.
2185 	 */
2186 	pm_runtime_set_active(&xd->dev);
2187 	pm_runtime_get_noresume(&xd->dev);
2188 	pm_runtime_enable(&xd->dev);
2189 
2190 	return xd;
2191 
2192 err_free_local_uuid:
2193 	kfree(xd->local_uuid);
2194 err_free:
2195 	kfree(xd);
2196 
2197 	return NULL;
2198 }
2199 
2200 /**
2201  * tb_xdomain_add() - Add XDomain to the bus
2202  * @xd: XDomain to add
2203  *
2204  * This function starts XDomain discovery protocol handshake and
2205  * eventually adds the XDomain to the bus. After calling this function
2206  * the caller needs to call tb_xdomain_remove() in order to remove and
2207  * release the object regardless whether the handshake succeeded or not.
2208  */
2209 void tb_xdomain_add(struct tb_xdomain *xd)
2210 {
2211 	/* Start exchanging properties with the other host */
2212 	start_handshake(xd);
2213 }
2214 
2215 static int unregister_service(struct device *dev, void *data)
2216 {
2217 	__unregister_service(dev);
2218 	return 0;
2219 }
2220 
2221 /**
2222  * tb_xdomain_remove() - Remove XDomain
2223  * @xd: XDomain to remove
2224  *
2225  * This will stop all ongoing configuration work. XDomain is not removed
2226  * from the bus if it was added. That needs to be done separately by
2227  * calling tb_xdomain_unregister().
2228  *
2229  * Called with @tb->lock held.
2230  */
2231 void tb_xdomain_remove(struct tb_xdomain *xd)
2232 {
2233 	tb_xdomain_debugfs_remove(xd);
2234 
2235 	mutex_lock(&xd->lock);
2236 	xd->removing = true;
2237 	mutex_unlock(&xd->lock);
2238 
2239 	stop_handshake(xd);
2240 	tb_xdomain_link_exit(xd);
2241 
2242 	if (!device_is_registered(&xd->dev)) {
2243 		/*
2244 		 * Undo runtime PM here explicitly because it is
2245 		 * possible that the XDomain was never added to the bus
2246 		 * and thus device_del() is not called for it
2247 		 * (device_del() would handle this otherwise).
2248 		 */
2249 		pm_runtime_disable(&xd->dev);
2250 		pm_runtime_put_noidle(&xd->dev);
2251 		pm_runtime_set_suspended(&xd->dev);
2252 		put_device(&xd->dev);
2253 	}
2254 }
2255 
2256 /**
2257  * tb_xdomain_unregister() - Unregister XDomain
2258  * @xd: XDomain to unregister
2259  *
2260  * This will unregister the XDomain along with any services from the
2261  * bus. When the last reference to @xd is released the object will be
2262  * released as well.
2263  */
2264 void tb_xdomain_unregister(struct tb_xdomain *xd)
2265 {
2266 	lockdep_assert_not_held(&xd->tb->lock);
2267 
2268 	device_for_each_child_reverse(&xd->dev, xd, unregister_service);
2269 
2270 	dev_info(&xd->dev, "host disconnected\n");
2271 	device_unregister(&xd->dev);
2272 }
2273 
2274 /**
2275  * tb_xdomain_lane_bonding_enable() - Enable lane bonding on XDomain
2276  * @xd: XDomain connection
2277  *
2278  * Lane bonding is disabled by default for XDomains. This function tries
2279  * to enable bonding by first enabling the port and waiting for the CL0
2280  * state.
2281  *
2282  * Return: %0 on success, negative errno otherwise.
2283  */
2284 int tb_xdomain_lane_bonding_enable(struct tb_xdomain *xd)
2285 {
2286 	unsigned int width_mask;
2287 	struct tb_port *port;
2288 	int ret;
2289 
2290 	port = tb_xdomain_downstream_port(xd);
2291 	if (!port->dual_link_port)
2292 		return -ENODEV;
2293 
2294 	ret = tb_port_enable(port->dual_link_port);
2295 	if (ret)
2296 		return ret;
2297 
2298 	ret = tb_wait_for_port(port->dual_link_port, true);
2299 	if (ret < 0)
2300 		return ret;
2301 	if (!ret)
2302 		return -ENOTCONN;
2303 
2304 	ret = tb_port_lane_bonding_enable(port);
2305 	if (ret) {
2306 		tb_port_warn(port, "failed to enable lane bonding\n");
2307 		return ret;
2308 	}
2309 
2310 	/* Any of the widths are all bonded */
2311 	width_mask = TB_LINK_WIDTH_DUAL | TB_LINK_WIDTH_ASYM_TX |
2312 		     TB_LINK_WIDTH_ASYM_RX;
2313 
2314 	ret = tb_port_wait_for_link_width(port, width_mask,
2315 					  XDOMAIN_BONDING_TIMEOUT);
2316 	if (ret) {
2317 		tb_port_warn(port, "failed to enable lane bonding\n");
2318 		return ret;
2319 	}
2320 
2321 	tb_port_update_credits(port);
2322 	tb_xdomain_update_link_attributes(xd);
2323 
2324 	dev_dbg(&xd->dev, "lane bonding enabled\n");
2325 	return 0;
2326 }
2327 EXPORT_SYMBOL_GPL(tb_xdomain_lane_bonding_enable);
2328 
2329 /**
2330  * tb_xdomain_lane_bonding_disable() - Disable lane bonding
2331  * @xd: XDomain connection
2332  *
2333  * Lane bonding is disabled by default for XDomains. If bonding has been
2334  * enabled, this function can be used to disable it.
2335  */
2336 void tb_xdomain_lane_bonding_disable(struct tb_xdomain *xd)
2337 {
2338 	struct tb_port *port;
2339 
2340 	port = tb_xdomain_downstream_port(xd);
2341 	if (port->dual_link_port) {
2342 		int ret;
2343 
2344 		tb_port_lane_bonding_disable(port);
2345 		ret = tb_port_wait_for_link_width(port, TB_LINK_WIDTH_SINGLE, 100);
2346 		if (ret == -ETIMEDOUT)
2347 			tb_port_warn(port, "timeout disabling lane bonding\n");
2348 		tb_port_disable(port->dual_link_port);
2349 		tb_port_update_credits(port);
2350 		tb_xdomain_update_link_attributes(xd);
2351 
2352 		dev_dbg(&xd->dev, "lane bonding disabled\n");
2353 	}
2354 }
2355 EXPORT_SYMBOL_GPL(tb_xdomain_lane_bonding_disable);
2356 
2357 /**
2358  * tb_xdomain_alloc_in_hopid() - Allocate input HopID for tunneling
2359  * @xd: XDomain connection
2360  * @hopid: Preferred HopID or %-1 for next available
2361  *
2362  * Returned HopID is guaranteed to be within range supported by the input
2363  * lane adapter.
2364  * Call tb_xdomain_release_in_hopid() to release the allocated HopID.
2365  *
2366  * Return:
2367  * * Allocated HopID - On success.
2368  * * %-ENOSPC - If there are no more available HopIDs.
2369  * * Negative errno - Another error occurred.
2370  */
2371 int tb_xdomain_alloc_in_hopid(struct tb_xdomain *xd, int hopid)
2372 {
2373 	if (hopid < 0)
2374 		hopid = TB_PATH_MIN_HOPID;
2375 	if (hopid < TB_PATH_MIN_HOPID || hopid > xd->local_max_hopid)
2376 		return -EINVAL;
2377 
2378 	return ida_alloc_range(&xd->in_hopids, hopid, xd->local_max_hopid,
2379 			       GFP_KERNEL);
2380 }
2381 EXPORT_SYMBOL_GPL(tb_xdomain_alloc_in_hopid);
2382 
2383 /**
2384  * tb_xdomain_alloc_out_hopid() - Allocate output HopID for tunneling
2385  * @xd: XDomain connection
2386  * @hopid: Preferred HopID or %-1 for next available
2387  *
2388  * Returned HopID is guaranteed to be within range supported by the
2389  * output lane adapter.
2390  * Call tb_xdomain_release_out_hopid() to release the allocated HopID.
2391  *
2392  * Return:
2393  * * Allocated HopID - On success.
2394  * * %-ENOSPC - If there are no more available HopIDs.
2395  * * Negative errno - Another error occurred.
2396  */
2397 int tb_xdomain_alloc_out_hopid(struct tb_xdomain *xd, int hopid)
2398 {
2399 	if (hopid < 0)
2400 		hopid = TB_PATH_MIN_HOPID;
2401 	if (hopid < TB_PATH_MIN_HOPID || hopid > xd->remote_max_hopid)
2402 		return -EINVAL;
2403 
2404 	return ida_alloc_range(&xd->out_hopids, hopid, xd->remote_max_hopid,
2405 			       GFP_KERNEL);
2406 }
2407 EXPORT_SYMBOL_GPL(tb_xdomain_alloc_out_hopid);
2408 
2409 /**
2410  * tb_xdomain_release_in_hopid() - Release input HopID
2411  * @xd: XDomain connection
2412  * @hopid: HopID to release
2413  */
2414 void tb_xdomain_release_in_hopid(struct tb_xdomain *xd, int hopid)
2415 {
2416 	ida_free(&xd->in_hopids, hopid);
2417 }
2418 EXPORT_SYMBOL_GPL(tb_xdomain_release_in_hopid);
2419 
2420 /**
2421  * tb_xdomain_release_out_hopid() - Release output HopID
2422  * @xd: XDomain connection
2423  * @hopid: HopID to release
2424  */
2425 void tb_xdomain_release_out_hopid(struct tb_xdomain *xd, int hopid)
2426 {
2427 	ida_free(&xd->out_hopids, hopid);
2428 }
2429 EXPORT_SYMBOL_GPL(tb_xdomain_release_out_hopid);
2430 
2431 /**
2432  * tb_xdomain_enable_paths() - Enable DMA paths for XDomain connection
2433  * @xd: XDomain connection
2434  * @transmit_path: HopID we are using to send out packets
2435  * @transmit_ring: DMA ring used to send out packets
2436  * @receive_path: HopID the other end is using to send packets to us
2437  * @receive_ring: DMA ring used to receive packets from @receive_path
2438  *
2439  * The function enables DMA paths accordingly so that after successful
2440  * return the caller can send and receive packets using high-speed DMA
2441  * path. If a transmit or receive path is not needed, pass %-1 for those
2442  * parameters.
2443  *
2444  * Return: %0 on success, negative errno otherwise.
2445  */
2446 int tb_xdomain_enable_paths(struct tb_xdomain *xd, int transmit_path,
2447 			    int transmit_ring, int receive_path,
2448 			    int receive_ring)
2449 {
2450 	int ret;
2451 
2452 	ret = tb_domain_approve_xdomain_paths(xd->tb, xd, transmit_path,
2453 					      transmit_ring, receive_path,
2454 					      receive_ring);
2455 	if (ret)
2456 		return ret;
2457 	atomic_inc(&xd->ntunnels);
2458 	return 0;
2459 }
2460 EXPORT_SYMBOL_GPL(tb_xdomain_enable_paths);
2461 
2462 /**
2463  * tb_xdomain_disable_paths() - Disable DMA paths for XDomain connection
2464  * @xd: XDomain connection
2465  * @transmit_path: HopID we are using to send out packets
2466  * @transmit_ring: DMA ring used to send out packets
2467  * @receive_path: HopID the other end is using to send packets to us
2468  * @receive_ring: DMA ring used to receive packets from @receive_path
2469  *
2470  * This does the opposite of tb_xdomain_enable_paths(). After call to
2471  * this the caller is not expected to use the rings anymore. Passing %-1
2472  * as path/ring parameter means don't care. Normally the callers should
2473  * pass the same values here as they do when paths are enabled.
2474  *
2475  * Return: %0 on success, negative errno otherwise.
2476  */
2477 int tb_xdomain_disable_paths(struct tb_xdomain *xd, int transmit_path,
2478 			     int transmit_ring, int receive_path,
2479 			     int receive_ring)
2480 {
2481 	int ret;
2482 
2483 	ret = tb_domain_disconnect_xdomain_paths(xd->tb, xd, transmit_path,
2484 						 transmit_ring, receive_path,
2485 						 receive_ring);
2486 	if (ret)
2487 		return ret;
2488 	atomic_dec(&xd->ntunnels);
2489 	return 0;
2490 }
2491 EXPORT_SYMBOL_GPL(tb_xdomain_disable_paths);
2492 
2493 struct tb_xdomain_lookup {
2494 	const uuid_t *uuid;
2495 	u8 link;
2496 	u8 depth;
2497 	u64 route;
2498 };
2499 
2500 static struct tb_xdomain *switch_find_xdomain(struct tb_switch *sw,
2501 	const struct tb_xdomain_lookup *lookup)
2502 {
2503 	struct tb_port *port;
2504 
2505 	if (!sw)
2506 		return NULL;
2507 
2508 	tb_switch_for_each_port(sw, port) {
2509 		struct tb_xdomain *xd;
2510 
2511 		if (port->xdomain) {
2512 			xd = port->xdomain;
2513 
2514 			if (lookup->uuid) {
2515 				if (xd->remote_uuid &&
2516 				    uuid_equal(xd->remote_uuid, lookup->uuid))
2517 					return xd;
2518 			} else {
2519 				if (lookup->link && lookup->link == xd->link &&
2520 				    lookup->depth == xd->depth)
2521 					return xd;
2522 				if (lookup->route && lookup->route == xd->route)
2523 					return xd;
2524 			}
2525 		} else if (tb_port_has_remote(port)) {
2526 			xd = switch_find_xdomain(port->remote->sw, lookup);
2527 			if (xd)
2528 				return xd;
2529 		}
2530 	}
2531 
2532 	return NULL;
2533 }
2534 
2535 /**
2536  * tb_xdomain_find_by_uuid() - Find an XDomain by UUID
2537  * @tb: Domain where the XDomain belongs to
2538  * @uuid: UUID to look for
2539  *
2540  * Finds XDomain by walking through the Thunderbolt topology below @tb.
2541  * The returned XDomain will have its reference count increased so the
2542  * caller needs to call tb_xdomain_put() when it is done with the
2543  * object.
2544  *
2545  * This will find all XDomains including the ones that are not yet added
2546  * to the bus (handshake is still in progress).
2547  *
2548  * The caller needs to hold @tb->lock.
2549  *
2550  * Return: Pointer to &struct tb_xdomain or %NULL if not found.
2551  */
2552 struct tb_xdomain *tb_xdomain_find_by_uuid(struct tb *tb, const uuid_t *uuid)
2553 {
2554 	struct tb_xdomain_lookup lookup;
2555 	struct tb_xdomain *xd;
2556 
2557 	memset(&lookup, 0, sizeof(lookup));
2558 	lookup.uuid = uuid;
2559 
2560 	xd = switch_find_xdomain(tb->root_switch, &lookup);
2561 	return tb_xdomain_get(xd);
2562 }
2563 EXPORT_SYMBOL_GPL(tb_xdomain_find_by_uuid);
2564 
2565 /**
2566  * tb_xdomain_find_by_link_depth() - Find an XDomain by link and depth
2567  * @tb: Domain where the XDomain belongs to
2568  * @link: Root switch link number
2569  * @depth: Depth in the link
2570  *
2571  * Finds XDomain by walking through the Thunderbolt topology below @tb.
2572  * The returned XDomain will have its reference count increased so the
2573  * caller needs to call tb_xdomain_put() when it is done with the
2574  * object.
2575  *
2576  * This will find all XDomains including the ones that are not yet added
2577  * to the bus (handshake is still in progress).
2578  *
2579  * The caller needs to hold @tb->lock.
2580  *
2581  * Return: Pointer to &struct tb_xdomain or %NULL if not found.
2582  */
2583 struct tb_xdomain *tb_xdomain_find_by_link_depth(struct tb *tb, u8 link,
2584 						 u8 depth)
2585 {
2586 	struct tb_xdomain_lookup lookup;
2587 	struct tb_xdomain *xd;
2588 
2589 	memset(&lookup, 0, sizeof(lookup));
2590 	lookup.link = link;
2591 	lookup.depth = depth;
2592 
2593 	xd = switch_find_xdomain(tb->root_switch, &lookup);
2594 	return tb_xdomain_get(xd);
2595 }
2596 
2597 /**
2598  * tb_xdomain_find_by_route() - Find an XDomain by route string
2599  * @tb: Domain where the XDomain belongs to
2600  * @route: XDomain route string
2601  *
2602  * Finds XDomain by walking through the Thunderbolt topology below @tb.
2603  * The returned XDomain will have its reference count increased so the
2604  * caller needs to call tb_xdomain_put() when it is done with the
2605  * object.
2606  *
2607  * This will find all XDomains including the ones that are not yet added
2608  * to the bus (handshake is still in progress).
2609  *
2610  * The caller needs to hold @tb->lock.
2611  *
2612  * Return: Pointer to &struct tb_xdomain or %NULL if not found.
2613  */
2614 struct tb_xdomain *tb_xdomain_find_by_route(struct tb *tb, u64 route)
2615 {
2616 	struct tb_xdomain_lookup lookup;
2617 	struct tb_xdomain *xd;
2618 
2619 	memset(&lookup, 0, sizeof(lookup));
2620 	lookup.route = route;
2621 
2622 	xd = switch_find_xdomain(tb->root_switch, &lookup);
2623 	return tb_xdomain_get(xd);
2624 }
2625 EXPORT_SYMBOL_GPL(tb_xdomain_find_by_route);
2626 
2627 bool tb_xdomain_handle_request(struct tb *tb, enum tb_cfg_pkg_type type,
2628 			       const void *buf, size_t size)
2629 {
2630 	const struct tb_protocol_handler *handler, *tmp;
2631 	const struct tb_xdp_header *hdr = buf;
2632 	unsigned int length;
2633 	int ret = 0;
2634 
2635 	/* We expect the packet is at least size of the header */
2636 	length = hdr->xd_hdr.length_sn & TB_XDOMAIN_LENGTH_MASK;
2637 	if (length != size / 4 - sizeof(hdr->xd_hdr) / 4)
2638 		return true;
2639 	if (length < sizeof(*hdr) / 4 - sizeof(hdr->xd_hdr) / 4)
2640 		return true;
2641 
2642 	/*
2643 	 * Handle XDomain discovery protocol packets directly here. For
2644 	 * other protocols (based on their UUID) we call registered
2645 	 * handlers in turn.
2646 	 */
2647 	if (uuid_equal(&hdr->uuid, &tb_xdp_uuid)) {
2648 		if (type == TB_CFG_PKG_XDOMAIN_REQ)
2649 			return tb_xdp_schedule_request(tb, hdr, size);
2650 		return false;
2651 	}
2652 
2653 	mutex_lock(&xdomain_lock);
2654 	list_for_each_entry_safe(handler, tmp, &protocol_handlers, list) {
2655 		if (!uuid_equal(&hdr->uuid, handler->uuid))
2656 			continue;
2657 
2658 		mutex_unlock(&xdomain_lock);
2659 		ret = handler->callback(buf, size, handler->data);
2660 		mutex_lock(&xdomain_lock);
2661 
2662 		if (ret)
2663 			break;
2664 	}
2665 	mutex_unlock(&xdomain_lock);
2666 
2667 	return ret > 0;
2668 }
2669 
2670 static void update_all_xdomains(void)
2671 {
2672 	bus_for_each_dev(&tb_bus_type, NULL, NULL, update_xdomain);
2673 }
2674 
2675 static bool remove_directory(const char *key, const struct tb_property_dir *dir)
2676 {
2677 	struct tb_property *p;
2678 
2679 	p = tb_property_find(xdomain_property_dir, key,
2680 			     TB_PROPERTY_TYPE_DIRECTORY);
2681 	if (p && p->value.dir == dir) {
2682 		tb_property_remove(p);
2683 		return true;
2684 	}
2685 	return false;
2686 }
2687 
2688 /**
2689  * tb_register_property_dir() - Register property directory to the host
2690  * @key: Key (name) of the directory to add
2691  * @dir: Directory to add
2692  *
2693  * Service drivers can use this function to add new property directory
2694  * to the host available properties. The other connected hosts are
2695  * notified so they can re-read properties of this host if they are
2696  * interested.
2697  *
2698  * Return: %0 on success, negative errno otherwise.
2699  */
2700 int tb_register_property_dir(const char *key, struct tb_property_dir *dir)
2701 {
2702 	int ret;
2703 
2704 	if (WARN_ON(!xdomain_property_dir))
2705 		return -EAGAIN;
2706 
2707 	if (!key || strlen(key) > 8)
2708 		return -EINVAL;
2709 
2710 	mutex_lock(&xdomain_lock);
2711 	if (tb_property_find(xdomain_property_dir, key,
2712 			     TB_PROPERTY_TYPE_DIRECTORY)) {
2713 		ret = -EEXIST;
2714 		goto err_unlock;
2715 	}
2716 
2717 	ret = tb_property_add_dir(xdomain_property_dir, key, dir);
2718 	if (ret)
2719 		goto err_unlock;
2720 
2721 	xdomain_property_block_gen++;
2722 
2723 	mutex_unlock(&xdomain_lock);
2724 	update_all_xdomains();
2725 	return 0;
2726 
2727 err_unlock:
2728 	mutex_unlock(&xdomain_lock);
2729 	return ret;
2730 }
2731 EXPORT_SYMBOL_GPL(tb_register_property_dir);
2732 
2733 /**
2734  * tb_unregister_property_dir() - Removes property directory from host
2735  * @key: Key (name) of the directory
2736  * @dir: Directory to remove
2737  *
2738  * This will remove the existing directory from this host and notify the
2739  * connected hosts about the change.
2740  */
2741 void tb_unregister_property_dir(const char *key, struct tb_property_dir *dir)
2742 {
2743 	int ret = 0;
2744 
2745 	mutex_lock(&xdomain_lock);
2746 	if (remove_directory(key, dir))
2747 		xdomain_property_block_gen++;
2748 	mutex_unlock(&xdomain_lock);
2749 
2750 	if (!ret)
2751 		update_all_xdomains();
2752 }
2753 EXPORT_SYMBOL_GPL(tb_unregister_property_dir);
2754 
2755 int tb_xdomain_init(void)
2756 {
2757 	xdomain_property_dir = tb_property_create_dir(NULL);
2758 	if (!xdomain_property_dir)
2759 		return -ENOMEM;
2760 
2761 	/*
2762 	 * Initialize standard set of properties without any service
2763 	 * directories. Those will be added by service drivers
2764 	 * themselves when they are loaded.
2765 	 *
2766 	 * Rest of the properties are filled dynamically based on these
2767 	 * when the P2P connection is made.
2768 	 */
2769 	tb_property_add_immediate(xdomain_property_dir, "vendorid", 0x1d6b);
2770 	tb_property_add_text(xdomain_property_dir, "vendorid", "Linux");
2771 	tb_property_add_immediate(xdomain_property_dir, "deviceid", 0x0004);
2772 	tb_property_add_immediate(xdomain_property_dir, "devicerv", 0x80000100);
2773 
2774 	xdomain_property_block_gen = get_random_u32();
2775 	return 0;
2776 }
2777 
2778 void tb_xdomain_exit(void)
2779 {
2780 	tb_property_free_dir(xdomain_property_dir);
2781 }
2782