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