xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ualink.c (revision b0a3a811634aa7422f8a92196db47a06a70bda16)
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright 2026 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  */
24 
25 #include <linux/xarray.h>
26 #include <drm/drm_mm.h>
27 #include <linux/random.h>
28 #include "amdgpu.h"
29 #include "amdgpu_sdma.h"
30 #include "amdgpu_ualink.h"
31 #include "amdgpu_xgmi.h"
32 #include "amdgpu_dma_buf.h"
33 #include "psp_gfx_if.h"
34 #include <linux/math.h>
35 #include <linux/sysfs.h>
36 #include <linux/string.h>
37 
38 static void deactivate_accelerator(struct amdgpu_device *adev);
39 static int amdgpu_ualink_remote_interrupt(struct amdgpu_device *adev,
40 				u32 remote_accel_id, u32 dw0, u32 dw1,
41 				u32 dw2, u32 dw3);
42 static void amdgpu_ualink_flush_tlb(struct amdgpu_device *adev,
43 				    u32 flush_type);
44 static int amdgpu_ualink_reserve_npa_vm_and_bos(struct amdgpu_device *adev,
45 						struct amdgpu_bo *bos[], u32 n_bos,
46 						struct drm_exec *exec,
47 						bool interruptible);
48 static void amdgpu_ualink_unreserve_npa_vm_and_bos(struct amdgpu_device *adev,
49 						   struct drm_exec *exec);
50 static void amdgpu_ualink_handle_connection_reset(struct amdgpu_device *adev,
51 						  u32 remote_accel_id, u32 state,
52 						  u32 generation_count);
53 static void amdgpu_ualink_invalidate_import_mappings(struct amdgpu_bo *bo);
54 static int amdgpu_ualink_remote_shootdown(struct amdgpu_device *adev,
55 					  u32 remote_accel_id, u64 addr,
56 					  u32 size_in_pages, u32 flush_type);
57 static void __amdgpu_ualink_activate_vpod_locked(struct amdgpu_device *adev);
58 static bool amdgpu_ualink_vpod_membership_changed(struct amdgpu_device *adev);
59 
60 #define STRIP_NPA(addr)						\
61 	(((u64)(addr) & ~AMDGPU_UALINK_NPA_ADDR_GPUID_MASK))
62 
63 #define GENERATE_NPA(addr, remote_acc_id)			\
64 		((u64)(((u64)(addr)) |				\
65 		 ((u64)(remote_acc_id) << AMDGPU_UALINK_NPA_ADDR_GPUID_SHIFT)))
66 
67 static const struct drm_client_funcs ualink_client_funcs = {
68 	.unregister	= drm_client_release,
69 };
70 
71 static int amdgpu_ualink_drm_client_create(struct amdgpu_device *adev)
72 {
73 	int ret;
74 
75 	ret = drm_client_init(&adev->ddev, &adev->ualink.client, "ualink",
76 			      &ualink_client_funcs);
77 	if (ret) {
78 		dev_err(adev->dev, "Failed to init UALink DRM client: %d\n",
79 			ret);
80 		return ret;
81 	}
82 
83 	drm_client_register(&adev->ualink.client);
84 
85 	return 0;
86 }
87 
88 static void amdgpu_ualink_object_fini(struct amdgpu_device *adev)
89 {
90 	if (!adev->ualink.info)
91 		return;
92 
93 	kobject_put(&adev->ualink.stations->kobj);
94 	kobject_put(&adev->ualink.config->kobj);
95 	kobject_put(&adev->ualink.setup->kobj);
96 	kobject_put(&adev->ualink.info->kobj);
97 	adev->ualink.stations = NULL;
98 	adev->ualink.config = NULL;
99 	adev->ualink.setup = NULL;
100 	adev->ualink.info = NULL;
101 }
102 
103 static bool __check_ppod_info(struct amdgpu_device *adev,
104 			      const struct amdgpu_ualink_info *info)
105 {
106 	const struct amdgpu_ualink_ppod_info *ppod = &info->ppod;
107 
108 	if (ppod->size <= 0 || ppod->size > AMDGPU_UALINK_ACCEL_MAX) {
109 		dev_dbg(adev->dev, "pPod size %u out of range [1..%u]\n",
110 			ppod->size, AMDGPU_UALINK_ACCEL_MAX);
111 		return false;
112 	}
113 	if (ppod->accel_id >= ppod->size) {
114 		dev_dbg(adev->dev,
115 			"Accelerator ID %u greater or equal pPod size %u\n",
116 			ppod->accel_id, ppod->size);
117 		return false;
118 	}
119 
120 	return true;
121 }
122 
123 static bool __check_vpod_info(struct amdgpu_device *adev,
124 			      const struct amdgpu_ualink_info *info)
125 {
126 	const struct amdgpu_ualink_ppod_info *ppod = &info->ppod;
127 	const struct amdgpu_ualink_vpod_info *vpod = &info->vpod;
128 	unsigned int weight;
129 
130 	if (vpod->size == 0 || vpod->size > ppod->size) {
131 		dev_warn(adev->dev,
132 			 "UALINK: vPod size %u out of range [1..%u]\n",
133 			 vpod->size, ppod->size);
134 		return false;
135 	}
136 	if (vpod->addr_mode >= AMDGPU_UALINK_ADDR_MODE_MAX) {
137 		dev_warn(adev->dev,
138 			 "UALINK: invalid addr mode %u\n",
139 			 vpod->addr_mode);
140 		return false;
141 	}
142 	weight =
143 		bitmap_weight(vpod->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX);
144 	if (weight != vpod->size) {
145 		dev_warn(adev->dev,
146 			 "UALINK: vPod size doesn't match vpod_active_accels list: %u != %u\n",
147 			 vpod->size, weight);
148 		return false;
149 	}
150 	if (!test_bit(ppod->accel_id, vpod->active_accel_bits)) {
151 		dev_warn(adev->dev,
152 			 "UALINK: accelerator ID %u not listed in vpod_active_accels\n",
153 			 ppod->accel_id);
154 		return false;
155 	}
156 
157 	return true;
158 }
159 
160 static void
161 amdgpu_ualink_info_set_accel_state(struct amdgpu_device *adev,
162 				   struct amdgpu_ualink_info *info,
163 				   enum psp_gfx_ual_config_state cfg_state)
164 {
165 	enum amdgpu_ualink_accel_state cur = info->accel_state;
166 	enum amdgpu_ualink_accel_state target;
167 	bool ppod_validated;
168 	bool vpod_validated;
169 
170 	if (!info)
171 		return;
172 
173 	ppod_validated = cur >= AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED &&
174 			 cur <= AMDGPU_UALINK_ACCEL_STATE_ACTIVE;
175 	vpod_validated = cur >= AMDGPU_UALINK_ACCEL_STATE_VPOD_CONFIGURED &&
176 			 cur <= AMDGPU_UALINK_ACCEL_STATE_ACTIVE;
177 
178 	switch (cfg_state) {
179 	case UAL_CFG_IDLE:
180 		return;
181 	case UAL_CFG_PPOD:
182 		target = AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED;
183 		break;
184 	case UAL_CFG_VPOD:
185 	case UAL_CFG_STATION:
186 		target = AMDGPU_UALINK_ACCEL_STATE_VPOD_CONFIGURED;
187 		break;
188 	case UAL_CFG_COMPLETE:
189 		target = AMDGPU_UALINK_ACCEL_STATE_READY;
190 		break;
191 	default:
192 		dev_dbg(adev->dev, "invalid configuration state %u", cfg_state);
193 		return;
194 	}
195 
196 	/* ppod stage: should be part of a ppod first */
197 	if (!ppod_validated && !__check_ppod_info(adev, info)) {
198 		if (target == AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED) {
199 			info->accel_state =
200 				AMDGPU_UALINK_ACCEL_STATE_UNCONFIGURED;
201 		} else {
202 			info->accel_state = AMDGPU_UALINK_ACCEL_STATE_ERROR;
203 			dev_err(adev->dev,
204 				"ppod configuration is invalid, setting to error state");
205 		}
206 		return;
207 	}
208 	if (target == AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED) {
209 		if (!ppod_validated)
210 			info->accel_state =
211 				AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED;
212 		return;
213 	}
214 
215 	/* A vpod_id of 0 means the GPU is not part of any vPod */
216 	if (info->vpod.id == AMDGPU_UALINK_VPOD_ID_INVALID) {
217 		info->accel_state = AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED;
218 		return;
219 	}
220 
221 	/* vpod stage: required to reach vpod_configured or ready */
222 	if (!vpod_validated && !__check_vpod_info(adev, info)) {
223 		info->accel_state = AMDGPU_UALINK_ACCEL_STATE_ERROR;
224 		dev_err(adev->dev,
225 			"vpod configuration is invalid, setting to error state");
226 		return;
227 	}
228 	if (target == AMDGPU_UALINK_ACCEL_STATE_VPOD_CONFIGURED) {
229 		if (!vpod_validated)
230 			info->accel_state =
231 				AMDGPU_UALINK_ACCEL_STATE_VPOD_CONFIGURED;
232 		return;
233 	}
234 
235 	/* complete stage: advance to ready unless already ready/active */
236 	if (cur < AMDGPU_UALINK_ACCEL_STATE_READY ||
237 	    cur > AMDGPU_UALINK_ACCEL_STATE_ACTIVE)
238 		info->accel_state = AMDGPU_UALINK_ACCEL_STATE_READY;
239 }
240 
241 static int amdgpu_ualink_update_vpod_config(struct amdgpu_device *adev)
242 {
243 	/* TBD: Do updates/cleanup based on updated vpod configuration */
244 	return 0;
245 }
246 
247 static int amdgpu_ualink_update_accel_state(
248 	struct amdgpu_device *adev, enum amdgpu_ualink_accel_state prev_state,
249 	u32 prev_vpod_id, enum psp_gfx_ual_config_state cfg_state)
250 {
251 	dev_info(adev->dev,
252 		 "UALINK: update_accel_state: prev_state=%d prev_vpod_id=%u new_vpod_id=%u cfg_state=%d\n",
253 		 prev_state, prev_vpod_id, adev->ualink.info->vpod.id,
254 		 cfg_state);
255 
256 	/* If the device is already active and its vpod_id is unchanged, the
257 	 * update does not affect vpod membership. Skip the local vpod
258 	 * integrity check and re-activation.
259 	 */
260 	if (prev_state == AMDGPU_UALINK_ACCEL_STATE_ACTIVE &&
261 	    adev->ualink.info->vpod.id == prev_vpod_id) {
262 		amdgpu_ualink_update_vpod_config(adev);
263 
264 		/* Same vpod_id, but the member set may have changed (vPod grown
265 		 * or shrunk while this GPU stayed ACTIVE). If so, run the local
266 		 * vpod activation path: once every local peer has committed the
267 		 * new config (integrity passes), it bounces the affected ACTIVE
268 		 * peers to rebuild links/GART for the new member set.
269 		 */
270 		if (amdgpu_ualink_vpod_membership_changed(adev)) {
271 			dev_info(adev->dev,
272 				 "UALINK: update_accel_state: ACTIVE vpod_id=%u membership changed, reconfiguring\n",
273 				 adev->ualink.info->vpod.id);
274 			scoped_guard(mutex, &mgpu_info.mutex)
275 				__amdgpu_ualink_activate_vpod_locked(adev);
276 		} else {
277 			dev_info(adev->dev,
278 				 "UALINK: update_accel_state: already ACTIVE, vpod_id/membership unchanged\n");
279 		}
280 		return 0;
281 	}
282 
283 	/* A new vpod_id of 0 means this GPU was removed from the vPod. */
284 	if (adev->ualink.info->vpod.id == AMDGPU_UALINK_VPOD_ID_INVALID) {
285 		dev_info(adev->dev,
286 			 "UALINK: update_accel_state: vpod_id=0, removing accelerator from vPod\n");
287 		amdgpu_ualink_update_vpod_config(adev);
288 		scoped_guard(mutex, &mgpu_info.mutex)
289 			deactivate_accelerator(adev);
290 		return 0;
291 	}
292 
293 	/* GPU joining a new vpod should be with invalid vpod id*/
294 	scoped_guard(mutex, &mgpu_info.mutex) {
295 		if (prev_vpod_id == AMDGPU_UALINK_VPOD_ID_INVALID) {
296 			dev_info(adev->dev,
297 				 "UALINK: update_accel_state: joining vpod_id=%u\n",
298 				 adev->ualink.info->vpod.id);
299 			amdgpu_ualink_info_set_accel_state(
300 				adev, adev->ualink.info, cfg_state);
301 			__amdgpu_ualink_activate_vpod_locked(adev);
302 		} else {
303 			/* GPU should first get removal which will set invalid vpod_id
304 			* and then join a new vpod
305 			*/
306 			dev_err(adev->dev,
307 				"Invalid vpod transition from %u to %u\n",
308 				prev_vpod_id, adev->ualink.info->vpod.id);
309 			return -EINVAL;
310 		}
311 	}
312 
313 	return 0;
314 }
315 
316 int amdgpu_ualink_config_update_handler(struct amdgpu_device *adev)
317 {
318 	enum amdgpu_ualink_accel_state prev_state;
319 	enum psp_gfx_ual_config_state cfg_state;
320 	u32 prev_vpod_id;
321 	int r, qerr;
322 
323 	/* TBD: Stop ASP interrupts if driver faced an issue */
324 	if (adev->ualink.mgr_state != AMDGPU_UALINK_INIT_COMPLETE) {
325 		u32 status;
326 
327 		dev_dbg(adev->dev,
328 			"UALink not initialized, skipping config update\n");
329 		status = !!(adev->ualink.mgr_state == AMDGPU_UALINK_INIT_ERROR);
330 		return psp_ual_send_completion(
331 			&adev->psp, adev->ualink.psp_if_ver,
332 			PSP_GFX_INT_CTXT_UAL_CMD_CFG_UPDATE_ID, status);
333 	}
334 
335 	prev_state = adev->ualink.info->accel_state;
336 	prev_vpod_id = adev->ualink.info->vpod.id;
337 
338 	qerr = psp_ual_query_info(&adev->psp, adev->ualink.psp_if_ver,
339 				  adev->ualink.info, &cfg_state);
340 
341 	/*TBD: find the right value of status to be sent to ASP*/
342 	r = psp_ual_send_completion(&adev->psp, adev->ualink.psp_if_ver,
343 				    PSP_GFX_INT_CTXT_UAL_CMD_CFG_UPDATE_ID, 0);
344 	if (r || qerr)
345 		goto err;
346 
347 	r = amdgpu_ualink_update_accel_state(adev, prev_state, prev_vpod_id,
348 					     cfg_state);
349 	if (r)
350 		goto err;
351 
352 	return 0;
353 
354 err:
355 	scoped_guard(mutex, &mgpu_info.mutex) {
356 		deactivate_accelerator(adev);
357 		adev->ualink.info->accel_state =
358 			AMDGPU_UALINK_ACCEL_STATE_ERROR;
359 	}
360 	dev_err(adev->dev,
361 		"UALink config update failed, setting to error state");
362 
363 	return r;
364 }
365 
366 int amdgpu_ualink_pause_handler(struct amdgpu_device *adev)
367 {
368 	u32 status = 0;
369 
370 	if (adev->ualink.mgr_state != AMDGPU_UALINK_INIT_COMPLETE) {
371 		dev_dbg(adev->dev,
372 			"UALink not initialized, skipping pause update\n");
373 		status = !!(adev->ualink.mgr_state == AMDGPU_UALINK_INIT_ERROR);
374 		goto out;
375 	}
376 
377 	dev_dbg(adev->dev, "UALink pause command is not handled\n");
378 
379 out:
380 	return psp_ual_send_completion(&adev->psp, adev->ualink.psp_if_ver,
381 				       PSP_GFX_INT_CTXT_UAL_CMD_PAUSE_ID,
382 				       status);
383 }
384 
385 int amdgpu_ualink_resume_handler(struct amdgpu_device *adev)
386 {
387 	u32 status = 0;
388 
389 	if (adev->ualink.mgr_state != AMDGPU_UALINK_INIT_COMPLETE) {
390 		dev_dbg(adev->dev,
391 			"UALink not initialized, skipping pause update\n");
392 		status = !!(adev->ualink.mgr_state == AMDGPU_UALINK_INIT_ERROR);
393 		goto out;
394 	}
395 
396 	dev_dbg(adev->dev, "UALink resume command is not handled\n");
397 
398 out:
399 	return psp_ual_send_completion(&adev->psp, adev->ualink.psp_if_ver,
400 				       PSP_GFX_INT_CTXT_UAL_CMD_RESUME_ID,
401 				       status);
402 }
403 
404 int ualink_ip_hw_init(struct amdgpu_ip_block *ip_block)
405 {
406 	struct amdgpu_device *adev = ip_block->adev;
407 	int r;
408 
409 	if (!adev->ualink.info)
410 		return 0;
411 
412 	adev->ualink.info->accel_state = AMDGPU_UALINK_ACCEL_STATE_UNCONFIGURED;
413 	r = psp_ual_get_interface_version(&adev->psp, &adev->ualink.psp_if_ver);
414 	if (r) {
415 		adev->ualink.psp_if_ver = 0xffffffff;
416 		goto disable;
417 	}
418 	dev_info(adev->dev, "Found UALink interface version 0x%x\n",
419 		 adev->ualink.psp_if_ver);
420 
421 	adev->ualink.mgr_state = AMDGPU_UALINK_INIT_HW;
422 
423 	return 0;
424 disable:
425 	adev->ualink.mgr_state = AMDGPU_UALINK_INIT_ERROR;
426 	return 0;
427 }
428 
429 int ualink_ip_hw_fini(struct amdgpu_ip_block *ip_block)
430 {
431 	struct amdgpu_device *adev = ip_block->adev;
432 
433 	if (adev->ualink.mgr_state != AMDGPU_UALINK_INIT_COMPLETE)
434 		return 0;
435 
436 	scoped_guard(mutex, &mgpu_info.mutex)
437 		deactivate_accelerator(adev);
438 
439 	return 0;
440 }
441 
442 int ualink_ip_late_init(struct amdgpu_ip_block *ip_block)
443 {
444 	struct amdgpu_device *adev = ip_block->adev;
445 	enum psp_gfx_ual_config_state cfg_state;
446 	int r;
447 
448 	if (adev->ualink.mgr_state != AMDGPU_UALINK_INIT_HW)
449 		return 0;
450 
451 	r = psp_ual_query_info(&adev->psp, adev->ualink.psp_if_ver,
452 			       adev->ualink.info, &cfg_state);
453 	if (r)
454 		return r;
455 
456 	scoped_guard(mutex, &mgpu_info.mutex) {
457 		amdgpu_ualink_info_set_accel_state(adev, adev->ualink.info,
458 						   cfg_state);
459 		__amdgpu_ualink_activate_vpod_locked(adev);
460 	}
461 
462 	r = amdgpu_ualink_drm_client_create(adev);
463 	if (r) {
464 		dev_err(adev->dev, "Failed to create UALink DRM client: %d\n",
465 			r);
466 		goto error;
467 	}
468 
469 	/* Consider UALink initialized only at this stage */
470 	adev->ualink.mgr_state = AMDGPU_UALINK_INIT_COMPLETE;
471 
472 	return 0;
473 
474 error:
475 	adev->ualink.mgr_state = AMDGPU_UALINK_INIT_ERROR;
476 	return r;
477 }
478 
479 /****************************************************************************
480  * UALink info and configuration in sysfs
481  *
482  * Using kobj_attribute and not device_attribute here because the UALink
483  * attributes are part of their own nested kobjects and not the amdgpu
484  * device itself or a subdevice.
485  ****************************************************************************/
486 
487 /* UALink configuration APIs are being deprecated before upstreaming and are
488  * not enabled by default. They are replaced by a unified in-band/side-band
489  * approach through the IFoE driver. Querying of the current configuration
490  * will continue to be supported in sysfs.
491  *
492  * Uncomment the following line to enable the deprecated configuration APIs
493  * for testing purposes only. The code to support these APIs will be removed
494  * in a future patch.
495  */
496 /* #define UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS */
497 
498 #define UALINK_VALUE_SHOW(prefix, name, field, format)			\
499 static ssize_t ualink_##prefix##_##name##_show(struct kobject *kobj,	\
500 					       struct kobj_attribute *attr,\
501 					       char *buf)		\
502 {									\
503 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
504 									\
505 	return sysfs_emit(buf, format"\n", info->field);		\
506 }
507 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
508 #define UALINK_VALUE_STORE(prefix, name, field, type, base)		\
509 static ssize_t ualink_##prefix##_##name##_store(struct kobject *kobj,	\
510 						struct kobj_attribute *attr,\
511 						const char *buf, size_t count)\
512 {									\
513 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
514 	int r;								\
515 									\
516 	r = kstrto##type(buf, base, &info->field);			\
517 	if (r < 0)							\
518 		return r;						\
519 	return count;							\
520 }
521 #endif
522 
523 static ssize_t show_idbits(unsigned long *bits, unsigned int nbits, char *buf)
524 {
525 	ssize_t len = 0;
526 	unsigned int id;
527 
528 	for_each_set_bit(id, bits, nbits)
529 		len += sysfs_emit_at(buf, len, "%u ", id);
530 	if (len)
531 		len--;
532 	return len + sysfs_emit_at(buf, len, "\n");
533 }
534 #define UALINK_IDBITS_SHOW(prefix, name, field)				\
535 static ssize_t ualink_##prefix##_##name##_show(struct kobject *kobj,	\
536 					       struct kobj_attribute *attr,\
537 					       char *buf)		\
538 {									\
539 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
540 									\
541 	return show_idbits(info->field, sizeof(info->field)*8, buf);	\
542 }
543 
544 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
545 static ssize_t store_idbits(unsigned long *bits, unsigned int nbits,
546 			    const char *buf, size_t count)
547 {
548 	char *dup_buf, *str, *tok;
549 	ssize_t r;
550 	u32 id;
551 
552 	bitmap_zero(bits, nbits);
553 	if (!count)
554 		return 0;
555 
556 	dup_buf = kstrndup(buf, count, GFP_KERNEL);
557 	if (unlikely(!dup_buf))
558 		return -ENOMEM;
559 	str = dup_buf;
560 	do {
561 		str += strspn(str, " ");
562 		tok = strsep(&str, ", ");
563 		r = kstrtou32(tok, 10, &id);
564 		if (r < 0)
565 			goto err;
566 		if (id >= nbits) {
567 			r = -ERANGE;
568 			goto err;
569 		}
570 		set_bit(id, bits);
571 	} while (str);
572 	kfree(dup_buf);
573 
574 	return count;
575 
576 err:
577 	kfree(dup_buf);
578 	return r;
579 }
580 #define UALINK_IDBITS_STORE(prefix, name, field, nbits)			\
581 static ssize_t ualink_##prefix##_##name##_store(struct kobject *kobj,	\
582 						struct kobj_attribute *attr,\
583 						const char *buf, size_t count)\
584 {									\
585 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
586 	DECLARE_BITMAP(bits, nbits);					\
587 	ssize_t r = store_idbits(bits, nbits, buf, count);		\
588 									\
589 	if (r >= 0)							\
590 		bitmap_copy(info->field, bits, nbits);			\
591 	return r;							\
592 }
593 #endif
594 
595 static ssize_t show_idarray(const u32 *array, u32 size, char *buf)
596 {
597 	ssize_t len = 0;
598 	unsigned int i;
599 
600 	for (i = 0; i < size; i++)
601 		len += sysfs_emit_at(buf, len, "%u ", array[i]);
602 	if (len)
603 		len--;
604 	return len + sysfs_emit_at(buf, len, "\n");
605 }
606 #define UALINK_IDARRAY_SHOW(prefix, name, field, size)			\
607 static ssize_t ualink_##prefix##_##name##_show(struct kobject *kobj,	\
608 					       struct kobj_attribute *attr,\
609 					       char *buf)		\
610 {									\
611 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
612 									\
613 	return show_idarray(info->field, info->size, buf);		\
614 }
615 
616 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
617 static ssize_t store_idarray(u32 *array, u32 *size, u32 max_id, u32 max_size,
618 			     const char *buf, size_t count)
619 {
620 	char *dup_buf, *str, *tok;
621 	unsigned int index = 0;
622 	ssize_t r;
623 	u32 id;
624 
625 	*size = 0;
626 	if (!count)
627 		return 0;
628 
629 	dup_buf = kstrndup(buf, count, GFP_KERNEL);
630 	if (unlikely(!dup_buf))
631 		return -ENOMEM;
632 	str = dup_buf;
633 	do {
634 		str += strspn(str, " ");
635 		tok = strsep(&str, ", ");
636 		r = kstrtou32(tok, 10, &id);
637 		if (r < 0)
638 			goto err;
639 		if (index >= max_size) {
640 			r = -ENOSPC;
641 			goto err;
642 		}
643 		if (id >= max_id) {
644 			r = -ERANGE;
645 			goto err;
646 		}
647 		array[index++] = id;
648 	} while (str);
649 	kfree(dup_buf);
650 
651 	*size = index;
652 	return count;
653 
654 err:
655 	kfree(dup_buf);
656 	return r;
657 }
658 #define UALINK_IDARRAY_STORE(prefix, name, field, size, max_id)		\
659 static ssize_t ualink_##prefix##_##name##_store(struct kobject *kobj,	\
660 						struct kobj_attribute *attr,\
661 						const char *buf, size_t count)\
662 {									\
663 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
664 	u32 new_array[ARRAY_SIZE(info->field)];				\
665 	u32 new_size;							\
666 	ssize_t r = store_idarray(new_array, &new_size, max_id,		\
667 				  ARRAY_SIZE(new_array), buf, count);	\
668 									\
669 	if (r >= 0) {							\
670 		memcpy(info->field, new_array, sizeof(new_array));	\
671 		info->size = new_size;					\
672 	}								\
673 	return r;							\
674 }
675 #endif
676 
677 #define UALINK_UUID_SHOW(prefix, name, field)				\
678 static ssize_t ualink_##prefix##_##name##_show(struct kobject *kobj,	\
679 					       struct kobj_attribute *attr,\
680 					       char *buf)		\
681 {									\
682 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
683 									\
684 	return sysfs_emit(buf, "%pU\n", &info->field);			\
685 }
686 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
687 #define UALINK_UUID_STORE(prefix, name, field)				\
688 static ssize_t ualink_##prefix##_##name##_store(struct kobject *kobj,	\
689 						struct kobj_attribute *attr,\
690 						const char *buf, size_t count)\
691 {									\
692 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
693 	int r;								\
694 									\
695 	r = uuid_parse(buf, &info->field);				\
696 	return r ? r : count;						\
697 }
698 #endif
699 
700 static ssize_t show_enum(u32 x, const char * const values[], unsigned int n,
701 			 char *buf)
702 {
703 	return sysfs_emit(buf, "%s\n", x < n && values[x] ? values[x] : "invalid");
704 }
705 #define UALINK_ENUM_SHOW(prefix, name, field)				\
706 static ssize_t ualink_##prefix##_##name##_show(struct kobject *kobj,	\
707 					       struct kobj_attribute *attr,\
708 					       char *buf)		\
709 {									\
710 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
711 									\
712 	return show_enum(info->field, ualink_##name##_values,		\
713 			 ARRAY_SIZE(ualink_##name##_values), buf);	\
714 }
715 
716 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
717 static ssize_t store_enum(u32 *x, const char * const values[], unsigned int n,
718 			  const char *buf, size_t count)
719 {
720 	unsigned int i;
721 
722 	for (i = 0; i < n; i++) {
723 		if (values[i] && sysfs_streq(buf, values[i])) {
724 			*x = i;
725 			return count;
726 		}
727 	}
728 	return -EINVAL;
729 }
730 #define UALINK_ENUM_STORE(prefix, name, field)				\
731 static ssize_t ualink_##prefix##_##name##_store(struct kobject *kobj,	\
732 						struct kobj_attribute *attr,\
733 						const char *buf, size_t count)\
734 {									\
735 	struct amdgpu_ualink_##prefix *info = to_ualink_##prefix(kobj);	\
736 									\
737 	return store_enum(&info->field, ualink_##name##_values,		\
738 			 ARRAY_SIZE(ualink_##name##_values),		\
739 			 buf, count);					\
740 }
741 #endif
742 static const char * const ualink_link_type_values[] = {
743 	"UALoE", "UALink"
744 };
745 static const char * const ualink_addr_mode_values[] = {
746 	"source-aliasing", "source-identification"
747 };
748 static const char * const ualink_accel_state_values[] = {
749 	[AMDGPU_UALINK_ACCEL_STATE_UNCONFIGURED]	= "unconfigured",
750 	[AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED]	= "ppod_configured",
751 	[AMDGPU_UALINK_ACCEL_STATE_VPOD_CONFIGURED]	= "vpod_configured",
752 	[AMDGPU_UALINK_ACCEL_STATE_READY]		= "ready",
753 	[AMDGPU_UALINK_ACCEL_STATE_ACTIVE]		= "active",
754 	[AMDGPU_UALINK_ACCEL_STATE_ERROR]		= "error",
755 };
756 static_assert(ARRAY_SIZE(ualink_accel_state_values) ==
757 	      AMDGPU_UALINK_ACCEL_STATE_MAX);
758 
759 UALINK_ENUM_SHOW(info, link_type, link_type);
760 UALINK_VALUE_SHOW(info, accel_id,  ppod.accel_id,  "%u");
761 UALINK_VALUE_SHOW(info, bandwidth, ppod.bandwidth, "%u");
762 UALINK_VALUE_SHOW(info, latency,   ppod.latency,   "%u");
763 UALINK_UUID_SHOW(info, ppod_id, ppod.id);
764 UALINK_VALUE_SHOW(info, ppod_size, ppod.size,      "%u");
765 UALINK_VALUE_SHOW(info, vpod_id,   vpod.id,        "%u");
766 UALINK_VALUE_SHOW(info, vpod_size, vpod.size,      "%u");
767 UALINK_IDBITS_SHOW(info, vpod_active_accels, vpod.active_accel_bits);
768 UALINK_ENUM_SHOW(info, addr_mode, vpod.addr_mode);
769 UALINK_ENUM_SHOW(info, accel_state, accel_state);
770 UALINK_IDARRAY_SHOW(info, local_accels, local_accels, n_local_accels);
771 
772 static struct amdgpu_device *ualink_xcp_kobj_to_adev(struct kobject *kobj)
773 {
774 	struct amdgpu_xcp *xcp = container_of(kobj, struct amdgpu_xcp,
775 					      ualink.kobj);
776 
777 	return xcp->xcp_mgr->adev;
778 }
779 
780 #define UALINK_XCP_INFO_SHOW(name)					\
781 static ssize_t ualink_xcp_info_##name##_show(struct kobject *kobj,	\
782 		struct kobj_attribute *attr, char *buf)			\
783 {									\
784 	struct amdgpu_device *adev = ualink_xcp_kobj_to_adev(kobj);	\
785 									\
786 	return ualink_info_##name##_show(&adev->ualink.info->kobj,	\
787 					 attr, buf);			\
788 }
789 
790 UALINK_XCP_INFO_SHOW(link_type)
791 UALINK_XCP_INFO_SHOW(accel_id)
792 UALINK_XCP_INFO_SHOW(bandwidth)
793 UALINK_XCP_INFO_SHOW(latency)
794 UALINK_XCP_INFO_SHOW(ppod_id)
795 UALINK_XCP_INFO_SHOW(ppod_size)
796 UALINK_XCP_INFO_SHOW(vpod_id)
797 UALINK_XCP_INFO_SHOW(vpod_size)
798 UALINK_XCP_INFO_SHOW(vpod_active_accels)
799 UALINK_XCP_INFO_SHOW(addr_mode)
800 UALINK_XCP_INFO_SHOW(accel_state)
801 UALINK_XCP_INFO_SHOW(local_accels)
802 
803 #define UALINK_INFO_ATTR(name) __ATTR(name, 0444, ualink_info_##name##_show, NULL)
804 static struct kobj_attribute ualink_info_link_type = UALINK_INFO_ATTR(link_type);
805 static struct kobj_attribute ualink_info_accel_id  = UALINK_INFO_ATTR(accel_id);
806 static struct kobj_attribute ualink_info_bandwidth = UALINK_INFO_ATTR(bandwidth);
807 static struct kobj_attribute ualink_info_latency   = UALINK_INFO_ATTR(latency);
808 static struct kobj_attribute ualink_info_ppod_id   = UALINK_INFO_ATTR(ppod_id);
809 static struct kobj_attribute ualink_info_ppod_size = UALINK_INFO_ATTR(ppod_size);
810 static struct kobj_attribute ualink_info_vpod_id   = UALINK_INFO_ATTR(vpod_id);
811 static struct kobj_attribute ualink_info_vpod_size = UALINK_INFO_ATTR(vpod_size);
812 static struct kobj_attribute ualink_info_vpod_active_accels = UALINK_INFO_ATTR(vpod_active_accels);
813 static struct kobj_attribute ualink_info_addr_mode = UALINK_INFO_ATTR(addr_mode);
814 static struct kobj_attribute ualink_info_accel_state = UALINK_INFO_ATTR(accel_state);
815 static struct kobj_attribute ualink_info_local_accels = UALINK_INFO_ATTR(local_accels);
816 
817 static const struct attribute *ualink_info_attrs[] = {
818 	&ualink_info_link_type.attr,
819 	&ualink_info_accel_id.attr,
820 	&ualink_info_bandwidth.attr,
821 	&ualink_info_latency.attr,
822 	&ualink_info_ppod_id.attr,
823 	&ualink_info_ppod_size.attr,
824 	&ualink_info_vpod_id.attr,
825 	&ualink_info_vpod_size.attr,
826 	&ualink_info_vpod_active_accels.attr,
827 	&ualink_info_addr_mode.attr,
828 	&ualink_info_accel_state.attr,
829 	&ualink_info_local_accels.attr,
830 	NULL
831 };
832 
833 #define UALINK_XCP_INFO_ATTR(name) \
834 	__ATTR(name, 0444, ualink_xcp_info_##name##_show, NULL)
835 static struct kobj_attribute ualink_xcp_info_link_type = UALINK_XCP_INFO_ATTR(link_type);
836 static struct kobj_attribute ualink_xcp_info_accel_id  = UALINK_XCP_INFO_ATTR(accel_id);
837 static struct kobj_attribute ualink_xcp_info_bandwidth = UALINK_XCP_INFO_ATTR(bandwidth);
838 static struct kobj_attribute ualink_xcp_info_latency   = UALINK_XCP_INFO_ATTR(latency);
839 static struct kobj_attribute ualink_xcp_info_ppod_id   = UALINK_XCP_INFO_ATTR(ppod_id);
840 static struct kobj_attribute ualink_xcp_info_ppod_size = UALINK_XCP_INFO_ATTR(ppod_size);
841 static struct kobj_attribute ualink_xcp_info_vpod_id   = UALINK_XCP_INFO_ATTR(vpod_id);
842 static struct kobj_attribute ualink_xcp_info_vpod_size = UALINK_XCP_INFO_ATTR(vpod_size);
843 static struct kobj_attribute ualink_xcp_info_vpod_active_accels = UALINK_XCP_INFO_ATTR(vpod_active_accels);
844 static struct kobj_attribute ualink_xcp_info_addr_mode = UALINK_XCP_INFO_ATTR(addr_mode);
845 static struct kobj_attribute ualink_xcp_info_accel_state = UALINK_XCP_INFO_ATTR(accel_state);
846 static struct kobj_attribute ualink_xcp_info_local_accels = UALINK_XCP_INFO_ATTR(local_accels);
847 
848 static struct attribute *ualink_xcp_info_attrs[] = {
849 	&ualink_xcp_info_link_type.attr,
850 	&ualink_xcp_info_accel_id.attr,
851 	&ualink_xcp_info_bandwidth.attr,
852 	&ualink_xcp_info_latency.attr,
853 	&ualink_xcp_info_ppod_id.attr,
854 	&ualink_xcp_info_ppod_size.attr,
855 	&ualink_xcp_info_vpod_id.attr,
856 	&ualink_xcp_info_vpod_size.attr,
857 	&ualink_xcp_info_vpod_active_accels.attr,
858 	&ualink_xcp_info_addr_mode.attr,
859 	&ualink_xcp_info_accel_state.attr,
860 	&ualink_xcp_info_local_accels.attr,
861 	NULL
862 };
863 
864 static umode_t ualink_xcp_info_is_visible(struct kobject *kobj,
865 					  struct attribute *attr, int n)
866 {
867 	struct amdgpu_xcp *xcp = container_of(kobj, struct amdgpu_xcp,
868 					      ualink.kobj);
869 
870 	if (!xcp->valid)
871 		return 0;
872 
873 	return attr->mode;
874 }
875 
876 static const struct attribute_group ualink_xcp_info_group = {
877 	.attrs = ualink_xcp_info_attrs,
878 	.is_visible = ualink_xcp_info_is_visible,
879 };
880 
881 static const struct kobj_type ualink_xcp_info_ktype = {
882 	.sysfs_ops = &kobj_sysfs_ops
883 };
884 
885 static void ualink_info_release(struct kobject *kobj)
886 {
887 	kfree(to_ualink_info(kobj));
888 }
889 
890 static const struct kobj_type ualink_info_ktype = {
891 	.release = ualink_info_release,
892 	.sysfs_ops = &kobj_sysfs_ops
893 };
894 
895 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
896 UALINK_VALUE_SHOW(ppod_setup, accel_id,  ppod.accel_id,  "%u");
897 UALINK_VALUE_SHOW(ppod_setup, bandwidth, ppod.bandwidth, "%u");
898 UALINK_VALUE_SHOW(ppod_setup, latency,   ppod.latency,   "%u");
899 UALINK_UUID_SHOW(ppod_setup, ppod_id, ppod.id);
900 UALINK_VALUE_SHOW(ppod_setup, ppod_size, ppod.size,      "%u");
901 UALINK_IDARRAY_SHOW(ppod_setup, local_accels, local_accels, n_local_accels);
902 
903 UALINK_VALUE_STORE(ppod_setup, accel_id,  ppod.accel_id,  u32, 10);
904 UALINK_VALUE_STORE(ppod_setup, bandwidth, ppod.bandwidth, u32, 10);
905 UALINK_VALUE_STORE(ppod_setup, latency,   ppod.latency,   u32, 10);
906 UALINK_UUID_STORE(ppod_setup, ppod_id,   ppod.id);
907 UALINK_VALUE_STORE(ppod_setup, ppod_size, ppod.size,      u32, 10);
908 UALINK_IDARRAY_STORE(ppod_setup, local_accels, local_accels, n_local_accels,
909 		     AMDGPU_UALINK_ACCEL_MAX);
910 
911 static enum amdgpu_ualink_accel_state
912 check_ppod_state(struct amdgpu_device *adev,
913 		 const struct amdgpu_ualink_ppod_setup *setup)
914 {
915 	if (setup->ppod.size <= 0 || setup->ppod.size > AMDGPU_UALINK_ACCEL_MAX) {
916 		dev_dbg(adev->dev, "pPod size %u out of range [1..%u]\n",
917 			setup->ppod.size, AMDGPU_UALINK_ACCEL_MAX);
918 		return AMDGPU_UALINK_ACCEL_STATE_UNCONFIGURED;
919 	}
920 	if (setup->ppod.accel_id >= setup->ppod.size) {
921 		dev_dbg(adev->dev, "Accelerator ID %u greater or equal pPod size %u\n",
922 			setup->ppod.accel_id, setup->ppod.size);
923 		return AMDGPU_UALINK_ACCEL_STATE_UNCONFIGURED;
924 	}
925 	return AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED;
926 }
927 
928 static ssize_t ualink_ppod_setup_commit_store(struct kobject *kobj,
929 					      struct kobj_attribute *attr,
930 					      const char *buf, size_t count)
931 {
932 	struct amdgpu_ualink_ppod_setup *setup = to_ualink_ppod_setup(kobj);
933 	struct amdgpu_ualink_info *info = to_ualink_info(kobj->parent);
934 	struct device *dev = kobj_to_dev(info->kobj.parent);
935 	struct drm_device *ddev = dev_get_drvdata(dev);
936 	struct amdgpu_device *adev = drm_to_adev(ddev);
937 	int r;
938 
939 	if (!sysfs_streq(buf, "true"))
940 		return -EINVAL;
941 
942 	r = psp_ual_set_ppod_config(&adev->psp, adev->ualink.psp_if_ver,
943 				    setup);
944 	if (r)
945 		return r;
946 	r = psp_ual_query_info(&adev->psp, adev->ualink.psp_if_ver, info, NULL);
947 	if (r)
948 		return r;
949 
950 	/*
951 	 * Hold mgpu_info.mutex to serialize with activate_local_vpod() in
952 	 * vpod_config_commit_store which also holds this lock. Without it,
953 	 * deactivate_accelerator() can race with activate_accelerator(),
954 	 * causing concurrent vm_fini / vm_init on the same NPA VM.
955 	 */
956 	mutex_lock(&mgpu_info.mutex);
957 	if (info->accel_state >= AMDGPU_UALINK_ACCEL_STATE_READY)
958 		deactivate_accelerator(adev);
959 	info->accel_state = check_ppod_state(adev, setup);
960 	/* PPOD is expected to be configured first */
961 	info->vpod.id = AMDGPU_UALINK_VPOD_ID_INVALID;
962 	mutex_unlock(&mgpu_info.mutex);
963 
964 	/* TODO: If accel_state was ACTIVE, reset all connections */
965 
966 	return count;
967 }
968 
969 #define UALINK_PPOD_SETUP_ATTR(name) __ATTR(name, 0600,			\
970 		ualink_ppod_setup_##name##_show,			\
971 		ualink_ppod_setup_##name##_store)
972 static struct kobj_attribute ualink_ppod_setup_accel_id  = UALINK_PPOD_SETUP_ATTR(accel_id);
973 static struct kobj_attribute ualink_ppod_setup_bandwidth = UALINK_PPOD_SETUP_ATTR(bandwidth);
974 static struct kobj_attribute ualink_ppod_setup_latency   = UALINK_PPOD_SETUP_ATTR(latency);
975 static struct kobj_attribute ualink_ppod_setup_ppod_id   = UALINK_PPOD_SETUP_ATTR(ppod_id);
976 static struct kobj_attribute ualink_ppod_setup_ppod_size = UALINK_PPOD_SETUP_ATTR(ppod_size);
977 static struct kobj_attribute ualink_ppod_setup_local_accels = UALINK_PPOD_SETUP_ATTR(local_accels);
978 static struct kobj_attribute ualink_ppod_setup_commit = __ATTR(commit, 0200, NULL,
979 							       ualink_ppod_setup_commit_store);
980 
981 static const struct attribute *ualink_ppod_setup_attrs[] = {
982 	&ualink_ppod_setup_accel_id.attr,
983 	&ualink_ppod_setup_bandwidth.attr,
984 	&ualink_ppod_setup_latency.attr,
985 	&ualink_ppod_setup_ppod_id.attr,
986 	&ualink_ppod_setup_ppod_size.attr,
987 	&ualink_ppod_setup_local_accels.attr,
988 	&ualink_ppod_setup_commit.attr,
989 	NULL
990 };
991 #endif
992 
993 static void ualink_ppod_setup_release(struct kobject *kobj)
994 {
995 	kfree(to_ualink_ppod_setup(kobj));
996 }
997 
998 static const struct kobj_type ualink_ppod_setup_ktype = {
999 	.release = ualink_ppod_setup_release,
1000 	.sysfs_ops = &kobj_sysfs_ops
1001 };
1002 
1003 static struct amdgpu_device *find_peer_adev(unsigned int accel_id)
1004 {
1005 	unsigned int i;
1006 
1007 	for (i = 0; i < mgpu_info.num_gpu; i++) {
1008 		struct amdgpu_device *peer_adev = mgpu_info.gpu_ins[i].adev;
1009 
1010 		if (peer_adev->ualink.info &&
1011 		    peer_adev->ualink.info->ppod.accel_id == accel_id)
1012 			return peer_adev;
1013 	}
1014 
1015 	return NULL;
1016 }
1017 
1018 static bool amdgpu_ualink_is_local_accel(struct amdgpu_device *adev,
1019 					 u32 accel_id)
1020 {
1021 	struct amdgpu_ualink_info *info = adev->ualink.info;
1022 	unsigned int i;
1023 
1024 	if (!info)
1025 		return false;
1026 
1027 	for (i = 0; i < info->n_local_accels; i++) {
1028 		if (info->local_accels[i] == accel_id)
1029 			return true;
1030 	}
1031 	return false;
1032 }
1033 
1034 static void activate_accelerator(struct amdgpu_device *adev)
1035 {
1036 	int r;
1037 
1038 	if (adev->ualink.info->accel_state >= AMDGPU_UALINK_ACCEL_STATE_ACTIVE)
1039 		return;
1040 
1041 	dev_info(adev->dev,
1042 		 "UALINK: activating accelerator accel_id=%u (accel_state=%d)\n",
1043 		 adev->ualink.info->ppod.accel_id,
1044 		 adev->ualink.info->accel_state);
1045 
1046 	/* Enable incoming NPA address translation with NPA VMID */
1047 	r = psp_ual_set_npa_config(&adev->psp, adev->ualink.psp_if_ver,
1048 				   adev->vm_manager.npa_vmid, true);
1049 	if (r) {
1050 		dev_err(adev->dev, "Failed to set NPA config\n");
1051 		return;
1052 	}
1053 
1054 	r = amdgpu_ualink_manager_start(adev);
1055 	if (r) {
1056 		dev_err(adev->dev, "Failed to start UALink manager\n");
1057 		return;
1058 	}
1059 
1060 	r = amdgpu_ualink_sw_init(adev);
1061 	if (r) {
1062 		dev_err(adev->dev, "Failed to init UALink sw r=%d\n", r);
1063 		amdgpu_ualink_manager_stop(adev);
1064 		return;
1065 	}
1066 
1067 	adev->ualink.info->accel_state = AMDGPU_UALINK_ACCEL_STATE_ACTIVE;
1068 	dev_info(adev->dev,
1069 		 "UALINK: accelerator accel_id=%u is now ACTIVE\n",
1070 		 adev->ualink.info->ppod.accel_id);
1071 }
1072 
1073 static void deactivate_accelerator(struct amdgpu_device *adev)
1074 {
1075 	if (adev->ualink.info->accel_state < AMDGPU_UALINK_ACCEL_STATE_ACTIVE)
1076 		return;
1077 
1078 	dev_info(adev->dev,
1079 		 "UALINK: deactivating accelerator accel_id=%u (accel_state=%d -> PPOD_CONFIGURED)\n",
1080 		 adev->ualink.info->ppod.accel_id,
1081 		 adev->ualink.info->accel_state);
1082 
1083 	/* Disable incoming NPA address translation with NPA VMID */
1084 	psp_ual_set_npa_config(&adev->psp, adev->ualink.psp_if_ver,
1085 			       adev->vm_manager.npa_vmid, false);
1086 	/* ignore return value */
1087 	adev->ualink.info->accel_state =
1088 		AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED;
1089 
1090 	amdgpu_ualink_sw_fini(adev);
1091 	amdgpu_ualink_manager_stop(adev);
1092 }
1093 
1094 static void activate_local_vpod(struct amdgpu_device *adev)
1095 {
1096 	struct amdgpu_ualink_info *info = adev->ualink.info;
1097 	struct amdgpu_device *peer_adev;
1098 	unsigned int accel_id;
1099 	unsigned int i;
1100 
1101 	for (i = 0; i < info->n_local_accels; i++) {
1102 		accel_id = info->local_accels[i];
1103 
1104 		peer_adev = find_peer_adev(accel_id);
1105 		if (WARN_ON(!peer_adev || !peer_adev->ualink.info))
1106 			/* info->local_accels is corrupted? */
1107 			continue;
1108 
1109 		/* Bring the peer up to match the current vPod membership.
1110 		 *
1111 		 * A peer that is not yet ACTIVE (or whose ACTIVE membership
1112 		 * changed on a grow/shrink) has its remote metadata, links and
1113 		 * GART mappings built for a stale member set (or none at all).
1114 		 * Firmware only accepts a full metadata reload while halted, so
1115 		 * surgical per-peer deltas are not possible: fully bounce the
1116 		 * accelerator. deactivate_accelerator() is a no-op when the peer
1117 		 * is not ACTIVE, so this handles first-time bring-up too.
1118 		 * Unchanged ACTIVE peers are left untouched.
1119 		 */
1120 		if (amdgpu_ualink_vpod_membership_changed(peer_adev)) {
1121 			dev_info(peer_adev->dev,
1122 				 "UALINK: (re)configuring vpod for accel_id=%u\n",
1123 				 peer_adev->ualink.info->ppod.accel_id);
1124 			deactivate_accelerator(peer_adev);
1125 			activate_accelerator(peer_adev);
1126 		}
1127 	}
1128 }
1129 
1130 static inline bool __is_vpod_peer(struct amdgpu_ualink_info *info,
1131 				  struct amdgpu_ualink_info *peer_info)
1132 {
1133 	return peer_info->vpod.id == info->vpod.id &&
1134 	       uuid_equal(&peer_info->ppod.id, &info->ppod.id);
1135 }
1136 
1137 static int __check_local_vpod_integrity(struct amdgpu_device *adev)
1138 {
1139 	DECLARE_BITMAP(local_accel_ids, AMDGPU_UALINK_ACCEL_MAX);
1140 	struct amdgpu_ualink_info *info = adev->ualink.info;
1141 	u32 local_accels[AMDGPU_UALINK_LOCAL_ACCELS_MAX];
1142 	struct amdgpu_ualink_info *peer_info;
1143 	struct amdgpu_device *peer_adev;
1144 	unsigned int i, n_local_accels;
1145 	unsigned int accel_id;
1146 	/* Check that all local accelerators listed in vpod_active_accels have
1147 	 * matching pod IDs
1148 	 */
1149 	bitmap_zero(local_accel_ids, AMDGPU_UALINK_ACCEL_MAX);
1150 	n_local_accels = 0;
1151 	__set_bit(info->ppod.accel_id, local_accel_ids);
1152 	local_accels[n_local_accels++] = info->ppod.accel_id;
1153 
1154 	for (i = 0; i < mgpu_info.num_gpu; i++) {
1155 		peer_adev = mgpu_info.gpu_ins[i].adev;
1156 		if (peer_adev == adev || !peer_adev->ualink.info)
1157 			continue;
1158 
1159 		peer_info = peer_adev->ualink.info;
1160 		/* peer device ppod not configured */
1161 		if (peer_info->accel_state <
1162 		    AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED) {
1163 			dev_info(adev->dev,
1164 				 "UALINK: integrity EAGAIN: peer accel_id=%u not ppod-configured (accel_state=%d)\n",
1165 				 peer_info->ppod.accel_id,
1166 				 peer_info->accel_state);
1167 			return -EAGAIN;
1168 		}
1169 
1170 		accel_id = peer_info->ppod.accel_id;
1171 		if (!test_bit(accel_id, info->vpod.active_accel_bits))
1172 			continue;
1173 		/* peer device vpod not configured */
1174 		if (peer_info->accel_state <
1175 		    AMDGPU_UALINK_ACCEL_STATE_VPOD_CONFIGURED) {
1176 			dev_info(adev->dev,
1177 				 "UALINK: integrity EAGAIN: vpod peer accel_id=%u not vpod-configured (accel_state=%d)\n",
1178 				 accel_id, peer_info->accel_state);
1179 			return -EAGAIN;
1180 		}
1181 
1182 		if (!uuid_equal(&peer_info->ppod.id, &info->ppod.id)) {
1183 			dev_warn(adev->dev,
1184 				 "UALINK: integrity fail: peer %u ppod_id doesn't match: %pU != %pU\n",
1185 				 peer_info->ppod.accel_id, &peer_info->ppod.id,
1186 				 &info->ppod.id);
1187 			return -EINVAL;
1188 		}
1189 
1190 		if (peer_info->ppod.size != info->ppod.size) {
1191 			dev_warn(adev->dev,
1192 				 "UALINK: integrity fail: peer %u ppod_size doesn't match: %u != %u\n",
1193 				 accel_id, peer_info->ppod.size,
1194 				 info->ppod.size);
1195 			return -EINVAL;
1196 		}
1197 
1198 		if (peer_info->vpod.id != info->vpod.id) {
1199 			dev_warn(adev->dev,
1200 				 "UALINK: integrity fail: peer %u vpod_id doesn't match: %u != %u\n",
1201 				 accel_id, peer_info->vpod.id, info->vpod.id);
1202 			return -EINVAL;
1203 		}
1204 		if (peer_info->vpod.size != info->vpod.size) {
1205 			dev_warn(adev->dev,
1206 				 "UALINK: integrity fail: peer %u vpod_size doesn't match: %u != %u\n",
1207 				 accel_id, peer_info->vpod.size,
1208 				 info->vpod.size);
1209 			return -EINVAL;
1210 		}
1211 		if (peer_info->vpod.addr_mode != info->vpod.addr_mode) {
1212 			dev_warn(adev->dev,
1213 				 "UALINK: integrity fail: peer %u addr_mode doesn't match: %u != %u\n",
1214 				 accel_id, peer_info->vpod.addr_mode,
1215 				 info->vpod.addr_mode);
1216 			return -EINVAL;
1217 		}
1218 		if (!bitmap_equal(peer_info->vpod.active_accel_bits,
1219 				  info->vpod.active_accel_bits,
1220 				  AMDGPU_UALINK_ACCEL_MAX)) {
1221 			dev_warn(adev->dev,
1222 				 "UALINK: integrity fail: peer %u vpod_active_accels don't match\n",
1223 				 accel_id);
1224 			return -EINVAL;
1225 		}
1226 
1227 		if (__test_and_set_bit(accel_id, local_accel_ids)) {
1228 			dev_warn(adev->dev,
1229 				 "UALINK: integrity fail: duplicate accel_id %u among local vpod peers\n",
1230 				 accel_id);
1231 			return -EINVAL;
1232 		}
1233 		local_accels[n_local_accels++] = accel_id;
1234 	}
1235 
1236 	for (i = 0; i < mgpu_info.num_gpu; i++) {
1237 		peer_adev = mgpu_info.gpu_ins[i].adev;
1238 		peer_info = peer_adev->ualink.info;
1239 
1240 		if (!peer_info)
1241 			continue;
1242 		if (peer_adev != adev && !__is_vpod_peer(info, peer_info))
1243 			continue;
1244 
1245 		peer_info->n_local_accels = n_local_accels;
1246 		memcpy(peer_info->local_accels, local_accels,
1247 		       sizeof(local_accels));
1248 	}
1249 
1250 	return 0;
1251 }
1252 
1253 static void __amdgpu_ualink_activate_vpod_locked(struct amdgpu_device *adev)
1254 {
1255 	int ret;
1256 
1257 	if (adev->ualink.info->accel_state <
1258 		    AMDGPU_UALINK_ACCEL_STATE_VPOD_CONFIGURED ||
1259 	    adev->ualink.info->accel_state ==
1260 		    AMDGPU_UALINK_ACCEL_STATE_ERROR)
1261 		return;
1262 
1263 	ret = __check_local_vpod_integrity(adev);
1264 	if (ret && ret != -EAGAIN) {
1265 		dev_err(adev->dev,
1266 			"Local vpod integrity check failed: %d\n", ret);
1267 		return;
1268 	}
1269 	if (ret == -EAGAIN) {
1270 		dev_info(adev->dev,
1271 			 "UALINK: activate deferred, waiting for local vpod peers to reach VPOD_CONFIGURED\n");
1272 		return;
1273 	}
1274 
1275 	dev_info(adev->dev,
1276 		 "UALINK: integrity OK, applying local vpod (%u local accels)\n",
1277 		 adev->ualink.info->n_local_accels);
1278 	activate_local_vpod(adev);
1279 }
1280 
1281 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
1282 UALINK_VALUE_SHOW(vpod_config, vpod_id,   vpod.id,   "%u");
1283 UALINK_VALUE_SHOW(vpod_config, vpod_size, vpod.size, "%u");
1284 UALINK_IDBITS_SHOW(vpod_config, vpod_active_accels, vpod.active_accel_bits);
1285 UALINK_ENUM_SHOW(vpod_config, addr_mode, vpod.addr_mode);
1286 
1287 UALINK_VALUE_STORE(vpod_config, vpod_id,   vpod.id,   u32, 10);
1288 UALINK_VALUE_STORE(vpod_config, vpod_size, vpod.size, u32, 10);
1289 UALINK_IDBITS_STORE(vpod_config, vpod_active_accels, vpod.active_accel_bits,
1290 		    AMDGPU_UALINK_ACCEL_MAX);
1291 UALINK_ENUM_STORE(vpod_config, addr_mode, vpod.addr_mode);
1292 
1293 static ssize_t ualink_vpod_config_commit_store(struct kobject *kobj,
1294 					       struct kobj_attribute *attr,
1295 					       const char *buf, size_t count)
1296 {
1297 	struct amdgpu_ualink_vpod_config *config = to_ualink_vpod_config(kobj);
1298 	struct amdgpu_ualink_info *info = to_ualink_info(kobj->parent);
1299 	struct device *dev = kobj_to_dev(info->kobj.parent);
1300 	struct drm_device *ddev = dev_get_drvdata(dev);
1301 	struct amdgpu_device *adev = drm_to_adev(ddev);
1302 	enum amdgpu_ualink_accel_state prev_state;
1303 	u32 prev_vpod_id;
1304 	int r;
1305 
1306 	if (!sysfs_streq(buf, "true"))
1307 		return -EINVAL;
1308 
1309 	dev_dbg(adev->dev,
1310 		"UALINK: vpod-commit enter: accel_state=%d staged vpod_id=%u vpod_size=%u addr_mode=%u\n",
1311 		info->accel_state, config->vpod.id, config->vpod.size,
1312 		config->vpod.addr_mode);
1313 
1314 	if (info->accel_state < AMDGPU_UALINK_ACCEL_STATE_PPOD_CONFIGURED) {
1315 		dev_warn(adev->dev,
1316 			 "UALINK: vpod-commit rejected, ppod not configured (accel_state=%d)\n",
1317 			 info->accel_state);
1318 		return -EINVAL;
1319 	}
1320 
1321 	prev_state = info->accel_state;
1322 	prev_vpod_id = info->vpod.id;
1323 	r = psp_ual_set_vpod_config(&adev->psp, adev->ualink.psp_if_ver,
1324 				    config);
1325 	if (r) {
1326 		dev_warn(adev->dev,
1327 			 "UALINK: vpod-commit psp_ual_set_vpod_config failed: %d\n",
1328 			 r);
1329 		return r;
1330 	}
1331 
1332 	r = psp_ual_query_info(&adev->psp, adev->ualink.psp_if_ver, info, NULL);
1333 	if (r) {
1334 		dev_warn(adev->dev,
1335 			 "UALINK: vpod-commit psp_ual_query_info failed: %d\n",
1336 			 r);
1337 		return r;
1338 	}
1339 
1340 	dev_dbg(adev->dev,
1341 		"UALINK: vpod-commit fw read-back: vpod_id=%u vpod_size=%u accel_id=%u ppod.size=%u addr_mode=%u\n",
1342 		info->vpod.id, info->vpod.size, info->ppod.accel_id,
1343 		info->ppod.size, info->vpod.addr_mode);
1344 
1345 	if (info->vpod.id != AMDGPU_UALINK_VPOD_ID_INVALID &&
1346 	    !__check_vpod_info(adev, info)) {
1347 		dev_err(adev->dev,
1348 			"UALINK: vpod-commit __check_vpod_info() failed: %d\n",
1349 			r);
1350 		return -EINVAL;
1351 	}
1352 
1353 	/* The integrity check makes sure each new GPU is consistent with the
1354 	 * other GPUs already in the vPod. All known local GPUs can become
1355 	 * "ready" at the same time.
1356 	 *
1357 	 * Misconfiguration of one GPU does not reduce the state of other GPUs
1358 	 * already in the vPod. GPU is intentionally not put to ERROR state if
1359 	 * misconfiguration occurs.
1360 	 */
1361 	r = amdgpu_ualink_update_accel_state(adev, prev_state, prev_vpod_id,
1362 					     UAL_CFG_VPOD);
1363 	if (r)
1364 		return r;
1365 
1366 	return count;
1367 }
1368 
1369 #define UALINK_VPOD_CONFIG_ATTR(name) __ATTR(name, 0600,		\
1370 		ualink_vpod_config_##name##_show,			\
1371 		ualink_vpod_config_##name##_store)
1372 static struct kobj_attribute ualink_vpod_config_vpod_id   = UALINK_VPOD_CONFIG_ATTR(vpod_id);
1373 static struct kobj_attribute ualink_vpod_config_vpod_size = UALINK_VPOD_CONFIG_ATTR(vpod_size);
1374 static struct kobj_attribute ualink_vpod_config_vpod_active_accels =
1375 						UALINK_VPOD_CONFIG_ATTR(vpod_active_accels);
1376 static struct kobj_attribute ualink_vpod_config_addr_mode = UALINK_VPOD_CONFIG_ATTR(addr_mode);
1377 static struct kobj_attribute ualink_vpod_config_commit = __ATTR(commit, 0200, NULL,
1378 								ualink_vpod_config_commit_store);
1379 
1380 static const struct attribute *ualink_vpod_config_attrs[] = {
1381 	&ualink_vpod_config_vpod_id.attr,
1382 	&ualink_vpod_config_vpod_size.attr,
1383 	&ualink_vpod_config_vpod_active_accels.attr,
1384 	&ualink_vpod_config_addr_mode.attr,
1385 	&ualink_vpod_config_commit.attr,
1386 	NULL
1387 };
1388 #endif
1389 
1390 static void ualink_vpod_config_release(struct kobject *kobj)
1391 {
1392 	kfree(to_ualink_vpod_config(kobj));
1393 }
1394 
1395 static const struct kobj_type ualink_vpod_config_ktype = {
1396 	.release = ualink_vpod_config_release,
1397 	.sysfs_ops = &kobj_sysfs_ops
1398 };
1399 
1400 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
1401 UALINK_VALUE_SHOW(station_config, flags, flags, "0x%x");
1402 
1403 UALINK_VALUE_STORE(station_config, flags, flags, u8, 16);
1404 
1405 static size_t lane_bitmap_to_string(char *str,
1406 		const struct amdgpu_ualink_station_config *stations)
1407 {
1408 	size_t i;
1409 
1410 	for (i = 0; i < stations->n_stations; i++)
1411 		str[i] = stations->lane_en_bitmap[i] +
1412 			(stations->lane_en_bitmap[i] < 10 ? '0' : 'a' - 10);
1413 	str[i] = '\0';
1414 
1415 	return i;
1416 }
1417 static ssize_t
1418 ualink_station_config_lane_en_bitmap_show(struct kobject *kobj,
1419 					  struct kobj_attribute *attr,
1420 					  char *buf)
1421 {
1422 	struct amdgpu_ualink_station_config *stations = to_ualink_station_config(kobj);
1423 	char str[AMDGPU_UALINK_STATIONS_MAX + 1];
1424 
1425 	lane_bitmap_to_string(str, stations);
1426 	return sysfs_emit(buf, "%s\n", str);
1427 }
1428 static ssize_t
1429 ualink_station_config_lane_en_bitmap_store(struct kobject *kobj,
1430 					   struct kobj_attribute *attr,
1431 					   const char *buf, size_t count)
1432 {
1433 	struct amdgpu_ualink_station_config *stations = to_ualink_station_config(kobj);
1434 	u8 lane_en_bitmap[AMDGPU_UALINK_STATIONS_MAX];
1435 	u32 n_stations = 0;
1436 	bool end = false;
1437 	size_t i;
1438 
1439 	for (i = 0; i < count; i++) {
1440 		/* Accept any number of \n in the end */
1441 		if (buf[i] == '\n') {
1442 			end = true;
1443 			continue;
1444 		}
1445 		/* Don't accept any more data after \n */
1446 		if (end)
1447 			return -EINVAL;
1448 		/* Don't accept more data than the array size */
1449 		if (i >= sizeof(lane_en_bitmap))
1450 			return -ENOSPC;
1451 		/* Accept hex digits */
1452 		if (buf[i] >= '0' && buf[i] <= '9')
1453 			lane_en_bitmap[n_stations++] = buf[i] - '0';
1454 		else if (buf[i] >= 'a' && buf[i] <= 'f')
1455 			lane_en_bitmap[n_stations++] = buf[i] + 10 - 'a';
1456 		else if (buf[i] >= 'A' && buf[i] <= 'F')
1457 			lane_en_bitmap[n_stations++] = buf[i] + 10 - 'A';
1458 		else
1459 			return -EINVAL;
1460 	}
1461 
1462 	memcpy(stations->lane_en_bitmap, lane_en_bitmap, sizeof(lane_en_bitmap));
1463 	stations->n_stations = n_stations;
1464 	return i;
1465 }
1466 
1467 static ssize_t ualink_station_config_commit_store(struct kobject *kobj,
1468 						  struct kobj_attribute *attr,
1469 						  const char *buf, size_t count)
1470 {
1471 	struct amdgpu_ualink_station_config *stations = to_ualink_station_config(kobj);
1472 	struct amdgpu_ualink_info *info = to_ualink_info(kobj->parent);
1473 	struct device *dev = kobj_to_dev(info->kobj.parent);
1474 	struct drm_device *ddev = dev_get_drvdata(dev);
1475 	struct amdgpu_device *adev = drm_to_adev(ddev);
1476 	int r;
1477 
1478 	/* DF reconfiguration does not interact with accelerator state */
1479 
1480 	if (!sysfs_streq(buf, "true"))
1481 		return -EINVAL;
1482 
1483 	r = psp_ual_set_station_config(&adev->psp, adev->ualink.psp_if_ver, stations);
1484 	if (r)
1485 		return r;
1486 
1487 	return count;
1488 }
1489 
1490 #define UALINK_STATION_CONFIG_ATTR(name) __ATTR(name, 0600,		\
1491 		ualink_station_config_##name##_show,			\
1492 		ualink_station_config_##name##_store)
1493 static struct kobj_attribute ualink_station_config_flags  = UALINK_STATION_CONFIG_ATTR(flags);
1494 static struct kobj_attribute ualink_station_config_lane_en_bitmap =
1495 							UALINK_STATION_CONFIG_ATTR(lane_en_bitmap);
1496 static struct kobj_attribute ualink_station_config_commit =
1497 				__ATTR(commit, 0200, NULL, ualink_station_config_commit_store);
1498 
1499 static const struct attribute *ualink_station_config_attrs[] = {
1500 	&ualink_station_config_flags.attr,
1501 	&ualink_station_config_lane_en_bitmap.attr,
1502 	&ualink_station_config_commit.attr,
1503 	NULL
1504 };
1505 #endif
1506 
1507 static void ualink_station_config_release(struct kobject *kobj)
1508 {
1509 	kfree(to_ualink_station_config(kobj));
1510 }
1511 
1512 static const struct kobj_type ualink_station_config_ktype = {
1513 	.release = ualink_station_config_release,
1514 	.sysfs_ops = &kobj_sysfs_ops
1515 };
1516 
1517 int ualink_ip_sw_init(struct amdgpu_ip_block *ip_block)
1518 {
1519 	struct amdgpu_ualink_station_config *stations;
1520 	struct amdgpu_ualink_vpod_config *vpod_config;
1521 	struct amdgpu_ualink_ppod_setup *ppod_setup;
1522 	struct amdgpu_device *adev = ip_block->adev;
1523 	struct amdgpu_ualink_info *info;
1524 
1525 	info = kzalloc(sizeof(*info), GFP_KERNEL);
1526 	ppod_setup = kzalloc(sizeof(*ppod_setup), GFP_KERNEL);
1527 	vpod_config = kzalloc(sizeof(*vpod_config), GFP_KERNEL);
1528 	stations = kzalloc(sizeof(*stations), GFP_KERNEL);
1529 	if (!info || !ppod_setup || !vpod_config || !stations) {
1530 		kfree(info);
1531 		kfree(ppod_setup);
1532 		kfree(vpod_config);
1533 		kfree(stations);
1534 		return -ENOMEM;
1535 	}
1536 
1537 	info->ppod.accel_id = 0xffffffff;
1538 	info->ppod.bandwidth = 0xffffffff;
1539 	info->ppod.latency = 0xffffffff;
1540 	info->vpod.id = AMDGPU_UALINK_VPOD_ID_INVALID;
1541 	info->vpod.addr_mode = AMDGPU_UALINK_ADDR_MODE_MAX;
1542 
1543 	/*
1544 	 * Initialize the kobjects here so their lifetime is tied to the UALink
1545 	 * manager software state. amdgpu_ualink_object_fini() drops the final
1546 	 * reference via kobject_put().
1547 	 */
1548 	kobject_init(&info->kobj, &ualink_info_ktype);
1549 	kobject_init(&ppod_setup->kobj, &ualink_ppod_setup_ktype);
1550 	kobject_init(&vpod_config->kobj, &ualink_vpod_config_ktype);
1551 	kobject_init(&stations->kobj, &ualink_station_config_ktype);
1552 
1553 	adev->ualink.info = info;
1554 	adev->ualink.setup = ppod_setup;
1555 	adev->ualink.config = vpod_config;
1556 	adev->ualink.stations = stations;
1557 
1558 	return 0;
1559 }
1560 
1561 int ualink_ip_sw_fini(struct amdgpu_ip_block *ip_block)
1562 {
1563 	amdgpu_ualink_object_fini(ip_block->adev);
1564 	return 0;
1565 }
1566 
1567 static int ualink_kobj_add(struct kobject *kobj, struct kobject *parent,
1568 			   const char *name, const struct attribute **attrs)
1569 {
1570 	int r;
1571 
1572 	r = kobject_add(kobj, parent, "%s", name);
1573 	if (r)
1574 		return r;
1575 	r = sysfs_create_files(kobj, attrs);
1576 	if (r)
1577 		kobject_del(kobj);
1578 
1579 	return r;
1580 }
1581 
1582 static void amdgpu_ualink_xcp_sysfs_init(struct amdgpu_device *adev);
1583 static void amdgpu_ualink_xcp_sysfs_fini(struct amdgpu_device *adev);
1584 
1585 int amdgpu_ualink_sysfs_init(struct amdgpu_device *adev)
1586 {
1587 	struct amdgpu_ualink_info *info = adev->ualink.info;
1588 	int r;
1589 
1590 	if (adev->ualink.mgr_state != AMDGPU_UALINK_INIT_COMPLETE)
1591 		return 0;
1592 
1593 	/* ualink parent node */
1594 	r = ualink_kobj_add(&info->kobj, &adev->dev->kobj, "ualink",
1595 			    ualink_info_attrs);
1596 	if (r)
1597 		goto err;
1598 
1599 #ifdef UALINK_ENABLE_DEPRECATED_CONFIG_SYSFS
1600 	r = ualink_kobj_add(&adev->ualink.setup->kobj, &info->kobj, "setup",
1601 			    ualink_ppod_setup_attrs);
1602 	if (r)
1603 		goto err_info;
1604 
1605 	r = ualink_kobj_add(&adev->ualink.config->kobj, &info->kobj, "config",
1606 			    ualink_vpod_config_attrs);
1607 	if (r)
1608 		goto err_setup;
1609 
1610 	r = ualink_kobj_add(&adev->ualink.stations->kobj, &info->kobj,
1611 			    "stations", ualink_station_config_attrs);
1612 	if (r)
1613 		goto err_config;
1614 #else
1615 	r = kobject_add(&adev->ualink.setup->kobj, &info->kobj, "%s",
1616 			"setup");
1617 	if (r)
1618 		goto err_info;
1619 
1620 	r = kobject_add(&adev->ualink.config->kobj, &info->kobj, "%s",
1621 			"config");
1622 	if (r)
1623 		goto err_setup;
1624 
1625 	r = kobject_add(&adev->ualink.stations->kobj, &info->kobj, "%s",
1626 			"stations");
1627 	if (r)
1628 		goto err_config;
1629 #endif
1630 
1631 	amdgpu_ualink_xcp_sysfs_init(adev);
1632 	adev->ualink.sysfs_init = true;
1633 
1634 	return 0;
1635 
1636 err_config:
1637 	kobject_del(&adev->ualink.config->kobj);
1638 err_setup:
1639 	kobject_del(&adev->ualink.setup->kobj);
1640 err_info:
1641 	kobject_del(&info->kobj);
1642 err:
1643 	dev_warn(adev->dev, "Failed to create UALink sysfs: %d\n", r);
1644 	return 0;
1645 }
1646 
1647 void amdgpu_ualink_sysfs_fini(struct amdgpu_device *adev)
1648 {
1649 	if (!adev->ualink.sysfs_init)
1650 		return;
1651 
1652 	amdgpu_ualink_xcp_sysfs_fini(adev);
1653 	kobject_del(&adev->ualink.stations->kobj);
1654 	kobject_del(&adev->ualink.config->kobj);
1655 	kobject_del(&adev->ualink.setup->kobj);
1656 	kobject_del(&adev->ualink.info->kobj);
1657 	adev->ualink.sysfs_init = false;
1658 }
1659 
1660 static int amdgpu_ualink_xcp_sysfs_add(struct amdgpu_xcp *xcp)
1661 {
1662 	struct amdgpu_device *adev = xcp->xcp_mgr->adev;
1663 	int r;
1664 
1665 	r = kobject_init_and_add(&xcp->ualink.kobj, &ualink_xcp_info_ktype,
1666 				 &xcp->ddev->dev->kobj, "ualink");
1667 	if (r)
1668 		goto err;
1669 
1670 	r = sysfs_create_group(&xcp->ualink.kobj, &ualink_xcp_info_group);
1671 	if (r)
1672 		goto err;
1673 
1674 	/* pin info so it outlives this node regardless of teardown order */
1675 	kobject_get(&adev->ualink.info->kobj);
1676 	xcp->ualink.sysfs = true;
1677 	return 0;
1678 err:
1679 	kobject_put(&xcp->ualink.kobj);
1680 	return r;
1681 }
1682 
1683 void amdgpu_ualink_xcp_sysfs_update(struct amdgpu_xcp *xcp)
1684 {
1685 	if (!xcp->ualink.sysfs)
1686 		return;
1687 
1688 	sysfs_update_group(&xcp->ualink.kobj, &ualink_xcp_info_group);
1689 }
1690 
1691 static void amdgpu_ualink_xcp_sysfs_remove(struct amdgpu_xcp *xcp)
1692 {
1693 	struct amdgpu_device *adev = xcp->xcp_mgr->adev;
1694 
1695 	if (!xcp->ualink.sysfs)
1696 		return;
1697 
1698 	/* group is only populated for valid partitions */
1699 	if (xcp->valid)
1700 		sysfs_remove_group(&xcp->ualink.kobj, &ualink_xcp_info_group);
1701 	kobject_put(&adev->ualink.info->kobj);
1702 	kobject_put(&xcp->ualink.kobj);
1703 	xcp->ualink.sysfs = false;
1704 }
1705 
1706 static void amdgpu_ualink_xcp_sysfs_init(struct amdgpu_device *adev)
1707 {
1708 	struct amdgpu_xcp *xcp;
1709 	int i;
1710 
1711 	if (!adev->xcp_mgr)
1712 		return;
1713 
1714 	for (i = 0; i < MAX_XCP; i++) {
1715 		xcp = &adev->xcp_mgr->xcp[i];
1716 		if (!xcp->ddev || amdgpu_xcp_is_primary(xcp))
1717 			continue;
1718 		amdgpu_ualink_xcp_sysfs_add(xcp);
1719 	}
1720 }
1721 
1722 static void amdgpu_ualink_xcp_sysfs_fini(struct amdgpu_device *adev)
1723 {
1724 	struct amdgpu_xcp *xcp;
1725 	int i;
1726 
1727 	if (!adev->xcp_mgr)
1728 		return;
1729 
1730 	for (i = 0; i < MAX_XCP; i++) {
1731 		xcp = &adev->xcp_mgr->xcp[i];
1732 		amdgpu_ualink_xcp_sysfs_remove(xcp);
1733 	}
1734 }
1735 
1736 static int amdgpu_ualink_npa_alloc_va(struct amdgpu_device *adev,
1737 			       struct drm_mm_node *mm_node,
1738 			       u64 va, u64 range_start,
1739 			       u64 range_end, int size)
1740 {
1741 	struct amdgpu_ualink_npa_mm *npa_mm = &adev->ualink.npa_mm;
1742 	u64 alignment = 0;
1743 	int ret;
1744 
1745 	mutex_lock(&npa_mm->mm_lock);
1746 	if (va) {
1747 		mm_node->start = va;
1748 		mm_node->size = size;
1749 		ret = drm_mm_reserve_node(&npa_mm->mm, mm_node);
1750 	} else {
1751 		if (!range_start && !range_end) {
1752 			range_start = npa_mm->va_start;
1753 			range_end = npa_mm->va_start + npa_mm->va_size;
1754 		}
1755 
1756 		/* If size is greater than 2MB (or 512 pages),
1757 		 * align it to 2MB (or 512 pages) granularity.
1758 		 */
1759 		if (size >= 0x200)
1760 			alignment = 0x200;
1761 
1762 		ret = drm_mm_insert_node_in_range(&npa_mm->mm, mm_node, size,
1763 						  alignment, 0, range_start,
1764 						  range_end, 0);
1765 	}
1766 	mutex_unlock(&npa_mm->mm_lock);
1767 
1768 	if (ret)
1769 		dev_err(adev->dev, "Failed to allocate NPA address\n");
1770 
1771 	return ret;
1772 }
1773 
1774 static void amdgpu_ualink_npa_free_va(struct amdgpu_device *adev,
1775 			       struct drm_mm_node *mm_node)
1776 {
1777 	struct amdgpu_ualink_npa_mm *npa_mm = &adev->ualink.npa_mm;
1778 
1779 	mutex_lock(&npa_mm->mm_lock);
1780 	drm_mm_remove_node(mm_node);
1781 	mutex_unlock(&npa_mm->mm_lock);
1782 }
1783 
1784 static void amdgpu_ualink_npa_mm_init(struct amdgpu_device *adev)
1785 {
1786 	struct amdgpu_ualink_npa_mm *npa_mm = &adev->ualink.npa_mm;
1787 	u32 addr_mode = adev->ualink.info->vpod.addr_mode;
1788 	u64 va_size;
1789 
1790 	mutex_init(&npa_mm->mm_lock);
1791 
1792 	if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT) {
1793 		/* 51 bit address space in Source-Identification mode.
1794 		 * 39 bits in page granularity.
1795 		 */
1796 		npa_mm->va_start = 0;
1797 		va_size = GENMASK_ULL(38, 0);
1798 	} else {
1799 		/* 41 bit address space in Source-Alias mode.
1800 		 * 29 bits in page granularity.
1801 		 */
1802 		/* First 8MB is reserved for Metadata NPAs */
1803 		npa_mm->va_start = 0x800;
1804 		va_size = GENMASK_ULL(28, 0);
1805 	}
1806 
1807 	npa_mm->va_size = va_size - npa_mm->va_start;
1808 	drm_mm_init(&npa_mm->mm, npa_mm->va_start, npa_mm->va_size);
1809 }
1810 
1811 static void amdgpu_ualink_npa_mm_fini(struct amdgpu_device *adev)
1812 {
1813 	mutex_destroy(&adev->ualink.npa_mm.mm_lock);
1814 	drm_mm_takedown(&adev->ualink.npa_mm.mm);
1815 }
1816 
1817 /* The caller of this function is expected to hold the XA lock when calling
1818  * this function.
1819  */
1820 static void amdgpu_generate_ualink_handle(struct amdgpu_device *adev,
1821 				   struct amdgpu_ualink_handle *handle)
1822 {
1823 	bool unique;
1824 
1825 	do {
1826 		handle->handle_lo = get_random_u64();
1827 		/* Replace bottom 10 bits in handle_lo with accId */
1828 		handle->handle_lo &= ~AMDGPU_UALINK_HANDLE_ACCID_MASK;
1829 		handle->handle_lo |= adev->ualink.info->ppod.accel_id;
1830 
1831 		/* Don't generate/store a Handle with value 0. */
1832 		if (!handle->handle_lo)
1833 			continue;
1834 
1835 		/* Find if the handle already exists in the exporter xarray.
1836 		 * If it already exists, then regenerate the handle since we
1837 		 * want the handle to be unique.
1838 		 */
1839 		unique = !xa_load(&adev->ualink.exp_xa, handle->handle_lo);
1840 	} while (!unique);
1841 
1842 	handle->handle_hi = get_random_u64();
1843 	dev_dbg(adev->dev, "GENERATE-HANDLE: generated handle: %llx:%llx\n",
1844 		handle->handle_hi, handle->handle_lo);
1845 }
1846 
1847 static void amdgpu_ualink_cleanup_exp_xa_node(struct kref *ref)
1848 {
1849 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
1850 	struct amdgpu_device *adev;
1851 
1852 	exp_xa_node = container_of(ref, struct amdgpu_ualink_exp_xa_node,
1853 				   refcount);
1854 	adev = amdgpu_ttm_adev(exp_xa_node->bo->tbo.bdev);
1855 	queue_work(adev->ualink.npa_wq, &exp_xa_node->cleanup_work);
1856 }
1857 
1858 static void amdgpu_ualink_cleanup_imp_xa_node(struct kref *ref)
1859 {
1860 	struct amdgpu_ualink_imp_xa_node *imp_xa_node;
1861 	struct amdgpu_device *adev;
1862 
1863 	imp_xa_node = container_of(ref, struct amdgpu_ualink_imp_xa_node,
1864 				   refcount);
1865 	adev = imp_xa_node->adev;
1866 
1867 	dev_dbg(adev->dev, "IMP-CLEANUP: Remove entry from XA for handle:%llx:%llx\n",
1868 		imp_xa_node->handle.handle_hi, imp_xa_node->handle.handle_lo);
1869 
1870 	/* Remove node from the Xarray */
1871 	if (!xa_erase(&adev->ualink.imp_xa, imp_xa_node->handle.handle_lo))
1872 		dev_err(adev->dev, "IMP-CLEANUP: Failed to find entry in XA for handle:%llx:%llx\n",
1873 			imp_xa_node->handle.handle_hi, imp_xa_node->handle.handle_lo);
1874 
1875 	if (imp_xa_node->npa_addr && imp_xa_node->size && imp_xa_node->dmabuf) {
1876 		dev_dbg(adev->dev,
1877 			"IMP-CLEANUP: dmabuf free for NPA:%llx handle:%llx:%llx, fc:%lu\n",
1878 			imp_xa_node->npa_addr, imp_xa_node->handle.handle_hi,
1879 			imp_xa_node->handle.handle_lo,
1880 			file_count(imp_xa_node->dmabuf->file));
1881 		dma_buf_put(imp_xa_node->dmabuf);
1882 		drm_gem_handle_delete(adev->ualink.client.file,
1883 				      imp_xa_node->gem_handle);
1884 
1885 	}
1886 
1887 	dev_dbg(adev->dev, "IMP-CLEANUP: Freeing XA entry for handle:%llx:%llx\n",
1888 		imp_xa_node->handle.handle_hi, imp_xa_node->handle.handle_lo);
1889 
1890 	kfree(imp_xa_node);
1891 }
1892 
1893 static int amdgpu_ualink_exp_xa_entry_get(struct amdgpu_ualink_exp_xa_node *exp_xa_node)
1894 {
1895 	return kref_get_unless_zero(&exp_xa_node->refcount);
1896 }
1897 
1898 static void amdgpu_ualink_exp_xa_entry_put(struct amdgpu_ualink_exp_xa_node *exp_xa_node)
1899 {
1900 	kref_put(&exp_xa_node->refcount, amdgpu_ualink_cleanup_exp_xa_node);
1901 }
1902 
1903 static int amdgpu_ualink_imp_xa_entry_get(struct amdgpu_ualink_imp_xa_node *imp_xa_node)
1904 {
1905 	return kref_get_unless_zero(&imp_xa_node->refcount);
1906 }
1907 
1908 static void amdgpu_ualink_imp_xa_entry_put(struct amdgpu_ualink_imp_xa_node *imp_xa_node)
1909 {
1910 	kref_put(&imp_xa_node->refcount, amdgpu_ualink_cleanup_imp_xa_node);
1911 }
1912 
1913 static int amdgpu_ualink_send_npa_release_msg(struct amdgpu_device *adev,
1914 				    u32 remote_acc_id,
1915 				    struct amdgpu_ualink_handle handle)
1916 {
1917 	u32 dw0, dw1, dw2, dw3;
1918 
1919 	dw0 = lower_32_bits(handle.handle_lo);
1920 	dw0 &= ~AMDGPU_UALINK_MESSAGE_HEADER_MASK;
1921 	dw0 |= AMDGPU_UALINK_NPA_RELEASE_MSG;
1922 
1923 	dw1 = upper_32_bits(handle.handle_lo);
1924 	dw2 = lower_32_bits(handle.handle_hi);
1925 	dw3 = upper_32_bits(handle.handle_hi);
1926 
1927 	dev_dbg(adev->dev, "SEND NPA-RELEASE: remote_acc_id %u handle %llx:%llx dw[0-3] 0x%x 0x%x 0x%x 0x%x\n",
1928 		remote_acc_id, handle.handle_hi, handle.handle_lo, dw0, dw1, dw2, dw3);
1929 
1930 	return amdgpu_ualink_remote_interrupt(adev, remote_acc_id, dw0, dw1,
1931 					      dw2, dw3);
1932 }
1933 
1934 static int amdgpu_ualink_send_npa_revoke_msg(struct amdgpu_device *adev,
1935 					u32 remote_acc_id,
1936 					struct amdgpu_ualink_handle handle)
1937 {
1938 	u32 dw0, dw1, dw2, dw3;
1939 
1940 	dw0 = lower_32_bits(handle.handle_lo);
1941 	dw0 &= ~AMDGPU_UALINK_MESSAGE_HEADER_MASK;
1942 	dw0 |= AMDGPU_UALINK_NPA_REVOKE_MSG;
1943 
1944 	dw1 = upper_32_bits(handle.handle_lo);
1945 	dw2 = lower_32_bits(handle.handle_hi);
1946 	dw3 = upper_32_bits(handle.handle_hi);
1947 
1948 	dev_dbg(adev->dev, "SEND NPA-REVOKE: remote_acc_id %u handle %llx:%llx dw[0-3] 0x%x 0x%x 0x%x 0x%x\n",
1949 		remote_acc_id, handle.handle_hi, handle.handle_lo, dw0, dw1, dw2, dw3);
1950 
1951 	return amdgpu_ualink_remote_interrupt(adev, remote_acc_id, dw0, dw1,
1952 					      dw2, dw3);
1953 }
1954 
1955 static int amdgpu_ualink_send_npa_fail_msg(struct amdgpu_device *adev,
1956 				    u32 remote_acc_id,
1957 				    struct amdgpu_ualink_handle handle,
1958 				    u32 fail_reason)
1959 {
1960 	u32 dw0, dw1, dw2, dw3;
1961 
1962 	dw0 = lower_32_bits(handle.handle_lo);
1963 	dw0 &= ~AMDGPU_UALINK_MESSAGE_HEADER_MASK;
1964 	dw0 |= AMDGPU_UALINK_NPA_FAIL_MSG;
1965 
1966 	dw1 = upper_32_bits(handle.handle_lo);
1967 	dw2 = fail_reason & 0xFF;
1968 	dw3 = 0;
1969 
1970 	dev_dbg(adev->dev, "SEND NPA-FAIL: remote_acc_id %u handle 0x%llx:%llx dw[0-3] 0x%x 0x%x 0x%x 0x%x\n",
1971 		remote_acc_id, handle.handle_hi, handle.handle_lo, dw0, dw1, dw2, dw3);
1972 
1973 	return amdgpu_ualink_remote_interrupt(adev, remote_acc_id, dw0, dw1,
1974 					      dw2, dw3);
1975 }
1976 
1977 static int amdgpu_ualink_send_npa_rsp_msg(struct amdgpu_device *adev,
1978 					  u32 remote_acc_id,
1979 					  struct amdgpu_ualink_handle handle,
1980 					  u32 npa_addr, u32 size)
1981 {
1982 	u32 dw0, dw1, dw2, dw3;
1983 
1984 	dw0 = lower_32_bits(handle.handle_lo);
1985 	dw0 &= ~AMDGPU_UALINK_MESSAGE_HEADER_MASK;
1986 	dw0 |= AMDGPU_UALINK_NPA_RSP_MSG;
1987 
1988 	dw1 = upper_32_bits(handle.handle_lo);
1989 	dw2 = size;
1990 	dw3 = npa_addr;
1991 
1992 	dev_dbg(adev->dev, "SEND NPA-RSP: remote_acc_id %u handle %llx:%llx dw[0-3] 0x%x 0x%x 0x%x 0x%x\n",
1993 		remote_acc_id, handle.handle_hi, handle.handle_lo, dw0, dw1, dw2, dw3);
1994 
1995 	return amdgpu_ualink_remote_interrupt(adev, remote_acc_id, dw0, dw1,
1996 					      dw2, dw3);
1997 }
1998 
1999 static int amdgpu_ualink_send_npa_req_msg(struct amdgpu_device *adev,
2000 					  u32 remote_acc_id,
2001 					  struct amdgpu_ualink_handle handle)
2002 {
2003 	u32 dw0, dw1, dw2, dw3;
2004 
2005 	dw0 =  lower_32_bits(handle.handle_lo);
2006 	dw0 &= ~AMDGPU_UALINK_MESSAGE_HEADER_MASK;
2007 	dw0 |= AMDGPU_UALINK_NPA_REQ_MSG;
2008 
2009 	dw1 = upper_32_bits(handle.handle_lo);
2010 	dw2 = lower_32_bits(handle.handle_hi);
2011 	dw3 = upper_32_bits(handle.handle_hi);
2012 
2013 	dev_dbg(adev->dev, "SEND NPA-REQ: remote_acc_id %u handle 0x%llx:%llx dw[0-3] 0x%x 0x%x 0x%x 0x%x\n",
2014 		remote_acc_id, handle.handle_hi, handle.handle_lo, dw0, dw1, dw2, dw3);
2015 
2016 	return amdgpu_ualink_remote_interrupt(adev, remote_acc_id, dw0, dw1,
2017 					      dw2, dw3);
2018 }
2019 
2020 static u64 amdgpu_ualink_get_export_pte_flags(struct amdgpu_device *adev,
2021 				       struct amdgpu_bo *bo,
2022 				       u64 mapping_flags)
2023 {
2024 	u64 pte_flags = adev->gmc.init_pte_flags;
2025 
2026 	pte_flags |= (AMDGPU_PTE_VALID | AMDGPU_PTE_READABLE |
2027 		      AMDGPU_PTE_WRITEABLE);
2028 	mapping_flags |= AMDGPU_VM_MTYPE_DEFAULT;
2029 
2030 	amdgpu_gmc_get_vm_pte(adev, &adev->ualink.npa_vm, bo, mapping_flags,
2031 			      &pte_flags);
2032 
2033 	return pte_flags;
2034 }
2035 
2036 static int amdgpu_ualink_unmap_npa_addr(struct amdgpu_device *adev,
2037 					struct amdgpu_bo *bo,
2038 					u64 npa_addr, u64 size)
2039 {
2040 	struct amdgpu_vm *vm = &adev->ualink.npa_vm;
2041 	uint64_t pte_value = adev->gmc.noretry_flags;
2042 	struct amdgpu_bo *bos[] = { bo };
2043 	struct dma_fence *fence = NULL;
2044 	struct drm_exec exec;
2045 	int r;
2046 
2047 	r = amdgpu_ualink_reserve_npa_vm_and_bos(adev, bos, ARRAY_SIZE(bos), &exec, false);
2048 	if (unlikely(r)) {
2049 		dev_err(adev->dev, "Failed to reserve VM and BO in unmap_npa_addr\n");
2050 		return r;
2051 	}
2052 
2053 	r = amdgpu_vm_update_range(adev, vm, false, false, true,
2054 				false, NULL, npa_addr, npa_addr + size - 1,
2055 				pte_value, 0, 0, NULL, NULL, &vm->last_update);
2056 	if (r) {
2057 		dev_err(adev->dev,
2058 			"Failed to unmap NPA addr (%llx) from NPA VM\n", npa_addr);
2059 		goto out;
2060 	}
2061 
2062 	r = amdgpu_vm_update_pdes(adev, vm, false);
2063 	if (r) {
2064 		dev_err(adev->dev,
2065 			"Failed %d to update page directories during unmapping NPA: 0x%llx\n",
2066 			r, npa_addr);
2067 		goto out;
2068 	}
2069 
2070 	fence = dma_fence_get(vm->last_update);
2071 	if (fence) {
2072 		r = dma_fence_wait(fence, false);
2073 		dma_fence_put(fence);
2074 		fence = NULL;
2075 		if (r) {
2076 			dev_dbg(adev->dev,
2077 				"UNMAP-NPA: dma fence wait failed, error: %d\n", r);
2078 			goto out;
2079 		}
2080 	}
2081 
2082 	amdgpu_ualink_flush_tlb(adev, TLB_FLUSH_HEAVYWEIGHT);
2083 out:
2084 	amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2085 
2086 	return r;
2087 }
2088 
2089 static int amdgpu_ualink_map_npa_addr(struct amdgpu_device *adev, u64 npa_addr,
2090 				u64 size, struct amdgpu_bo *bo, u64 offset,
2091 				u64 pte_flags)
2092 {
2093 	struct amdgpu_vm *vm = &adev->ualink.npa_vm;
2094 	struct amdgpu_bo *bos[] = { bo };
2095 	struct dma_fence *fence = NULL;
2096 	struct drm_exec exec;
2097 	int r;
2098 
2099 	r = amdgpu_ualink_reserve_npa_vm_and_bos(adev, bos, ARRAY_SIZE(bos), &exec, false);
2100 	if (unlikely(r)) {
2101 		dev_err(adev->dev, "Failed to reserve VM and BO in map_npa_addr\n");
2102 		return r;
2103 	}
2104 
2105 	r = amdgpu_vm_update_range(adev, vm, false, false, true,
2106 				false, NULL, npa_addr, npa_addr + size - 1,
2107 				pte_flags, offset, adev->vm_manager.vram_base_offset,
2108 				bo->tbo.resource, NULL, &vm->last_update);
2109 	if (r) {
2110 		dev_warn(adev->dev,
2111 			"Failed to map NPA addr (%llx) into NPA VM\n", npa_addr);
2112 		amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2113 		goto out;
2114 	}
2115 
2116 	r = amdgpu_vm_update_pdes(adev, vm, false);
2117 	if (r) {
2118 		dev_err(adev->dev,
2119 			"failed %d to update page directories for NPA: 0x%llx\n",
2120 			r, npa_addr);
2121 		amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2122 		goto unmap_npa;
2123 	}
2124 
2125 	fence = dma_fence_get(vm->last_update);
2126 	if (fence) {
2127 		r = dma_fence_wait(fence, false);
2128 		dma_fence_put(fence);
2129 		fence = NULL;
2130 		if (r) {
2131 			pr_debug("failed %d to dma fence wait\n", r);
2132 			amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2133 			goto unmap_npa;
2134 		}
2135 	}
2136 
2137 	amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2138 
2139 	/* TLB flush may be needed after updated page directories */
2140 	amdgpu_ualink_flush_tlb(adev, TLB_FLUSH_HEAVYWEIGHT);
2141 
2142 	return 0;
2143 
2144 unmap_npa:
2145 	amdgpu_ualink_unmap_npa_addr(adev, bo, npa_addr, size);
2146 out:
2147 	return r;
2148 }
2149 
2150 static int amdgpu_ualink_send_hello_ack_msg(struct amdgpu_device *adev,
2151 					    u32 remote_acc_id)
2152 {
2153 	dev_dbg(adev->dev, "SEND HELLO-ACK: HELLO-ACK message to remote AccId:%u\n",
2154 		remote_acc_id);
2155 	return amdgpu_ualink_remote_interrupt(adev, remote_acc_id,
2156 		AMDGPU_UALINK_HELLO_ACK_MSG,
2157 		0, 0, 0);
2158 }
2159 
2160 static int amdgpu_ualink_send_hello_msg(struct amdgpu_device *adev,
2161 					u32 remote_acc_id)
2162 {
2163 	u32 dw0;
2164 
2165 	dw0 = AMDGPU_UALINK_HELLO_MSG;
2166 	dw0 |= (remote_acc_id << AMDGPU_UALINK_HELLO_MSG_RECV_ACCID_SHIFT);
2167 	dw0 |= (adev->ualink.info->ppod.accel_id <<
2168 		AMDGPU_UALINK_HELLO_MSG_SENDER_ACCID_SHIFT);
2169 
2170 	dev_dbg(adev->dev, "SEND HELLO: HELLO message to remote AccId:%u\n",
2171 		remote_acc_id);
2172 	return amdgpu_ualink_remote_interrupt(adev, remote_acc_id, dw0, 0,
2173 					      0, 0);
2174 }
2175 
2176 static u32 amdgpu_ualink_check_conn_ready(struct amdgpu_device *adev,
2177 					  u32 remote_acc_id, u32 gen_count)
2178 {
2179 	struct amdgpu_ualink_connection *conn_state;
2180 	u32 current_gen_count = 0;
2181 
2182 	conn_state = &adev->ualink.conn_state[remote_acc_id];
2183 
2184 	/* Check if the connection is established. */
2185 	mutex_lock(&conn_state->lock);
2186 	if ((conn_state->state == AMDGPU_UALINK_CONN_ESTABLISHED) &&
2187 	    (!gen_count || conn_state->generation_count == gen_count))
2188 		current_gen_count = conn_state->generation_count;
2189 	mutex_unlock(&conn_state->lock);
2190 
2191 	return current_gen_count;
2192 }
2193 
2194 static void amdgpu_ualink_process_hello_ack_msg(struct amdgpu_device *adev,
2195 					       u32 sender_acc_id)
2196 {
2197 	struct amdgpu_ualink_connection *conn_state;
2198 
2199 	if (sender_acc_id >= AMDGPU_UALINK_ACCEL_MAX) {
2200 		dev_err(adev->dev,
2201 			"HELLO-ACK: sender AccId out of range:%u\n",
2202 			sender_acc_id);
2203 		return;
2204 	}
2205 
2206 	conn_state = &adev->ualink.conn_state[sender_acc_id];
2207 
2208 	/* If we are in IN_PROGRESS state, then transition the connection
2209 	 * state to established and signal that the HELLO ACK is received.
2210 	 * Otherwise, ignore the HELLO ACK.
2211 	 */
2212 	mutex_lock(&conn_state->lock);
2213 
2214 	if (conn_state->state == AMDGPU_UALINK_CONN_IN_PROGRESS) {
2215 		conn_state->state = AMDGPU_UALINK_CONN_ESTABLISHED;
2216 		conn_state->generation_count++;
2217 		complete(&conn_state->hello_done);
2218 	} else {
2219 		dev_dbg(adev->dev,
2220 			"HELLO-ACK: already connected, ignoring from AccId:%u\n",
2221 			sender_acc_id);
2222 	}
2223 	mutex_unlock(&conn_state->lock);
2224 }
2225 
2226 static void amdgpu_ualink_process_hello_msg(struct amdgpu_device *adev,
2227 					   u32 receiver_acc_id,
2228 					   u32 sender_acc_id,
2229 					   u32 src_acc_id)
2230 {
2231 	struct amdgpu_ualink_connection *conn_state;
2232 	u32 generation_count;
2233 	int r;
2234 
2235 	if (receiver_acc_id != adev->ualink.info->ppod.accel_id) {
2236 		dev_err(adev->dev,
2237 			"HELLO: receiver AccId mismatch got:%u self:%u\n",
2238 			receiver_acc_id, adev->ualink.info->ppod.accel_id);
2239 		return;
2240 	}
2241 
2242 	/* src_acc_id is the AccId received in IH cookie. Confirm it
2243 	 * matches with the sender AccId.
2244 	 */
2245 	if (sender_acc_id != src_acc_id) {
2246 		dev_err(adev->dev,
2247 			"HELLO: sender AccId mismatch sender:%u IH cookie:%u\n",
2248 			sender_acc_id, src_acc_id);
2249 		return;
2250 	}
2251 
2252 	if (sender_acc_id >= AMDGPU_UALINK_ACCEL_MAX) {
2253 		dev_err(adev->dev,
2254 			"HELLO: sender AccId out of range:%u\n",
2255 			sender_acc_id);
2256 		return;
2257 	}
2258 
2259 	conn_state = &adev->ualink.conn_state[sender_acc_id];
2260 
2261 	/* Check if connection is already established. If yes, then receiving HELLO msg
2262 	 * triggers a reset handling scenario.
2263 	 * If the connection is not ready, and we receive a HELLO msg, then
2264 	 * transition the state to PENDING.
2265 	 * Otherwise, leave it IN_PROGRESS.
2266 	 */
2267 	mutex_lock(&conn_state->lock);
2268 	if (conn_state->state != AMDGPU_UALINK_CONN_ESTABLISHED) {
2269 		if (conn_state->state == AMDGPU_UALINK_CONN_NOT_READY)
2270 			conn_state->state = AMDGPU_UALINK_CONN_PENDING;
2271 		/* otherwise, leave it IN_PROGRESS to signal the completion below */
2272 		mutex_unlock(&conn_state->lock);
2273 	} else {
2274 		/* Leave state ESTABLISHED so handle_connection_reset()
2275 		 * performs the transition and imp/exp XA cleanup.
2276 		 */
2277 		generation_count = conn_state->generation_count;
2278 		mutex_unlock(&conn_state->lock);
2279 
2280 		amdgpu_ualink_handle_connection_reset(adev, sender_acc_id,
2281 						AMDGPU_UALINK_CONN_PENDING,
2282 						generation_count);
2283 	}
2284 
2285 	r = amdgpu_ualink_send_hello_ack_msg(adev, sender_acc_id);
2286 	if (r)
2287 		dev_err(adev->dev, "HELLO-ACK: send failed to remote AccId:%u\n",
2288 			sender_acc_id);
2289 
2290 	mutex_lock(&conn_state->lock);
2291 	if (r) {
2292 		conn_state->state = AMDGPU_UALINK_CONN_NOT_READY;
2293 	} else {
2294 		/* If we are in IN_PROGRESS state and we receivied the HELLO message,
2295 		 * upon receiving the HELLO message, transition the state to ESTABLISHED
2296 		 * and signal the completion.
2297 		 */
2298 		if (conn_state->state == AMDGPU_UALINK_CONN_IN_PROGRESS)
2299 			complete(&conn_state->hello_done);
2300 		conn_state->state = AMDGPU_UALINK_CONN_ESTABLISHED;
2301 		conn_state->generation_count++;
2302 	}
2303 	mutex_unlock(&conn_state->lock);
2304 }
2305 
2306 static int amdgpu_ualink_setup_connection(struct amdgpu_device *adev,
2307 					  u32 remote_acc_id)
2308 {
2309 	struct amdgpu_ualink_connection *conn_state;
2310 	int r;
2311 
2312 	conn_state = &adev->ualink.conn_state[remote_acc_id];
2313 
2314 	/* Connection state management goes through different states.
2315 	 * The states are:
2316 	 * - NOT_READY: The connection is not ready.
2317 	 * - IN_PROGRESS: GPU sent HELLO message and is waiting for the HELLO_ACK.
2318 	 * - PENDING: GPU received HELLO message and is in the process of sending
2319 	 *            the HELLO_ACK.
2320 	 * - ESTABLISHED: The connection is established.
2321 	 */
2322 
2323 	/* Grab the lock and check if connection establishment was
2324 	 * already done by another thread.
2325 	 */
2326 	mutex_lock(&conn_state->lock);
2327 	if (conn_state->state == AMDGPU_UALINK_CONN_ESTABLISHED) {
2328 		r = 0;
2329 		goto out;
2330 	} else if (conn_state->state == AMDGPU_UALINK_CONN_IN_PROGRESS ||
2331 		   conn_state->state == AMDGPU_UALINK_CONN_PENDING) {
2332 		r = -EAGAIN;
2333 		goto out;
2334 	}
2335 
2336 	conn_state->state = AMDGPU_UALINK_CONN_IN_PROGRESS;
2337 	mutex_unlock(&conn_state->lock);
2338 
2339 	/* Send HELLO message */
2340 	r = amdgpu_ualink_send_hello_msg(adev, remote_acc_id);
2341 	if (r) {
2342 		dev_warn(adev->dev,
2343 			"HELLO: Send failed to remote AccId:%u\n",
2344 			remote_acc_id);
2345 		goto reset_state;
2346 	}
2347 
2348 	/* Wait for the HELLO_ACK to come back */
2349 	/* complete(conn_state->hello_done) should be called from the IRQ
2350 	 * handler when the HELLO_ACK is received.
2351 	 */
2352 	r = wait_for_completion_interruptible_timeout(&conn_state->hello_done,
2353 				msecs_to_jiffies(AMDGPU_UALINK_RESP_TIMEOUT));
2354 	if (r == -ERESTARTSYS) {
2355 		dev_err_ratelimited(adev->dev,
2356 			"HELLO-ACK: interrupted by signal\n");
2357 		goto reset_state;
2358 	} else if (r == 0) {
2359 		dev_warn(adev->dev,
2360 			"HELLO-ACK: Timeout from remote AccId:%u\n",
2361 			remote_acc_id);
2362 		r = -ETIMEDOUT;
2363 		goto reset_state;
2364 	}
2365 
2366 	return 0;
2367 
2368 reset_state:
2369 	mutex_lock(&conn_state->lock);
2370 	conn_state->state = AMDGPU_UALINK_CONN_NOT_READY;
2371 out:
2372 	mutex_unlock(&conn_state->lock);
2373 
2374 	return r;
2375 }
2376 
2377 /* Invalidate an importer node's mappings and drop its last ref (frees the
2378  * node, dma-buf and GEM handle). Caller must have unlinked it from the
2379  * per-remote list and must not hold the imp_xa lock.
2380  */
2381 static void amdgpu_ualink_release_imp_xa_node(struct amdgpu_device *adev,
2382 				struct amdgpu_ualink_imp_xa_node *imp_xa_node)
2383 {
2384 	struct amdgpu_bo *bo;
2385 
2386 	dev_dbg(adev->dev,
2387 		"IMP-CLEANUP: handle:%llx:%llx npa:%llx size:%llx\n",
2388 		imp_xa_node->handle.handle_hi, imp_xa_node->handle.handle_lo,
2389 		imp_xa_node->npa_addr, imp_xa_node->size);
2390 
2391 	if (imp_xa_node->dmabuf) {
2392 		bo = gem_to_amdgpu_bo(imp_xa_node->dmabuf->priv);
2393 		amdgpu_ualink_invalidate_import_mappings(bo);
2394 	}
2395 
2396 	amdgpu_ualink_imp_xa_entry_put(imp_xa_node);
2397 }
2398 
2399 static void amdgpu_ualink_cleanup_imp_xa_entries(struct amdgpu_device *adev,
2400 						 u32 remote_acc_id)
2401 {
2402 	struct amdgpu_ualink_imp_xa_node *imp_xa_node;
2403 	struct list_head *imp_handles_list;
2404 
2405 	dev_dbg(adev->dev,
2406 		"IMP-RESET: Cleaning up all XA entries for remote:%u\n",
2407 		remote_acc_id);
2408 
2409 	imp_handles_list = &adev->ualink.imp_handles_list[remote_acc_id];
2410 
2411 	xa_lock(&adev->ualink.imp_xa);
2412 	while (!list_empty(imp_handles_list)) {
2413 		imp_xa_node = list_first_entry(imp_handles_list,
2414 					struct amdgpu_ualink_imp_xa_node, list);
2415 		list_del_init(&imp_xa_node->list);
2416 		WRITE_ONCE(imp_xa_node->node_state, AMDGPU_UALINK_NODE_TEARDOWN);
2417 		xa_unlock(&adev->ualink.imp_xa);
2418 
2419 		amdgpu_ualink_release_imp_xa_node(adev, imp_xa_node);
2420 
2421 		xa_lock(&adev->ualink.imp_xa);
2422 	}
2423 	xa_unlock(&adev->ualink.imp_xa);
2424 }
2425 
2426 static void amdgpu_ualink_cleanup_exp_xa_entries(struct amdgpu_device *adev,
2427 						 u32 remote_acc_id)
2428 {
2429 	struct amdgpu_ualink_importer_entry *importer_entry;
2430 	u32 addr_mode = adev->ualink.info->vpod.addr_mode;
2431 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
2432 	struct list_head *exp_handles_list;
2433 	struct drm_mm_node *mm_node;
2434 	u64 npa_addr, size;
2435 
2436 	/* Get the list head for the list containing all the handles
2437 	 * exported to this remote GPU.
2438 	 */
2439 	exp_handles_list = &adev->ualink.exp_handles_list[remote_acc_id];
2440 
2441 	dev_dbg(adev->dev,
2442 		"EXP-RESET: Cleaning up all XA entries for remote:%u\n",
2443 		remote_acc_id);
2444 
2445 	xa_lock(&adev->ualink.exp_xa);
2446 	while (!list_empty(exp_handles_list)) {
2447 		importer_entry = list_first_entry(exp_handles_list,
2448 					struct amdgpu_ualink_importer_entry, list);
2449 		list_del_init(&importer_entry->list);
2450 
2451 		exp_xa_node = importer_entry->parent;
2452 		if (!amdgpu_ualink_exp_xa_entry_get(exp_xa_node))
2453 			continue;
2454 
2455 		xa_unlock(&adev->ualink.exp_xa);
2456 		/* Clear the bit corresponding to this remote GPU in
2457 		 * the importer bitmap.
2458 		 */
2459 		if (!test_and_clear_bit(remote_acc_id,
2460 					exp_xa_node->importers_bitmap)) {
2461 			amdgpu_ualink_exp_xa_entry_put(exp_xa_node);
2462 			xa_lock(&adev->ualink.exp_xa);
2463 			continue;
2464 		}
2465 
2466 		mutex_lock(&exp_xa_node->node_lock);
2467 		size = amdgpu_bo_ngpu_pages(exp_xa_node->bo);
2468 		/* Unpin the BO */
2469 		if (likely(!amdgpu_bo_reserve(exp_xa_node->bo, true))) {
2470 			amdgpu_bo_unpin(exp_xa_node->bo);
2471 			amdgpu_bo_unreserve(exp_xa_node->bo);
2472 		} else {
2473 			dev_warn(adev->dev,
2474 				"EXP-RESET: BO reserve to unpin failed handle:%llx:%llx\n",
2475 				exp_xa_node->handle.handle_hi, exp_xa_node->handle.handle_lo);
2476 		}
2477 
2478 		dev_dbg(adev->dev,
2479 			"EXP-RESET: handle:%llx:%llx pin_count:%d, importers:%d\n",
2480 			exp_xa_node->handle.handle_hi, exp_xa_node->handle.handle_lo,
2481 			exp_xa_node->bo->tbo.pin_count,
2482 			bitmap_weight(exp_xa_node->importers_bitmap,
2483 			AMDGPU_UALINK_ACCEL_MAX));
2484 
2485 		WARN_ON(exp_xa_node->bo->tbo.pin_count <
2486 			bitmap_weight(exp_xa_node->importers_bitmap,
2487 			AMDGPU_UALINK_ACCEL_MAX));
2488 
2489 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT) {
2490 			npa_addr = importer_entry->npa_addr;
2491 			mm_node = importer_entry->mm_node;
2492 			mutex_unlock(&exp_xa_node->node_lock);
2493 
2494 			dev_dbg(adev->dev,
2495 				"EXP-RESET: Unmap NPA:%llx size: %llx remote:%u handle:%llx:%llx\n",
2496 				npa_addr, size, remote_acc_id,
2497 				exp_xa_node->handle.handle_hi,
2498 				exp_xa_node->handle.handle_lo);
2499 			amdgpu_ualink_unmap_npa_addr(adev, exp_xa_node->bo,
2500 						     npa_addr, size);
2501 			amdgpu_ualink_npa_free_va(adev, mm_node);
2502 			kfree(mm_node);
2503 
2504 			/* Reset the NPA addr and mm_node */
2505 			mutex_lock(&exp_xa_node->node_lock);
2506 			importer_entry->npa_addr = 0;
2507 			importer_entry->mm_node = NULL;
2508 		} else if (bitmap_empty(exp_xa_node->importers_bitmap,
2509 				AMDGPU_UALINK_ACCEL_MAX)) {
2510 			/* In Source-Aliasing mode, if there are no importers
2511 			 * for this handle, then we can unmap and free the
2512 			 * NPA address.
2513 			 */
2514 			mm_node = exp_xa_node->importer_entries[0].mm_node;
2515 			npa_addr = exp_xa_node->importer_entries[0].npa_addr;
2516 			mutex_unlock(&exp_xa_node->node_lock);
2517 
2518 			dev_dbg(adev->dev,
2519 				"EXP-RESET: Unmap NPA:%llx size: %llx handle:%llx:%llx\n",
2520 				npa_addr, size, exp_xa_node->handle.handle_hi,
2521 				exp_xa_node->handle.handle_lo);
2522 			amdgpu_ualink_unmap_npa_addr(adev, exp_xa_node->bo,
2523 						     npa_addr, size);
2524 			amdgpu_ualink_npa_free_va(adev, mm_node);
2525 			kfree(mm_node);
2526 			mutex_lock(&exp_xa_node->node_lock);
2527 			exp_xa_node->importer_entries[0].npa_addr = 0;
2528 			exp_xa_node->importer_entries[0].mm_node = NULL;
2529 		}
2530 
2531 		mutex_unlock(&exp_xa_node->node_lock);
2532 		xa_lock(&adev->ualink.exp_xa);
2533 		amdgpu_ualink_exp_xa_entry_put(exp_xa_node);
2534 	}
2535 	xa_unlock(&adev->ualink.exp_xa);
2536 }
2537 
2538 static void amdgpu_ualink_handle_connection_reset(struct amdgpu_device *adev,
2539 						u32 remote_acc_id, u32 state,
2540 						u32 generation_count)
2541 {
2542 	struct amdgpu_ualink_connection *conn_state;
2543 
2544 	conn_state = &adev->ualink.conn_state[remote_acc_id];
2545 
2546 	mutex_lock(&conn_state->lock);
2547 	if ((conn_state->state == AMDGPU_UALINK_CONN_ESTABLISHED) &&
2548 	     (conn_state->generation_count == generation_count)) {
2549 		conn_state->state = state;
2550 		mutex_unlock(&conn_state->lock);
2551 
2552 		amdgpu_ualink_cleanup_imp_xa_entries(adev, remote_acc_id);
2553 		amdgpu_ualink_cleanup_exp_xa_entries(adev, remote_acc_id);
2554 	} else {
2555 		mutex_unlock(&conn_state->lock);
2556 	}
2557 }
2558 
2559 /* Set PTE.X = 1 for all importer entries to retry RPCs. */
2560 static void amdgpu_ualink_force_retry_rpcs(struct amdgpu_device *adev,
2561 				struct amdgpu_ualink_exp_xa_node *exp_xa_node)
2562 {
2563 	u32 addr_mode = adev->ualink.info->vpod.addr_mode;
2564 	struct amdgpu_ualink_importer_entry *imp_entry;
2565 	struct amdgpu_vm *vm = &adev->ualink.npa_vm;
2566 	u64 pte_flags, npa_addr, size;
2567 	struct dma_fence *fence = NULL;
2568 	struct amdgpu_bo *bo;
2569 	struct drm_exec exec;
2570 	u32 remote_acc_id;
2571 	int r;
2572 
2573 	bo = exp_xa_node->bo;
2574 	size = amdgpu_bo_ngpu_pages(bo);
2575 
2576 	r = amdgpu_ualink_reserve_npa_vm_and_bos(adev, &bo, 1, &exec, false);
2577 	if (unlikely(r)) {
2578 		dev_err(adev->dev, "Failed to reserve VM and BO in force_retry_rpcs\n");
2579 		return;
2580 	}
2581 
2582 	for_each_set_bit(remote_acc_id, exp_xa_node->importers_bitmap,
2583 			 AMDGPU_UALINK_ACCEL_MAX) {
2584 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2585 			imp_entry = &exp_xa_node->importer_entries[0];
2586 		else
2587 			imp_entry = &exp_xa_node->importer_entries[remote_acc_id];
2588 		npa_addr = imp_entry->npa_addr;
2589 
2590 		/* If the connection state changed while we are freeing
2591 		 * the BO, then ignore this importer. We will unmap this
2592 		 * address eventually in amdgpu_ualink_unmap_all_npa_addr()
2593 		 * function. Also, we will clear the corresponding bit in
2594 		 * the importer_bitmap in the same function.
2595 		 */
2596 		if (!amdgpu_ualink_check_conn_ready(adev, remote_acc_id,
2597 					imp_entry->generation_count))
2598 			continue;
2599 
2600 		/* Set PTE.X = 1 */
2601 		pte_flags = amdgpu_ualink_get_export_pte_flags(adev, bo,
2602 					AMDGPU_VM_PAGE_EXECUTABLE);
2603 		dev_dbg(adev->dev,
2604 			"RETRY-RPC: setting PTE.X=1 for NPA:%llx remote:%u pte:0x%llx\n",
2605 			npa_addr, remote_acc_id, pte_flags);
2606 
2607 		r = amdgpu_vm_update_range(adev, vm, false, false, true,
2608 					false, NULL, npa_addr, npa_addr + size - 1,
2609 					pte_flags, 0, adev->vm_manager.vram_base_offset,
2610 					bo->tbo.resource, NULL, &vm->last_update);
2611 
2612 		if (r)
2613 			dev_warn(adev->dev,
2614 				"RETRY-RPC: PTE.X update failed for NPA:%llx remote:%u, r: %d\n",
2615 				npa_addr, remote_acc_id, r);
2616 
2617 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2618 			break;
2619 	}
2620 
2621 	r = amdgpu_vm_update_pdes(adev, vm, false);
2622 	if (r) {
2623 		dev_err(adev->dev,
2624 			"Failed %d to update page directories during force retry rpcs\n",
2625 			r);
2626 		amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2627 		return;
2628 	}
2629 
2630 	fence = dma_fence_get(vm->last_update);
2631 	if (fence) {
2632 		r = dma_fence_wait(fence, false);
2633 		dma_fence_put(fence);
2634 		fence = NULL;
2635 		if (r)
2636 			dev_dbg(adev->dev, "RETRY-RPC: dma fence wait failed err:%d\n", r);
2637 	}
2638 
2639 	amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2640 
2641 	amdgpu_ualink_flush_tlb(adev, TLB_FLUSH_HEAVYWEIGHT);
2642 }
2643 
2644 static void amdgpu_ualink_send_tlb_shootdown(struct amdgpu_device *adev,
2645 				struct amdgpu_ualink_exp_xa_node *exp_xa_node)
2646 {
2647 	u32 addr_mode = adev->ualink.info->vpod.addr_mode;
2648 	u32 accel_id = adev->ualink.info->ppod.accel_id;
2649 	struct amdgpu_ualink_importer_entry *imp_entry;
2650 	u64 npa_addr, size;
2651 	u32 remote_acc_id;
2652 	int r;
2653 
2654 	size = amdgpu_bo_ngpu_pages(exp_xa_node->bo);
2655 
2656 	for_each_set_bit(remote_acc_id, exp_xa_node->importers_bitmap,
2657 			 AMDGPU_UALINK_ACCEL_MAX) {
2658 		/*
2659 		 * Replace the GPU-id bits with local accel_id
2660 		 */
2661 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2662 			imp_entry = &exp_xa_node->importer_entries[0];
2663 		else
2664 			imp_entry = &exp_xa_node->importer_entries[remote_acc_id];
2665 
2666 		npa_addr = STRIP_NPA(imp_entry->npa_addr);
2667 		npa_addr = GENERATE_NPA(npa_addr, accel_id);
2668 
2669 		if (!amdgpu_ualink_check_conn_ready(adev, remote_acc_id,
2670 					imp_entry->generation_count)) {
2671 			clear_bit(remote_acc_id,
2672 				  exp_xa_node->importers_bitmap);
2673 			continue;
2674 		}
2675 
2676 		dev_dbg(adev->dev,
2677 			"EXP-CLEANUP: Sending TLB-shootdown to remote:%u\n",
2678 			remote_acc_id);
2679 		r = amdgpu_ualink_remote_shootdown(adev, remote_acc_id,
2680 					npa_addr, size,
2681 					AMDGPU_UALINK_HEAVYWEIGHT_TLB_SHOOTDOWN);
2682 		if (r) {
2683 			dev_err(adev->dev,
2684 				"EXP-CLEANUP: TLB shootdown send failed to remote:%u\n",
2685 				remote_acc_id);
2686 
2687 			/* Send failed: mark the connection NOT_READY so the
2688 			 * rest of this cleanup (and other cleanups) skip the
2689 			 * unreachable peer via amdgpu_ualink_check_conn_ready().
2690 			 */
2691 			amdgpu_ualink_handle_connection_reset(adev, remote_acc_id,
2692 						AMDGPU_UALINK_CONN_NOT_READY,
2693 						imp_entry->generation_count);
2694 		}
2695 	}
2696 }
2697 
2698 /* Unmap all NPA addresses associated with a BO (UALink handle). This function is used
2699  * only in Source Identification mode.
2700  */
2701 static void amdgpu_ualink_unmap_all_npa_addr(struct amdgpu_device *adev,
2702 				struct amdgpu_ualink_exp_xa_node *exp_xa_node)
2703 {
2704 	struct amdgpu_vm *vm = &adev->ualink.npa_vm;
2705 	u32 addr_mode = adev->ualink.info->vpod.addr_mode;
2706 	struct amdgpu_ualink_importer_entry *imp_entry;
2707 	u64 pte_value = adev->gmc.noretry_flags;
2708 	struct dma_fence *fence = NULL;
2709 	struct drm_exec exec;
2710 	u64 npa_addr, size;
2711 	u32 remote_acc_id;
2712 	int r;
2713 
2714 	size = amdgpu_bo_ngpu_pages(exp_xa_node->bo);
2715 
2716 	r = amdgpu_ualink_reserve_npa_vm_and_bos(adev, &exp_xa_node->bo, 1,
2717 						 &exec, false);
2718 	if (unlikely(r)) {
2719 		dev_err(adev->dev, "Failed to reserve VM and BO in unmap_all_npa_addr\n");
2720 		return;
2721 	}
2722 
2723 	for_each_set_bit(remote_acc_id, exp_xa_node->importers_bitmap,
2724 			 AMDGPU_UALINK_ACCEL_MAX) {
2725 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2726 			imp_entry = &exp_xa_node->importer_entries[0];
2727 		else
2728 			imp_entry = &exp_xa_node->importer_entries[remote_acc_id];
2729 		npa_addr = imp_entry->npa_addr;
2730 
2731 		if (!amdgpu_ualink_check_conn_ready(adev, remote_acc_id,
2732 					imp_entry->generation_count)) {
2733 			clear_bit(remote_acc_id,
2734 				  exp_xa_node->importers_bitmap);
2735 			continue;
2736 		}
2737 
2738 		dev_dbg(adev->dev,
2739 			"UNMAP-NPA: Unmapping NPA:%llx, handle:%llx:%llx remote:%u pte:0x%llx\n",
2740 			npa_addr, exp_xa_node->handle.handle_hi, exp_xa_node->handle.handle_lo,
2741 			remote_acc_id, pte_value);
2742 
2743 		r = amdgpu_vm_update_range(adev, vm, false,
2744 					   false, true, false, NULL, npa_addr,
2745 					   npa_addr + size - 1, pte_value, 0,
2746 					   0, NULL, NULL, &vm->last_update);
2747 
2748 		if (r)
2749 			dev_err(adev->dev,
2750 				"UNMAP-NPA: Unmap failed NPA:%llx, handle:%llx:%llx remote:%u\n",
2751 				npa_addr, exp_xa_node->handle.handle_hi,
2752 				exp_xa_node->handle.handle_lo, remote_acc_id);
2753 
2754 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2755 			break;
2756 	}
2757 
2758 	r = amdgpu_vm_update_pdes(adev, vm, false);
2759 	if (r) {
2760 		dev_err(adev->dev,
2761 			"Failed %d to update page directories during all NPA addresses unmapping\n",
2762 			r);
2763 		amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2764 		return;
2765 	}
2766 
2767 	fence = dma_fence_get(vm->last_update);
2768 	if (fence) {
2769 		r = dma_fence_wait(fence, false);
2770 		dma_fence_put(fence);
2771 		fence = NULL;
2772 		if (r)
2773 			dev_err(adev->dev,
2774 				"UNMAP-NPA: dma fence wait failed\n");
2775 	}
2776 
2777 	amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
2778 
2779 	amdgpu_ualink_flush_tlb(adev, TLB_FLUSH_HEAVYWEIGHT);
2780 }
2781 
2782 static void amdgpu_ualink_free_all_npa_va(struct amdgpu_device *adev,
2783 				struct amdgpu_ualink_exp_xa_node *exp_xa_node,
2784 				unsigned long *importers_bitmap)
2785 {
2786 	u32 addr_mode = adev->ualink.info->vpod.addr_mode;
2787 	struct drm_mm_node *mm_node;
2788 	u32 remote_acc_id;
2789 
2790 	for_each_set_bit(remote_acc_id, importers_bitmap, AMDGPU_UALINK_ACCEL_MAX) {
2791 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2792 			mm_node = exp_xa_node->importer_entries[0].mm_node;
2793 		else
2794 			mm_node = exp_xa_node->importer_entries[remote_acc_id].mm_node;
2795 
2796 		if (!mm_node) {
2797 			if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2798 				break;
2799 			continue;
2800 		}
2801 
2802 		dev_dbg(adev->dev,
2803 			"FREE-NPA: freeing NPA address:%llx, handle:%llx:%llx remote:%u\n",
2804 			mm_node->start, exp_xa_node->handle.handle_hi,
2805 			exp_xa_node->handle.handle_lo, remote_acc_id);
2806 
2807 		amdgpu_ualink_npa_free_va(adev, mm_node);
2808 		kfree(mm_node);
2809 
2810 		if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
2811 			break;
2812 	}
2813 }
2814 
2815 static void amdgpu_ualink_exp_cleanup_worker(struct work_struct *work)
2816 {
2817 	DECLARE_BITMAP(orig_importers_bitmap, AMDGPU_UALINK_ACCEL_MAX);
2818 	struct amdgpu_ualink_importer_entry *imp_entry;
2819 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
2820 	struct amdgpu_ualink_handle handle;
2821 	struct amdgpu_device *adev;
2822 	struct amdgpu_bo *bo;
2823 	u32 remote_acc_id;
2824 	int r;
2825 
2826 	exp_xa_node = container_of(work, struct amdgpu_ualink_exp_xa_node,
2827 				   cleanup_work);
2828 	bo = exp_xa_node->bo;
2829 	adev = amdgpu_ttm_adev(bo->tbo.bdev);
2830 	handle = exp_xa_node->handle;
2831 
2832 	/* Revoking access to an exported memory follows the steps:
2833 	 * 1. Set PTE.X = 1 to retry for RPCs.
2834 	 * 2. Send Remote TLB Shootdowns to all importers.
2835 	 * 3. Unmap the NPA address from NPA VM.
2836 	 * 4. Drop the ref count for the BO.
2837 	 * 5. Send NPA_REVOKE to all importers.
2838 	 * 6. Wait for NPA_RELEASE from all importers.
2839 	 * 7. Free the NPA address once all responses are received.
2840 	 */
2841 	/* If there are no importers for this BO/handle */
2842 	if (bitmap_empty(exp_xa_node->importers_bitmap,
2843 			 AMDGPU_UALINK_ACCEL_MAX)) {
2844 		/* Release the dma_buf created at export time (used for the
2845 		 * local-import shortcut). The has-importers path below drops
2846 		 * it too; this branch must not skip it or the dma_buf and the
2847 		 * BO it pins are leaked.
2848 		 */
2849 		dma_buf_put(exp_xa_node->dmabuf);
2850 		/* Drop the BO reference so it can be freed. */
2851 		amdgpu_bo_unref(&bo);
2852 		exp_xa_node->bo = NULL;
2853 		goto free_node;
2854 	}
2855 
2856 	dev_dbg(adev->dev,
2857 		"EXP-CLEANUP: handle:%llx:%llx importers bitmap: %*pbl\n",
2858 		handle.handle_hi, handle.handle_lo,
2859 		AMDGPU_UALINK_ACCEL_MAX, exp_xa_node->importers_bitmap);
2860 
2861 	bitmap_copy(orig_importers_bitmap, exp_xa_node->importers_bitmap,
2862 		    AMDGPU_UALINK_ACCEL_MAX);
2863 
2864 	/* Set PTE.X = 1 for NPA addresses from all importers*/
2865 	amdgpu_ualink_force_retry_rpcs(adev, exp_xa_node);
2866 
2867 	/* Send TLB-shootdown to all importer GPUs */
2868 	amdgpu_ualink_send_tlb_shootdown(adev, exp_xa_node);
2869 
2870 	/* Unmap all NPA addresses for this BO from NPA VM */
2871 	amdgpu_ualink_unmap_all_npa_addr(adev, exp_xa_node);
2872 
2873 	dev_dbg(adev->dev, "EXP-CLEANUP: handle:%llx:%llx Unpin BO, pin_count:%u, importers:%u\n",
2874 		handle.handle_hi, handle.handle_lo, bo->tbo.pin_count,
2875 		bitmap_weight(orig_importers_bitmap, AMDGPU_UALINK_ACCEL_MAX));
2876 	WARN_ON(bo->tbo.pin_count < bitmap_weight(orig_importers_bitmap,
2877 						AMDGPU_UALINK_ACCEL_MAX));
2878 
2879 	/* Unpin the BO */
2880 	if (likely(!amdgpu_bo_reserve(bo, true))) {
2881 		bo->ualink_handle_lo = 0ULL;
2882 		for_each_set_bit(remote_acc_id, orig_importers_bitmap,
2883 				 AMDGPU_UALINK_ACCEL_MAX)
2884 			amdgpu_bo_unpin(bo);
2885 		amdgpu_bo_unreserve(bo);
2886 	} else {
2887 		dev_warn(adev->dev,
2888 			"EXP-CLEANUP: BO reserve to unpin failed for handle:%llx:%llx\n",
2889 			handle.handle_hi, handle.handle_lo);
2890 	}
2891 
2892 	/* Free the DMABuf */
2893 	dma_buf_put(exp_xa_node->dmabuf);
2894 	/* Drop the reference to the BO so it can be freed. */
2895 	amdgpu_bo_unref(&bo);
2896 	exp_xa_node->bo = NULL;
2897 
2898 	/* Build the full npa_release_bitmap before sending any NPA-REVOKE. */
2899 	for_each_set_bit(remote_acc_id, exp_xa_node->importers_bitmap,
2900 				 AMDGPU_UALINK_ACCEL_MAX) {
2901 		imp_entry = &exp_xa_node->importer_entries[remote_acc_id];
2902 		if (!amdgpu_ualink_check_conn_ready(adev, remote_acc_id,
2903 					imp_entry->generation_count)) {
2904 			clear_bit(remote_acc_id,
2905 				  exp_xa_node->importers_bitmap);
2906 			continue;
2907 		}
2908 
2909 		set_bit(remote_acc_id, exp_xa_node->npa_release_bitmap);
2910 	}
2911 
2912 	/* Send NPA-REVOKE to all importers which have imported this memory.
2913 	 * On send failure clear the bit (no response will arrive) and mark the
2914 	 * connection NOT_READY so other cleanups skip this unreachable peer.
2915 	 */
2916 	for_each_set_bit(remote_acc_id, exp_xa_node->importers_bitmap,
2917 				 AMDGPU_UALINK_ACCEL_MAX) {
2918 		dev_dbg(adev->dev,
2919 			"EXP-CLEANUP: Sending NPA-REVOKE to remote:%u\n",
2920 			remote_acc_id);
2921 		r = amdgpu_ualink_send_npa_revoke_msg(adev, remote_acc_id, handle);
2922 		if (r) {
2923 			dev_err(adev->dev,
2924 				"EXP-CLEANUP: NPA-REVOKE send failed to remote:%u\n",
2925 				remote_acc_id);
2926 			clear_bit(remote_acc_id, exp_xa_node->npa_release_bitmap);
2927 
2928 			imp_entry = &exp_xa_node->importer_entries[remote_acc_id];
2929 			amdgpu_ualink_handle_connection_reset(adev, remote_acc_id,
2930 						AMDGPU_UALINK_CONN_NOT_READY,
2931 						imp_entry->generation_count);
2932 		}
2933 	}
2934 
2935 	/* Wait for the NPA_RELEASE to come back from all importers */
2936 	if (!bitmap_empty(exp_xa_node->npa_release_bitmap,
2937 			AMDGPU_UALINK_ACCEL_MAX)) {
2938 		dev_dbg(adev->dev,
2939 			"EXP-CLEANUP: handle:%llx:%llx NPA-RELEASE bitmap: %*pbl\n",
2940 			handle.handle_hi, handle.handle_lo,
2941 			AMDGPU_UALINK_ACCEL_MAX, exp_xa_node->npa_release_bitmap);
2942 
2943 		/* Wait for the NPA_RELEASE to come back from all importers */
2944 		r = wait_for_completion_timeout(&exp_xa_node->npa_done,
2945 					msecs_to_jiffies(AMDGPU_UALINK_RESP_TIMEOUT));
2946 
2947 		if (r == 0)
2948 			dev_warn(adev->dev,
2949 				"EXP-CLEANUP: NPA-RELEASE timeout for handle:%llx:%llx\n",
2950 				handle.handle_hi, handle.handle_lo);
2951 	}
2952 
2953 	/* Free the NPA addresses given to all the importers */
2954 	amdgpu_ualink_free_all_npa_va(adev, exp_xa_node,
2955 				      orig_importers_bitmap);
2956 
2957 	/* Warn about all importers that didn't respond back with
2958 	 * NPA-RELEASE message and trigger connection timeout handling.
2959 	 */
2960 	for_each_set_bit(remote_acc_id, exp_xa_node->npa_release_bitmap,
2961 			 AMDGPU_UALINK_ACCEL_MAX) {
2962 		dev_warn(adev->dev,
2963 			"EXP-CLEANUP: handle:%llx:%llx NPA-RELEASE timeout from remote:%u\n",
2964 			handle.handle_hi, handle.handle_lo, remote_acc_id);
2965 		imp_entry = &exp_xa_node->importer_entries[remote_acc_id];
2966 		amdgpu_ualink_handle_connection_reset(adev, remote_acc_id,
2967 						AMDGPU_UALINK_CONN_NOT_READY,
2968 						imp_entry->generation_count);
2969 	}
2970 
2971 free_node:
2972 	xa_erase(&adev->ualink.handle_invalid_xa, handle.handle_lo);
2973 	mutex_destroy(&exp_xa_node->node_lock);
2974 	kfree(exp_xa_node);
2975 }
2976 
2977 /* This function is a copy of amdgpu_dma_buf_move_notify() function.
2978  * amdgpu_dma_buf_move_notify is only called for import attachments.
2979  * But NPA DMABufs don't use attachments because they are imported
2980  * on the same device. So we need to invalidate the GPUVM mappings
2981  * manually.
2982  */
2983 static void amdgpu_ualink_invalidate_import_mappings(struct amdgpu_bo *bo)
2984 {
2985 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
2986 	struct ttm_operation_ctx ctx = { false, false };
2987 	struct ttm_placement placement = {};
2988 	struct amdgpu_vm_bo_base *bo_base;
2989 	struct drm_exec exec;
2990 	int r;
2991 
2992 	/*
2993 	 * Lock the BO together with every client VM page directory it is
2994 	 * mapped into in a single drm_exec transaction.
2995 	 */
2996 	drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);
2997 	drm_exec_until_all_locked(&exec) {
2998 		r = drm_exec_lock_obj(&exec, &bo->tbo.base);
2999 		drm_exec_retry_on_contention(&exec);
3000 		if (unlikely(r))
3001 			goto fini;
3002 
3003 		for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
3004 			r = amdgpu_vm_lock_pd(bo_base->vm, &exec, 0);
3005 			drm_exec_retry_on_contention(&exec);
3006 			if (unlikely(r))
3007 				goto fini;
3008 		}
3009 	}
3010 
3011 	/* FIXME: This should be after the "if", but needs a fix to make sure
3012 	 * DMABuf imports are initialized in the right VM list.
3013 	 */
3014 	amdgpu_vm_bo_invalidate(bo, false);
3015 	if (!bo->tbo.resource || bo->tbo.resource->mem_type == TTM_PL_SYSTEM)
3016 		goto fini;
3017 
3018 	r = ttm_bo_validate(&bo->tbo, &placement, &ctx);
3019 	if (r) {
3020 		dev_err(adev->dev, "Failed to invalidate NPA DMA-buf import (%d)\n",
3021 			r);
3022 		goto fini;
3023 	}
3024 
3025 	for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
3026 		struct amdgpu_vm *vm = bo_base->vm;
3027 
3028 		/*
3029 		 * Fences for the two SDMA page table updates were already
3030 		 * reserved by amdgpu_vm_lock_pd() above (it reserves 2 +
3031 		 * num_fences on the same VM root PD dma_resv).
3032 		 */
3033 		r = amdgpu_vm_clear_freed(adev, vm, NULL);
3034 		if (!r)
3035 			r = amdgpu_vm_handle_moved(adev, vm, &exec.ticket);
3036 
3037 		if (r && r != -EBUSY)
3038 			dev_err(adev->dev, "Failed to invalidate VM page tables (%d))\n",
3039 				r);
3040 	}
3041 
3042 fini:
3043 	drm_exec_fini(&exec);
3044 }
3045 
3046 static int amdgpu_ualink_map_npa_to_dmabuf(struct amdgpu_device *adev,
3047 				struct amdgpu_ualink_imp_xa_node *imp_xa_node)
3048 {
3049 	struct ttm_operation_ctx ctx = { false, false };
3050 	u32 initial_domain = AMDGPU_GEM_DOMAIN_NPA;
3051 	struct drm_gem_object *gobj = NULL;
3052 	u64 alloc_flags, npa_addr, size;
3053 	struct dma_buf *dmabuf;
3054 	struct amdgpu_bo *bo;
3055 	u32 handle;
3056 	int r;
3057 
3058 	npa_addr = imp_xa_node->npa_addr;
3059 	size = imp_xa_node->size;
3060 
3061 	dev_dbg(adev->dev, "Create NPA BO addr 0x%llx size in pages 0x%llx\n",
3062 		npa_addr, size);
3063 
3064 	/*
3065 	 * Create the BO directly in the NPA domain.
3066 	 */
3067 	alloc_flags = AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
3068 	r = amdgpu_gem_object_create(adev, size * AMDGPU_GPU_PAGE_SIZE, 1,
3069 				     initial_domain, alloc_flags,
3070 				     ttm_bo_type_device, NULL, &gobj, 0);
3071 	if (r) {
3072 		dev_err(adev->dev, "Failed to create NPA BO. ret %d\n", r);
3073 		return r;
3074 	}
3075 
3076 	bo = gem_to_amdgpu_bo(gobj);
3077 
3078 	r = amdgpu_bo_reserve(bo, false);
3079 	if (unlikely(r != 0)) {
3080 		dev_err(adev->dev, "Failed to reserve NPA BO, r: %d\n", r);
3081 		goto err_reserve_failed;
3082 	}
3083 
3084 	/*
3085 	 * Drop the arbitrarily-placed NPA node and re-create it at the exact
3086 	 * remote window, mirroring amdgpu_bo_create_kernel_at().
3087 	 */
3088 	ttm_resource_free(&bo->tbo, &bo->tbo.resource);
3089 
3090 	bo->placements[0].fpfn = npa_addr;
3091 	bo->placements[0].lpfn = npa_addr + size;
3092 
3093 	r = ttm_bo_mem_space(&bo->tbo, &bo->placement, &bo->tbo.resource, &ctx);
3094 	amdgpu_bo_unreserve(bo);
3095 	if (r) {
3096 		dev_err(adev->dev,
3097 			"Failed to place NPA BO at 0x%llx, r: %d\n", npa_addr, r);
3098 		goto err_validate_failed;
3099 	}
3100 
3101 	r = drm_gem_handle_create(adev->ualink.client.file, gobj, &handle);
3102 	if (r) {
3103 		dev_err(adev->dev,
3104 			"Failed to get handle for NPA GEM object, r: %d\n", r);
3105 		goto err_validate_failed;
3106 	}
3107 	drm_gem_object_put(gobj);
3108 
3109 	dmabuf = drm_gem_prime_handle_to_dmabuf(&adev->ddev, adev->ualink.client.file,
3110 						handle, DRM_CLOEXEC | DRM_RDWR);
3111 	if (IS_ERR(dmabuf)) {
3112 		r = PTR_ERR(dmabuf);
3113 		dev_err(adev->dev,
3114 			"Failed to generate DMABuf for NPA GEM object\n");
3115 		goto err_dmabuf_failed;
3116 	}
3117 
3118 	imp_xa_node->dmabuf = dmabuf;
3119 	imp_xa_node->gem_handle = handle;
3120 
3121 	return 0;
3122 
3123 err_dmabuf_failed:
3124 	drm_gem_handle_delete(adev->ualink.client.file, handle);
3125 	return r;
3126 err_validate_failed:
3127 err_reserve_failed:
3128 	drm_gem_object_put(gobj);
3129 
3130 	return r;
3131 }
3132 
3133 void amdgpu_ualink_revoke_exported_memory(struct amdgpu_bo *bo)
3134 {
3135 	struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
3136 	struct amdgpu_ualink_importer_entry *imp_entry;
3137 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
3138 	u32 remote_acc_id;
3139 	int r;
3140 
3141 	if (!bo->ualink_handle_lo)
3142 		return;
3143 
3144 	/* Remove the entry from the Xarray. */
3145 	xa_lock(&adev->ualink.exp_xa);
3146 	exp_xa_node = __xa_erase(&adev->ualink.exp_xa,
3147 				 bo->ualink_handle_lo);
3148 	if (!exp_xa_node) {
3149 		xa_unlock(&adev->ualink.exp_xa);
3150 		dev_warn(adev->dev,
3151 			 "Exp XA: handle_lo:%llx not found\n",
3152 			 bo->ualink_handle_lo);
3153 		return;
3154 	}
3155 
3156 	for_each_set_bit(remote_acc_id, exp_xa_node->importers_bitmap,
3157 			 AMDGPU_UALINK_ACCEL_MAX) {
3158 		imp_entry = &exp_xa_node->importer_entries[remote_acc_id];
3159 		list_del_init(&imp_entry->list);
3160 	}
3161 	xa_unlock(&adev->ualink.exp_xa);
3162 
3163 	/* Add it to the Handle_Invalid xarray */
3164 	r = xa_err(xa_store(&adev->ualink.handle_invalid_xa,
3165 			    bo->ualink_handle_lo,
3166 			    exp_xa_node, GFP_KERNEL));
3167 	if (r)
3168 		dev_err(adev->dev,
3169 			"Handle_Invalid XA store failed handle:%llx:%llx error:%d\n",
3170 			exp_xa_node->handle.handle_hi,
3171 			exp_xa_node->handle.handle_lo, r);
3172 
3173 	amdgpu_ualink_exp_xa_entry_put(exp_xa_node);
3174 }
3175 
3176 static void amdgpu_ualink_process_npa_release_msg(struct amdgpu_device *adev,
3177 						 u32 remote_acc_id,
3178 						 struct amdgpu_ualink_handle handle)
3179 {
3180 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
3181 
3182 	xa_lock(&adev->ualink.handle_invalid_xa);
3183 	exp_xa_node = xa_load(&adev->ualink.handle_invalid_xa, handle.handle_lo);
3184 	if (!exp_xa_node) {
3185 		dev_warn(adev->dev,
3186 			 "NPA-RELEASE: Handle (%llx:%llx) not found\n",
3187 			 handle.handle_hi, handle.handle_lo);
3188 		goto out;
3189 	}
3190 
3191 	/* Confirm that the complete handle matches. */
3192 	if (handle.handle_hi != exp_xa_node->handle.handle_hi) {
3193 		dev_warn(adev->dev,
3194 			 "NPA-RELEASE: handle_hi mismatch exp:%llx got:%llx:%llx remote:%u\n",
3195 			 exp_xa_node->handle.handle_hi,
3196 			 handle.handle_hi, handle.handle_lo, remote_acc_id);
3197 		goto out;
3198 	}
3199 
3200 	/* Test and clear the bit corresponding to the remote GPU id to signal
3201 	 * the arrival of NPA_RELEASE message from it.
3202 	 * If the corresponding bit wasn't set, then raise a warning and ignore
3203 	 * the NPA-Release message from the remote GPU.
3204 	 */
3205 	if (!test_and_clear_bit(remote_acc_id, exp_xa_node->npa_release_bitmap)) {
3206 		dev_warn(adev->dev,
3207 			 "NPA-RELEASE: unexpected from remote:%u handle:%llx:%llx\n",
3208 			 remote_acc_id, handle.handle_hi, handle.handle_lo);
3209 		goto out;
3210 	}
3211 
3212 	/* Signal completion if NPA_Release received from all importers */
3213 	if (bitmap_empty(exp_xa_node->npa_release_bitmap,
3214 			 AMDGPU_UALINK_ACCEL_MAX))
3215 		complete(&exp_xa_node->npa_done);
3216 
3217 out:
3218 	xa_unlock(&adev->ualink.handle_invalid_xa);
3219 }
3220 
3221 static void amdgpu_ualink_process_npa_revoke_msg(struct amdgpu_device *adev,
3222 						u32 remote_acc_id,
3223 						struct amdgpu_ualink_handle handle)
3224 {
3225 	struct amdgpu_ualink_imp_xa_node *imp_xa_node;
3226 	struct amdgpu_bo *bo;
3227 	int r = 0;
3228 
3229 	/* Remove the entry from the Xarray. */
3230 	xa_lock(&adev->ualink.imp_xa);
3231 	imp_xa_node = xa_load(&adev->ualink.imp_xa, handle.handle_lo);
3232 	if (!imp_xa_node) {
3233 		xa_unlock(&adev->ualink.imp_xa);
3234 		dev_warn(adev->dev,
3235 			 "NPA-REVOKE: Handle (%llx:%llx) not found\n",
3236 			 handle.handle_hi, handle.handle_lo);
3237 		return;
3238 	}
3239 
3240 	/* Confirm that the complete handle matches. */
3241 	if (handle.handle_hi != imp_xa_node->handle.handle_hi) {
3242 		xa_unlock(&adev->ualink.imp_xa);
3243 		dev_warn(adev->dev,
3244 			 "NPA-REVOKE: handle_hi mismatch exp:%llx got:%llx:%llx remote:%u\n",
3245 			 imp_xa_node->handle.handle_hi,
3246 			 handle.handle_hi, handle.handle_lo, remote_acc_id);
3247 		return;
3248 	}
3249 
3250 	WRITE_ONCE(imp_xa_node->node_state, AMDGPU_UALINK_NODE_TEARDOWN);
3251 	list_del_init(&imp_xa_node->list);
3252 	xa_unlock(&adev->ualink.imp_xa);
3253 
3254 	/* Invalidate the GPUVM mappings */
3255 	bo = gem_to_amdgpu_bo(imp_xa_node->dmabuf->priv);
3256 	amdgpu_ualink_invalidate_import_mappings(bo);
3257 
3258 	/* Drop the refcount for the node */
3259 	amdgpu_ualink_imp_xa_entry_put(imp_xa_node);
3260 
3261 	r = amdgpu_ualink_send_npa_release_msg(adev, remote_acc_id, handle);
3262 	if (r)
3263 		dev_err(adev->dev,
3264 			"NPA-Release send failed remote:%u handle:%llx:%llx error:%d\n",
3265 			remote_acc_id, handle.handle_hi, handle.handle_lo, r);
3266 }
3267 
3268 static void amdgpu_ualink_process_npa_fail_msg(struct amdgpu_device *adev,
3269 				       u32 remote_acc_id, u64 partial_handle,
3270 				       u32 fail_reason)
3271 {
3272 	struct amdgpu_ualink_imp_xa_node *imp_xa_node;
3273 	int r = 0;
3274 
3275 	if (!amdgpu_ualink_check_conn_ready(adev, remote_acc_id, 0)) {
3276 		dev_warn(adev->dev,
3277 			"NPA-FAIL: no connection with remote AccId:%u\n",
3278 			remote_acc_id);
3279 		goto conn_setup;
3280 	}
3281 
3282 	xa_lock(&adev->ualink.imp_xa);
3283 	imp_xa_node = xa_load(&adev->ualink.imp_xa, partial_handle);
3284 	if (!imp_xa_node) {
3285 		xa_unlock(&adev->ualink.imp_xa);
3286 		dev_warn(adev->dev,
3287 			"NPA-FAIL: imp XA handle not found:%llx\n",
3288 			partial_handle);
3289 		return;
3290 	}
3291 
3292 	imp_xa_node->fail_reason = fail_reason;
3293 	/* Signal completion done to signal response received for NPA-REQ
3294 	 * message.
3295 	 * If the node is in NOT_READY state, then set the node state to
3296 	 * PENDING and signal the completion. If the node is not in NOT_READY
3297 	 * state, then it is an unsolicited NPA-FAIL message and we
3298 	 * log a debug message.
3299 	 */
3300 	if (READ_ONCE(imp_xa_node->node_state) == AMDGPU_UALINK_NODE_NOT_READY) {
3301 		WRITE_ONCE(imp_xa_node->node_state, AMDGPU_UALINK_NODE_PENDING);
3302 		complete(&imp_xa_node->npa_done);
3303 	} else {
3304 		dev_dbg(adev->dev,
3305 			"NPA-FAIL: unsolicited for handle:%llx:%llx from AccId:%u\n",
3306 			imp_xa_node->handle.handle_hi, imp_xa_node->handle.handle_lo,
3307 			remote_acc_id);
3308 	}
3309 	xa_unlock(&adev->ualink.imp_xa);
3310 
3311 	return;
3312 
3313 conn_setup:
3314 	r = amdgpu_ualink_setup_connection(adev, remote_acc_id);
3315 	if (r)
3316 		dev_warn(adev->dev,
3317 			"NPA-FAIL: connection setup failed with remote AccId:%u\n",
3318 			remote_acc_id);
3319 }
3320 
3321 static void amdgpu_ualink_process_npa_rsp_msg(struct amdgpu_device *adev,
3322 				      u32 remote_acc_id, u64 partial_handle,
3323 				      u64 npa_addr, u64 size)
3324 {
3325 	struct amdgpu_ualink_imp_xa_node *imp_xa_node;
3326 	int r = 0;
3327 
3328 	/* Check if the connection is established. If it is not, then start
3329 	 * connection setup.
3330 	 */
3331 	if (!amdgpu_ualink_check_conn_ready(adev, remote_acc_id, 0)) {
3332 		dev_warn(adev->dev,
3333 			"NPA-RSP: no connection with remote AccId:%u\n",
3334 			remote_acc_id);
3335 		goto conn_setup;
3336 	}
3337 
3338 	xa_lock(&adev->ualink.imp_xa);
3339 	imp_xa_node = xa_load(&adev->ualink.imp_xa, partial_handle);
3340 	if (!imp_xa_node) {
3341 		xa_unlock(&adev->ualink.imp_xa);
3342 		dev_warn(adev->dev,
3343 			"NPA-RSP: imp XA handle not found:%llx\n", partial_handle);
3344 		return;
3345 	}
3346 
3347 	/* NPA addr received in NPA-RSP is page aligned and without the remote
3348 	 * GPU-id in Bits 41-50. Assemble back the NPA address before storing
3349 	 * it.
3350 	 */
3351 	imp_xa_node->npa_addr = GENERATE_NPA(npa_addr, remote_acc_id);
3352 	/* Size is in number of GPU pages granularity. */
3353 	imp_xa_node->size = size;
3354 
3355 	/* Signal completion done to signal NPA_RSP received.
3356 	 * If the node is in NOT_READY state, then set the node state to
3357 	 * PENDING and signal the completion. If the node is not in NOT_READY
3358 	 * state, then it is an unsolicited NPA-RSP message and we
3359 	 * log a debug message.
3360 	 */
3361 	if (READ_ONCE(imp_xa_node->node_state) == AMDGPU_UALINK_NODE_NOT_READY) {
3362 		WRITE_ONCE(imp_xa_node->node_state, AMDGPU_UALINK_NODE_PENDING);
3363 		complete(&imp_xa_node->npa_done);
3364 	} else {
3365 		dev_dbg(adev->dev,
3366 			"NPA-RSP: unsolicited for handle:%llx:%llx from AccId:%u\n",
3367 			imp_xa_node->handle.handle_hi, imp_xa_node->handle.handle_lo,
3368 			remote_acc_id);
3369 	}
3370 	xa_unlock(&adev->ualink.imp_xa);
3371 
3372 	return;
3373 
3374 conn_setup:
3375 	r = amdgpu_ualink_setup_connection(adev, remote_acc_id);
3376 	if (r)
3377 		dev_warn(adev->dev,
3378 			"NPA-RSP: connection setup failed with remote AccId:%u\n",
3379 			remote_acc_id);
3380 }
3381 
3382 static void amdgpu_ualink_process_npa_req_msg(struct amdgpu_device *adev,
3383 				      u32 remote_acc_id,
3384 				      struct amdgpu_ualink_handle handle)
3385 {
3386 	struct amdgpu_ualink_importer_entry *importer_entry, *npa_addr_entry;
3387 	u32 addr_mode = adev->ualink.info->vpod.addr_mode;
3388 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
3389 	u64 range_start, range_end, pte_flags;
3390 	struct drm_mm_node *mm_node = NULL;
3391 	int r = 0, fail_reason = 0;
3392 	bool send_npa_fail = true;
3393 	u64 npa_addr = 0, size;
3394 	struct amdgpu_bo *bo;
3395 	u32 gen_count;
3396 
3397 	/* Check if the connection is established. If it is not, then start
3398 	 * connection setup.
3399 	 */
3400 	gen_count = amdgpu_ualink_check_conn_ready(adev, remote_acc_id, 0);
3401 	if (!gen_count) {
3402 		dev_warn(adev->dev,
3403 			"NPA-REQ: no connection with remote AccId:%u\n",
3404 			remote_acc_id);
3405 		goto conn_setup;
3406 	}
3407 
3408 	/* Check entry exists in Exporter XA. If yes, increase the refcount
3409 	 * for the node.
3410 	 */
3411 	xa_lock(&adev->ualink.exp_xa);
3412 	exp_xa_node = xa_load(&adev->ualink.exp_xa, handle.handle_lo);
3413 	if (!exp_xa_node  || (handle.handle_hi != exp_xa_node->handle.handle_hi) ||
3414 	    !amdgpu_ualink_exp_xa_entry_get(exp_xa_node)) {
3415 		xa_unlock(&adev->ualink.exp_xa);
3416 		dev_warn(adev->dev,
3417 			"NPA-REQ: exp XA handle not found handle:%llx:%llx\n",
3418 			handle.handle_hi, handle.handle_lo);
3419 		fail_reason = AMDGPU_UALINK_NPA_FAIL_INVALID_HANDLE;
3420 		goto handle_invalid_fail;
3421 	}
3422 	xa_unlock(&adev->ualink.exp_xa);
3423 
3424 	bo = exp_xa_node->bo;
3425 	size = amdgpu_bo_ngpu_pages(bo);
3426 
3427 	/* Pin the BO */
3428 	r = amdgpu_bo_reserve(bo, true);
3429 	if (unlikely(r)) {
3430 		dev_warn(adev->dev,
3431 			"NPA-REQ: BO reserve failed handle:%llx:%llx\n",
3432 			handle.handle_hi, handle.handle_lo);
3433 		fail_reason = AMDGPU_UALINK_NPA_FAIL_ERROR;
3434 		goto bo_reserve_fail;
3435 	}
3436 	r = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_VRAM);
3437 	amdgpu_bo_unreserve(bo);
3438 	if (r) {
3439 		dev_warn(adev->dev,
3440 			"NPA-REQ: BO pin failed handle:%llx:%llx\n",
3441 			handle.handle_hi, handle.handle_lo);
3442 		fail_reason = AMDGPU_UALINK_NPA_FAIL_ERROR;
3443 		goto bo_pin_fail;
3444 	}
3445 
3446 	if (addr_mode == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT) {
3447 		mutex_lock(&exp_xa_node->node_lock);
3448 		importer_entry = &exp_xa_node->importer_entries[remote_acc_id];
3449 		npa_addr_entry = importer_entry;
3450 		mutex_unlock(&exp_xa_node->node_lock);
3451 		/* Check if NPA address is already allocated for this importer.
3452 		 * If yes, then send the NPA-FAIL message back to the remote GPU.
3453 		 */
3454 		if (importer_entry->npa_addr) {
3455 			fail_reason = AMDGPU_UALINK_NPA_FAIL_DUPLICATE;
3456 			goto npa_duplicate_fail;
3457 		}
3458 
3459 		range_start = ((u64)remote_acc_id << AMDGPU_UALINK_NPA_ADDR_GPUID_SHIFT) |
3460 				AMDGPU_UALINK_NPA_ADDR_RANGE_RESERVED;
3461 		range_end = range_start | AMDGPU_UALINK_NPA_ADDR_RANGE_MASK;
3462 	} else {
3463 		/* We store NPA-address in importer_entries[0] in
3464 		 * Source-Aliasing mode.
3465 		 */
3466 		mutex_lock(&exp_xa_node->node_lock);
3467 		npa_addr_entry = &exp_xa_node->importer_entries[0];
3468 		importer_entry = &exp_xa_node->importer_entries[remote_acc_id];
3469 		/* Check if NPA address is already allocated for this importer.
3470 		 * If yes, then set the corresponding bit in the importers_bitmap,
3471 		 * set the generation count and send the NPA-RSP back to the remote GPU.
3472 		 */
3473 		if (npa_addr_entry->npa_addr) {
3474 			npa_addr = npa_addr_entry->npa_addr;
3475 			set_bit(remote_acc_id, exp_xa_node->importers_bitmap);
3476 			importer_entry->generation_count = gen_count;
3477 			mutex_unlock(&exp_xa_node->node_lock);
3478 			dev_dbg(adev->dev,
3479 				"NPA-REQ: NPA:%llx size:%llx handle:%llx:%llx\n",
3480 				npa_addr, size, handle.handle_hi, handle.handle_lo);
3481 
3482 			goto send_npa_rsp;
3483 		}
3484 		mutex_unlock(&exp_xa_node->node_lock);
3485 
3486 		range_start = 0;
3487 		range_end = 0;
3488 	}
3489 
3490 	mm_node = kzalloc(sizeof(*mm_node), GFP_KERNEL);
3491 	if (!mm_node) {
3492 		dev_warn(adev->dev,
3493 			"NPA-REQ: mm_node alloc failed handle:%llx:%llx\n",
3494 			handle.handle_hi, handle.handle_lo);
3495 		fail_reason = AMDGPU_UALINK_NPA_FAIL_NOSPACE;
3496 		goto mem_alloc_fail;
3497 	}
3498 
3499 	/* Allocate NPA address */
3500 	r = amdgpu_ualink_npa_alloc_va(adev, mm_node, 0, range_start,
3501 					range_end, size);
3502 	if (r) {
3503 		dev_warn(adev->dev,
3504 			"NPA-REQ: NPA addr alloc failed handle:%llx:%llx\n",
3505 			handle.handle_hi, handle.handle_lo);
3506 		fail_reason = AMDGPU_UALINK_NPA_FAIL_NOSPACE;
3507 		goto npa_alloc_fail;
3508 	}
3509 	npa_addr = mm_node->start;
3510 
3511 	pte_flags = amdgpu_ualink_get_export_pte_flags(adev, bo, 0);
3512 	dev_dbg(adev->dev,
3513 		"NPA-REQ: Allocated NPA:%llx size:%llx PTE:%llx handle:%llx:%llx\n",
3514 		npa_addr, size, pte_flags, handle.handle_hi, handle.handle_lo);
3515 
3516 	/* Map the NPA address into NPA VM*/
3517 	r = amdgpu_ualink_map_npa_addr(adev, npa_addr, size, bo, 0, pte_flags);
3518 	if (r) {
3519 		fail_reason = AMDGPU_UALINK_NPA_FAIL_ERROR;
3520 		dev_warn(adev->dev,
3521 			"NPA-REQ: NPA addr (%llx) map failed handle:%llx:%llx\n",
3522 			npa_addr, handle.handle_hi, handle.handle_lo);
3523 		goto map_npa_fail;
3524 	}
3525 
3526 	dev_dbg(adev->dev,
3527 		"NPA-REQ: Mapped NPA:%llx size:%llx pte:%llx handle:%llx:%llx\n",
3528 		npa_addr, size, pte_flags, handle.handle_hi, handle.handle_lo);
3529 send_npa_rsp:
3530 	/* Send NPA-RSP back to the remote GPU */
3531 	r = amdgpu_ualink_send_npa_rsp_msg(adev, remote_acc_id, handle,
3532 					   STRIP_NPA(npa_addr), size);
3533 	if (r) {
3534 		dev_warn(adev->dev,
3535 			"NPA-REQ: send NPA-RSP failed remote:%u handle:%llx:%llx\n",
3536 			remote_acc_id, handle.handle_hi, handle.handle_lo);
3537 		send_npa_fail = false;
3538 		goto send_npa_rsp_fail;
3539 	}
3540 
3541 	dev_dbg(adev->dev,
3542 		"NPA-REQ: Sent NPA-RSP with NPA:%llx size:%llx handle:%llx:%llx\n",
3543 		npa_addr, size, handle.handle_hi, handle.handle_lo);
3544 
3545 	/* If this is the first time we are setting the bit for this importer,
3546 	 * then store the NPA address, mm_node and generation count.
3547 	 */
3548 	mutex_lock(&exp_xa_node->node_lock);
3549 	if (!test_and_set_bit(remote_acc_id, exp_xa_node->importers_bitmap)) {
3550 		npa_addr_entry->npa_addr = npa_addr;
3551 		npa_addr_entry->mm_node = mm_node;
3552 		importer_entry->generation_count = gen_count;
3553 	}
3554 	mutex_unlock(&exp_xa_node->node_lock);
3555 
3556 	dev_dbg(adev->dev,
3557 		"NPA-REQ: BO pin_count:%d, importers:%d, handle:%llx:%llx\n",
3558 		bo->tbo.pin_count, bitmap_weight(exp_xa_node->importers_bitmap,
3559 		AMDGPU_UALINK_ACCEL_MAX), handle.handle_hi, handle.handle_lo);
3560 	WARN_ON(bo->tbo.pin_count < bitmap_weight(exp_xa_node->importers_bitmap,
3561 						   AMDGPU_UALINK_ACCEL_MAX));
3562 
3563 	/* Add this node to the exported handles list for the remote GPU,
3564 	 * but only if the node is still in exp_xa. If revoke already erased
3565 	 * it, skip the list_add to avoid a dangling list entry. The cleanup
3566 	 * worker is guaranteed to run after we drop our ref, so it will see
3567 	 * this importer in the bitmap and send NPA-REVOKE.
3568 	 */
3569 	xa_lock(&adev->ualink.exp_xa);
3570 	if (xa_load(&adev->ualink.exp_xa, exp_xa_node->handle.handle_lo) == exp_xa_node)
3571 		list_add(&importer_entry->list, &adev->ualink.exp_handles_list[remote_acc_id]);
3572 	xa_unlock(&adev->ualink.exp_xa);
3573 
3574 	amdgpu_ualink_exp_xa_entry_put(exp_xa_node);
3575 
3576 	return;
3577 
3578 send_npa_rsp_fail:
3579 	mutex_lock(&exp_xa_node->node_lock);
3580 	clear_bit(remote_acc_id, exp_xa_node->importers_bitmap);
3581 	mutex_unlock(&exp_xa_node->node_lock);
3582 	if (mm_node)
3583 		amdgpu_ualink_unmap_npa_addr(adev, bo, npa_addr, size);
3584 
3585 map_npa_fail:
3586 	if (mm_node)
3587 		amdgpu_ualink_npa_free_va(adev, mm_node);
3588 
3589 npa_alloc_fail:
3590 	kfree(mm_node);
3591 mem_alloc_fail:
3592 npa_duplicate_fail:
3593 	r = amdgpu_bo_reserve(bo, true);
3594 	if (likely(!r)) {
3595 		amdgpu_bo_unpin(bo);
3596 		amdgpu_bo_unreserve(bo);
3597 	} else {
3598 		dev_warn(adev->dev,
3599 			"NPA-REQ: BO reserve to unpin failed for handle:%llx:%llx\n",
3600 			handle.handle_hi, handle.handle_lo);
3601 	}
3602 
3603 bo_pin_fail:
3604 bo_reserve_fail:
3605 	amdgpu_ualink_exp_xa_entry_put(exp_xa_node);
3606 
3607 handle_invalid_fail:
3608 	if (send_npa_fail) {
3609 		r = amdgpu_ualink_send_npa_fail_msg(adev, remote_acc_id,
3610 						    handle, fail_reason);
3611 		if (r)
3612 			dev_warn(adev->dev,
3613 				"NPA-REQ: send NPA-FAIL failed remote:%u handle:%llx:%llx\n",
3614 				remote_acc_id, handle.handle_hi, handle.handle_lo);
3615 	}
3616 	return;
3617 conn_setup:
3618 	r = amdgpu_ualink_setup_connection(adev, remote_acc_id);
3619 	if (r)
3620 		dev_warn(adev->dev,
3621 			"NPA-REQ: connection setup failed with remote AccId:%u\n",
3622 			remote_acc_id);
3623 }
3624 
3625 static int amdgpu_ualink_translate_npa_fail_reason(struct amdgpu_device *adev,
3626 						   u32 fail_reason)
3627 {
3628 	switch (fail_reason) {
3629 	case AMDGPU_UALINK_NPA_FAIL_NOSPACE:
3630 		return -ENOSPC;
3631 	case AMDGPU_UALINK_NPA_FAIL_INVALID_HANDLE:
3632 	case AMDGPU_UALINK_NPA_FAIL_DUPLICATE:
3633 	case AMDGPU_UALINK_NPA_FAIL_ERROR:
3634 		return -EINVAL;
3635 	default:
3636 		dev_err(adev->dev,
3637 			"IMPORT: invalid NPA-FAIL reason:%u\n",
3638 			fail_reason);
3639 		return -EINVAL;
3640 	}
3641 }
3642 
3643 static int amdgpu_ualink_do_import_handle(struct amdgpu_device *adev,
3644 				struct amdgpu_ualink_imp_xa_node *imp_xa_node,
3645 				u32 remote_acc_id)
3646 {
3647 	struct amdgpu_ualink_handle handle = imp_xa_node->handle;
3648 	u32 generation_count;
3649 	int r;
3650 
3651 	/* First check if the connection is setup with the
3652 	 * remote GPU. If yes, then initiate the NPA protocol to
3653 	 * get the NPA address.
3654 	 * If not, then initiate the HELLO protocol to first setup
3655 	 * the connection and once the connection is setup, then
3656 	 * initiate the NPA protocol.
3657 	 */
3658 	r = amdgpu_ualink_setup_connection(adev, remote_acc_id);
3659 	if (r) {
3660 		if (r != -EAGAIN)
3661 			dev_warn(adev->dev,
3662 			"IMPORT: connection setup failed with remote AccId:%u\n",
3663 			remote_acc_id);
3664 		return r;
3665 	}
3666 
3667 	/* Send NPA_REQ message */
3668 	r = amdgpu_ualink_send_npa_req_msg(adev, remote_acc_id, handle);
3669 	if (r) {
3670 		dev_warn(adev->dev,
3671 			"IMPORT: NPA-REQ send failed to remote AccId:%u\n",
3672 			remote_acc_id);
3673 		return r;
3674 	}
3675 
3676 	/* Wait for the NPA_RSP to come back */
3677 	r = wait_for_completion_interruptible_timeout(&imp_xa_node->npa_done,
3678 				msecs_to_jiffies(AMDGPU_UALINK_RESP_TIMEOUT));
3679 	if (r == -ERESTARTSYS) {
3680 		dev_err_ratelimited(adev->dev,
3681 			"IMPORT: NPA-RSP wait interrupted by signal\n");
3682 		return r;
3683 	} else if (r == 0) {
3684 		dev_warn(adev->dev,
3685 			"IMPORT: NPA-RSP timeout from remote AccId:%u\n",
3686 			remote_acc_id);
3687 		r = -ETIMEDOUT;
3688 		goto reset_conn;
3689 	}
3690 
3691 	/* If the NPA addr/size isn't filled with valid values, then either
3692 	 * we got a NPA_FAIL or something bad happened. In either case, we
3693 	 * return the error back to user-space.
3694 	 */
3695 	if (imp_xa_node->fail_reason) {
3696 		dev_warn(adev->dev,
3697 			"IMPORT: NPA-REQ failed with fail_reason:%d handle:%llx:%llx\n",
3698 			imp_xa_node->fail_reason, handle.handle_hi, handle.handle_lo);
3699 		return amdgpu_ualink_translate_npa_fail_reason(adev,
3700 						imp_xa_node->fail_reason);
3701 	}
3702 
3703 	if (!imp_xa_node->npa_addr || !imp_xa_node->size) {
3704 		dev_warn(adev->dev,
3705 			"IMPORT: invalid npa:%llx or size:%llx\n",
3706 			imp_xa_node->npa_addr, imp_xa_node->size);
3707 		imp_xa_node->npa_addr = 0;
3708 		imp_xa_node->size = 0;
3709 		return -EINVAL;
3710 	}
3711 
3712 	r = amdgpu_ualink_map_npa_to_dmabuf(adev, imp_xa_node);
3713 	if (r) {
3714 		dev_warn(adev->dev,
3715 			"IMPORT: dmabuf creation failed npa:%llx size:%llx\n",
3716 			imp_xa_node->npa_addr, imp_xa_node->size);
3717 		imp_xa_node->npa_addr = 0;
3718 		imp_xa_node->size = 0;
3719 		return r;
3720 	}
3721 
3722 	/* Add this node to the imported handles list for the remote GPU */
3723 	xa_lock(&adev->ualink.imp_xa);
3724 	list_add(&imp_xa_node->list, &adev->ualink.imp_handles_list[remote_acc_id]);
3725 	xa_unlock(&adev->ualink.imp_xa);
3726 
3727 	return 0;
3728 
3729 reset_conn:
3730 	dev_dbg(adev->dev,
3731 		"IMPORT: Resetting connection for remote:%u\n", remote_acc_id);
3732 	generation_count = amdgpu_ualink_check_conn_ready(adev, remote_acc_id, 0);
3733 	amdgpu_ualink_handle_connection_reset(adev, remote_acc_id,
3734 					      AMDGPU_UALINK_CONN_NOT_READY,
3735 					      generation_count);
3736 	return r;
3737 }
3738 
3739 static int amdgpu_ualink_local_import(struct amdgpu_device *adev,
3740 				      u32 remote_acc_id,
3741 				      struct amdgpu_ualink_handle *handle,
3742 				      int *fd_out)
3743 {
3744 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
3745 	struct amdgpu_device *peer_adev;
3746 	int fd;
3747 
3748 	mutex_lock(&mgpu_info.mutex);
3749 	peer_adev = find_peer_adev(remote_acc_id);
3750 	mutex_unlock(&mgpu_info.mutex);
3751 	if (!peer_adev) {
3752 		dev_err(adev->dev,
3753 			"IMPORT LOCAL: peer adev not found for AccId:%u\n",
3754 			remote_acc_id);
3755 		return -ENODEV;
3756 	}
3757 
3758 	xa_lock(&peer_adev->ualink.exp_xa);
3759 	exp_xa_node = xa_load(&peer_adev->ualink.exp_xa, handle->handle_lo);
3760 	if (!exp_xa_node ||
3761 	    exp_xa_node->handle.handle_hi != handle->handle_hi ||
3762 	    !amdgpu_ualink_exp_xa_entry_get(exp_xa_node)) {
3763 		xa_unlock(&peer_adev->ualink.exp_xa);
3764 		dev_err(adev->dev,
3765 			"IMPORT LOCAL: handle:%llx:%llx not found in peer exp_xa\n",
3766 			handle->handle_hi, handle->handle_lo);
3767 		return -EINVAL;
3768 	}
3769 	xa_unlock(&peer_adev->ualink.exp_xa);
3770 
3771 	get_dma_buf(exp_xa_node->dmabuf);
3772 	/* Get a new fd for the DMABuf */
3773 	fd = dma_buf_fd(exp_xa_node->dmabuf, O_CLOEXEC | O_RDWR);
3774 	if (fd < 0) {
3775 		dev_err(adev->dev,
3776 			"IMPORT LOCAL: dma-buf fd failed handle:%llx:%llx\n",
3777 			handle->handle_hi, handle->handle_lo);
3778 		dma_buf_put(exp_xa_node->dmabuf);
3779 		amdgpu_ualink_exp_xa_entry_put(exp_xa_node);
3780 		return fd;
3781 	}
3782 
3783 	amdgpu_ualink_exp_xa_entry_put(exp_xa_node);
3784 	*fd_out = fd;
3785 	return 0;
3786 }
3787 
3788 int amdgpu_ualink_import_handle(struct drm_device *dev,
3789 				const struct amdgpu_ualink_handle *ualink_handle,
3790 				int *fd_out)
3791 {
3792 	struct amdgpu_ualink_imp_xa_node *imp_xa_node;
3793 	struct amdgpu_device *adev = drm_to_adev(dev);
3794 	struct amdgpu_ualink_handle handle = *ualink_handle;
3795 	u32 remote_acc_id, node_state;
3796 	int r = 0, fd;
3797 
3798 	remote_acc_id = (handle.handle_lo &
3799 			AMDGPU_UALINK_HANDLE_ACCID_MASK);
3800 
3801 	if (remote_acc_id >= AMDGPU_UALINK_ACCEL_MAX) {
3802 		dev_err(adev->dev,
3803 			"IMPORT: invalid remote AccId:%u\n", remote_acc_id);
3804 		return -EINVAL;
3805 	}
3806 
3807 	if (amdgpu_ualink_is_local_accel(adev, remote_acc_id))
3808 		return amdgpu_ualink_local_import(adev, remote_acc_id,
3809 						  &handle, fd_out);
3810 
3811 	xa_lock(&adev->ualink.imp_xa);
3812 	imp_xa_node = xa_load(&adev->ualink.imp_xa, handle.handle_lo);
3813 
3814 	if (imp_xa_node) {
3815 		/* If node state is Not_ready/Pending, then some other
3816 		 * thread is already trying the NPA protocol for the same
3817 		 * ualink handle. Back off and let the thread finish.
3818 		 * If the node state is Teardown, then it means this
3819 		 * node is about to be removed. So let user-space know
3820 		 * that this handle is invalid.
3821 		 */
3822 		node_state = READ_ONCE(imp_xa_node->node_state);
3823 		if (node_state == AMDGPU_UALINK_NODE_NOT_READY ||
3824 		    node_state == AMDGPU_UALINK_NODE_PENDING) {
3825 			xa_unlock(&adev->ualink.imp_xa);
3826 			r = -EAGAIN;
3827 			goto out;
3828 		} else if (node_state == AMDGPU_UALINK_NODE_TEARDOWN) {
3829 			xa_unlock(&adev->ualink.imp_xa);
3830 			r = -EINVAL;
3831 			goto out;
3832 		}
3833 
3834 		/* Increase the refcount while we are processing the request */
3835 		r = amdgpu_ualink_imp_xa_entry_get(imp_xa_node) ? 0 : -EINVAL;
3836 		xa_unlock(&adev->ualink.imp_xa);
3837 
3838 		/* If the refcount has become 0 but the entry is not yet
3839 		 * removed from the Xarray, then return error to user-space.
3840 		 */
3841 		if (r)
3842 			goto out;
3843 	} else {
3844 		xa_unlock(&adev->ualink.imp_xa);
3845 		/* if the partial handle doesn't exist in the Importer xarray then
3846 		 * initiate the NPA protocol and generate the DMABuf corresponding
3847 		 * to the NPA address.
3848 		 * First store the entry in the Xarray.
3849 		 */
3850 		imp_xa_node = kzalloc(sizeof(*imp_xa_node), GFP_KERNEL);
3851 		if (!imp_xa_node) {
3852 			r = -ENOMEM;
3853 			goto out;
3854 		}
3855 		imp_xa_node->adev = adev;
3856 		imp_xa_node->node_state = AMDGPU_UALINK_NODE_NOT_READY;
3857 		imp_xa_node->handle = handle;
3858 		init_completion(&imp_xa_node->npa_done);
3859 		INIT_LIST_HEAD(&imp_xa_node->list);
3860 		kref_init(&imp_xa_node->refcount);
3861 
3862 		/* Take an extra reference to store in the Xarray. The error
3863 		 * handling paths will drop both these references, while a
3864 		 * successful path will drop only one reference to the Xarray
3865 		 * entry.
3866 		 */
3867 		amdgpu_ualink_imp_xa_entry_get(imp_xa_node);
3868 
3869 		/* Check if another thread created a node for the same handle while
3870 		 * we were trying to create and initialize the node.
3871 		 */
3872 		r = xa_insert(&adev->ualink.imp_xa, handle.handle_lo,
3873 			      imp_xa_node, GFP_KERNEL);
3874 		if (r) {
3875 			kfree(imp_xa_node);
3876 			/* -EBUSY means another thread raced us and inserted a
3877 			 * node for the same handle. Ask user-space to retry.
3878 			 */
3879 			if (r == -EBUSY)
3880 				r = -EAGAIN;
3881 			else
3882 				dev_err(adev->dev,
3883 					"IMPORT: XA insert failed for handle:%llx:%llx err:%d\n",
3884 					handle.handle_hi, handle.handle_lo, r);
3885 			goto out;
3886 		}
3887 
3888 		r = amdgpu_ualink_do_import_handle(adev, imp_xa_node, remote_acc_id);
3889 
3890 		/* If error is returned, then cleanup the xarray entry before returning
3891 		 * the error back to user-space
3892 		 */
3893 		if (r) {
3894 			amdgpu_ualink_imp_xa_entry_put(imp_xa_node);
3895 			if (r != -EAGAIN)
3896 				dev_err(adev->dev,
3897 					"IMPORT: XA import failed for handle:%llx:%llx\n",
3898 					handle.handle_hi, handle.handle_lo);
3899 			goto cleanup;
3900 		} else {
3901 			WRITE_ONCE(imp_xa_node->node_state,
3902 				   AMDGPU_UALINK_NODE_READY);
3903 		}
3904 	}
3905 
3906 	/* dma_buf_fd consumes a reference and assigns it to the fd.
3907 	 * Therefore take an extra reference to be consumed. It will be
3908 	 * released when user mode closes the fd.
3909 	 */
3910 	get_dma_buf(imp_xa_node->dmabuf);
3911 
3912 	fd = dma_buf_fd(imp_xa_node->dmabuf, O_CLOEXEC | O_RDWR);
3913 	if (fd >= 0) {
3914 		*fd_out = fd;
3915 	} else {
3916 		dma_buf_put(imp_xa_node->dmabuf);
3917 		r = fd;
3918 		dev_err(adev->dev,
3919 			"IMPORT: dma-buf fd creation failed handle:%llx:%llx\n",
3920 			handle.handle_hi, handle.handle_lo);
3921 	}
3922 
3923 cleanup:
3924 	amdgpu_ualink_imp_xa_entry_put(imp_xa_node);
3925 out:
3926 	return r;
3927 }
3928 
3929 int amdgpu_ualink_export_handle(struct drm_device *dev, struct drm_file *filp,
3930 				u32 gem_handle,
3931 				struct amdgpu_ualink_handle *handle_out)
3932 {
3933 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
3934 	struct amdgpu_ualink_handle handle;
3935 	struct drm_gem_object *gobj;
3936 	struct amdgpu_device *adev;
3937 	struct amdgpu_bo *robj;
3938 	int r = 0, i;
3939 
3940 	gobj = drm_gem_object_lookup(filp, gem_handle);
3941 	if (!gobj)
3942 		return -ENOENT;
3943 
3944 	robj = gem_to_amdgpu_bo(gobj);
3945 	adev = amdgpu_ttm_adev(robj->tbo.bdev);
3946 
3947 	if (!(robj->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM)) {
3948 		dev_err(adev->dev, "Only VRAM BOs can be exported\n");
3949 		r = -EOPNOTSUPP;
3950 		goto out;
3951 	}
3952 
3953 	if (!robj->ualink_handle_lo) {
3954 		/* If no ualink handle generated for BO, then generate one and
3955 		 * add it to the exporter Xarray.
3956 		 */
3957 		exp_xa_node = kzalloc(sizeof(*exp_xa_node), GFP_KERNEL);
3958 		if (!exp_xa_node) {
3959 			dev_err(adev->dev, "Failed to allocate exp_xa_node\n");
3960 			r = -ENOMEM;
3961 			goto out;
3962 		}
3963 
3964 		amdgpu_bo_ref(robj);
3965 		exp_xa_node->bo = robj;
3966 		init_completion(&exp_xa_node->npa_done);
3967 		bitmap_zero(exp_xa_node->importers_bitmap,
3968 			    AMDGPU_UALINK_ACCEL_MAX);
3969 		bitmap_zero(exp_xa_node->npa_release_bitmap,
3970 			AMDGPU_UALINK_ACCEL_MAX);
3971 		kref_init(&exp_xa_node->refcount);
3972 		mutex_init(&exp_xa_node->node_lock);
3973 		INIT_WORK(&exp_xa_node->cleanup_work,
3974 			  amdgpu_ualink_exp_cleanup_worker);
3975 		for (i = 0; i < AMDGPU_UALINK_ACCEL_MAX; i++) {
3976 			INIT_LIST_HEAD(&exp_xa_node->importer_entries[i].list);
3977 			exp_xa_node->importer_entries[i].parent = exp_xa_node;
3978 		}
3979 		/* DMABuf handle for local import of fabric handles */
3980 		exp_xa_node->dmabuf = drm_gem_prime_handle_to_dmabuf(&adev->ddev, filp,
3981 						gem_handle, DRM_CLOEXEC | DRM_RDWR);
3982 		if (IS_ERR(exp_xa_node->dmabuf)) {
3983 			r = PTR_ERR(exp_xa_node->dmabuf);
3984 			dev_err(adev->dev, "Failed to generate DMABuf for the BO\n");
3985 			kfree(exp_xa_node);
3986 			goto out;
3987 		}
3988 
3989 		xa_lock(&adev->ualink.exp_xa);
3990 		amdgpu_generate_ualink_handle(adev, &handle);
3991 		exp_xa_node->handle = handle;
3992 		r = __xa_insert(&adev->ualink.exp_xa, handle.handle_lo,
3993 				exp_xa_node, GFP_KERNEL);
3994 		xa_unlock(&adev->ualink.exp_xa);
3995 		if (r) {
3996 			dev_err(adev->dev, "Failed to insert exp_xa_node into XA: %d\n", r);
3997 			dma_buf_put(exp_xa_node->dmabuf);
3998 			amdgpu_bo_unref(&robj);
3999 			kfree(exp_xa_node);
4000 			goto out;
4001 		}
4002 
4003 		robj->ualink_handle_lo = handle.handle_lo;
4004 		/* Return the generated handle back to the caller */
4005 		*handle_out = handle;
4006 	} else {
4007 		handle_out->handle_lo = robj->ualink_handle_lo;
4008 
4009 		/* Do a sanity check to ensure the handle exists in the XA */
4010 		xa_lock(&adev->ualink.exp_xa);
4011 		exp_xa_node = xa_load(&adev->ualink.exp_xa,
4012 				      robj->ualink_handle_lo);
4013 		xa_unlock(&adev->ualink.exp_xa);
4014 		WARN(!exp_xa_node, "Exp XA: Handle_Lo: %llx not found",
4015 		     robj->ualink_handle_lo);
4016 		if (exp_xa_node)
4017 			handle_out->handle_hi = exp_xa_node->handle.handle_hi;
4018 	}
4019 
4020 out:
4021 	drm_gem_object_put(gobj);
4022 	return r;
4023 }
4024 
4025 int amdgpu_gem_ualink_handle_ioctl(struct drm_device *dev, void *data,
4026 				   struct drm_file *filp)
4027 {
4028 	union drm_amdgpu_ualink_handle *args = data;
4029 	struct amdgpu_device *adev = drm_to_adev(dev);
4030 	struct amdgpu_ualink_handle handle = {};
4031 	u32 gem_handle;
4032 	int r, fd = -1;
4033 
4034 	if (adev->ualink.info->accel_state !=
4035 	    AMDGPU_UALINK_ACCEL_STATE_ACTIVE) {
4036 		dev_err(adev->dev,
4037 			"ualink device is not in active state in vpod\n");
4038 		return -EOPNOTSUPP;
4039 	}
4040 
4041 	/* The input and output members of the ioctl argument alias each other.
4042 	 * Latch every input field before invoking the handlers, and only write
4043 	 * the output fields afterwards.
4044 	 */
4045 	switch (args->in.op) {
4046 	case DRM_AMDGPU_UALINK_HANDLE_OP_EXPORT:
4047 		gem_handle = args->in.gem_handle;
4048 		r = amdgpu_ualink_export_handle(dev, filp, gem_handle, &handle);
4049 		if (!r) {
4050 			args->out.export_ualink_handle[0] = handle.handle_lo;
4051 			args->out.export_ualink_handle[1] = handle.handle_hi;
4052 		}
4053 		break;
4054 	case DRM_AMDGPU_UALINK_HANDLE_OP_IMPORT:
4055 		handle.handle_lo = args->in.import_ualink_handle[0];
4056 		handle.handle_hi = args->in.import_ualink_handle[1];
4057 		r = amdgpu_ualink_import_handle(dev, &handle, &fd);
4058 		if (!r)
4059 			args->out.import_dmabuf_handle = fd;
4060 		break;
4061 	default:
4062 		r = -EINVAL;
4063 		break;
4064 	}
4065 
4066 	return r;
4067 }
4068 
4069 int amdgpu_ualink_manager_start(struct amdgpu_device *adev)
4070 {
4071 	int i, r;
4072 
4073 	r = amdgpu_vm_init(adev, &adev->ualink.npa_vm, 0);
4074 	if (r)
4075 		goto out;
4076 
4077 	/* For pinning page tables and using CPU for page table updates. */
4078 	r = amdgpu_vm_make_npa(adev, &adev->ualink.npa_vm);
4079 	if (r)
4080 		goto uninit_vm;
4081 
4082 	adev->ualink.npa_wq = alloc_workqueue("NPA WQ", WQ_UNBOUND, 0);
4083 	if (unlikely(!adev->ualink.npa_wq)) {
4084 		dev_err(adev->dev, "Failed to allocate NPA WQ\n");
4085 		r = -ENOMEM;
4086 		goto uninit_vm;
4087 	}
4088 
4089 	/* Map this VM to NPA VMID */
4090 	adev->mmhub.funcs->setup_vm_pt_regs(adev, adev->vm_manager.npa_vmid,
4091 			amdgpu_gmc_pd_addr(adev->ualink.npa_vm.root.bo));
4092 
4093 	xa_init(&adev->ualink.exp_xa);
4094 	xa_init(&adev->ualink.imp_xa);
4095 	xa_init(&adev->ualink.handle_invalid_xa);
4096 
4097 	for (i = 0; i < AMDGPU_UALINK_ACCEL_MAX; i++) {
4098 		init_completion(&adev->ualink.conn_state[i].hello_done);
4099 		mutex_init(&adev->ualink.conn_state[i].lock);
4100 		adev->ualink.conn_state[i].state = AMDGPU_UALINK_CONN_NOT_READY;
4101 		INIT_LIST_HEAD(&adev->ualink.exp_handles_list[i]);
4102 		INIT_LIST_HEAD(&adev->ualink.imp_handles_list[i]);
4103 	}
4104 
4105 	amdgpu_ualink_npa_mm_init(adev);
4106 
4107 	return 0;
4108 
4109 uninit_vm:
4110 	amdgpu_vm_fini(adev, &adev->ualink.npa_vm);
4111 out:
4112 	return r;
4113 }
4114 
4115 /* Free every importer entry left in imp_xa at manager stop. */
4116 static void amdgpu_ualink_teardown_imp_xa_entries(struct amdgpu_device *adev)
4117 {
4118 	struct amdgpu_ualink_imp_xa_node *imp_xa_node;
4119 	unsigned long index;
4120 
4121 	xa_for_each(&adev->ualink.imp_xa, index, imp_xa_node) {
4122 		list_del_init(&imp_xa_node->list);
4123 		WRITE_ONCE(imp_xa_node->node_state, AMDGPU_UALINK_NODE_TEARDOWN);
4124 		amdgpu_ualink_release_imp_xa_node(adev, imp_xa_node);
4125 	}
4126 }
4127 
4128 /* Free a single exporter node at manager stop. This is the message-free
4129  * portion of amdgpu_ualink_exp_cleanup_worker().
4130  */
4131 static void amdgpu_ualink_teardown_exp_xa_node(struct amdgpu_device *adev,
4132 				struct amdgpu_ualink_exp_xa_node *exp_xa_node)
4133 {
4134 	DECLARE_BITMAP(importers_bitmap, AMDGPU_UALINK_ACCEL_MAX);
4135 	struct amdgpu_bo *bo = exp_xa_node->bo;
4136 	u32 remote_acc_id;
4137 
4138 	bitmap_copy(importers_bitmap, exp_xa_node->importers_bitmap,
4139 		    AMDGPU_UALINK_ACCEL_MAX);
4140 
4141 	dev_dbg(adev->dev,
4142 		"EXP-STOP: handle:%llx:%llx importers bitmap: %*pbl\n",
4143 		exp_xa_node->handle.handle_hi, exp_xa_node->handle.handle_lo,
4144 		AMDGPU_UALINK_ACCEL_MAX, importers_bitmap);
4145 
4146 	if (!bitmap_empty(importers_bitmap, AMDGPU_UALINK_ACCEL_MAX)) {
4147 		amdgpu_ualink_unmap_all_npa_addr(adev, exp_xa_node);
4148 
4149 		/* Unlink importers and unpin the BO once per importer. */
4150 		if (likely(!amdgpu_bo_reserve(bo, true))) {
4151 			bo->ualink_handle_lo = 0ULL;
4152 			for_each_set_bit(remote_acc_id, importers_bitmap,
4153 					 AMDGPU_UALINK_ACCEL_MAX) {
4154 				list_del_init(&exp_xa_node->importer_entries[remote_acc_id].list);
4155 				amdgpu_bo_unpin(bo);
4156 			}
4157 			amdgpu_bo_unreserve(bo);
4158 		} else {
4159 			dev_warn(adev->dev,
4160 				"EXP-STOP: BO reserve to unpin failed handle:%llx:%llx\n",
4161 				exp_xa_node->handle.handle_hi,
4162 				exp_xa_node->handle.handle_lo);
4163 			for_each_set_bit(remote_acc_id, importers_bitmap,
4164 					 AMDGPU_UALINK_ACCEL_MAX)
4165 				list_del_init(&exp_xa_node->importer_entries[remote_acc_id].list);
4166 		}
4167 
4168 		amdgpu_ualink_free_all_npa_va(adev, exp_xa_node, importers_bitmap);
4169 	}
4170 
4171 	/* Release the export dma-buf and drop the BO ref. */
4172 	dma_buf_put(exp_xa_node->dmabuf);
4173 	amdgpu_bo_unref(&bo);
4174 	exp_xa_node->bo = NULL;
4175 
4176 	mutex_destroy(&exp_xa_node->node_lock);
4177 	kfree(exp_xa_node);
4178 }
4179 
4180 /* Free every exporter entry left in exp_xa at manager stop. These were
4181  * exported but never revoked, so no cleanup worker was queued for them.
4182  */
4183 static void amdgpu_ualink_teardown_exp_xa_entries(struct amdgpu_device *adev)
4184 {
4185 	struct amdgpu_ualink_exp_xa_node *exp_xa_node;
4186 	unsigned long index;
4187 
4188 	xa_for_each(&adev->ualink.exp_xa, index, exp_xa_node) {
4189 		xa_erase(&adev->ualink.exp_xa, index);
4190 		amdgpu_ualink_teardown_exp_xa_node(adev, exp_xa_node);
4191 	}
4192 }
4193 
4194 void amdgpu_ualink_manager_stop(struct amdgpu_device *adev)
4195 {
4196 	int i;
4197 
4198 	adev->mmhub.funcs->setup_vm_pt_regs(adev, adev->vm_manager.npa_vmid, 0);
4199 
4200 	/* Mark connections down so the drained workers and the teardown below
4201 	 * take the message-free path in amdgpu_ualink_check_conn_ready().
4202 	 */
4203 	for (i = 0; i < AMDGPU_UALINK_ACCEL_MAX; i++) {
4204 		mutex_lock(&adev->ualink.conn_state[i].lock);
4205 		adev->ualink.conn_state[i].state = AMDGPU_UALINK_CONN_NOT_READY;
4206 		mutex_unlock(&adev->ualink.conn_state[i].lock);
4207 	}
4208 
4209 	/* Drain in-flight exporter cleanup work so revoked nodes in
4210 	 * handle_invalid_xa free themselves and empty that xarray.
4211 	 */
4212 	drain_workqueue(adev->ualink.npa_wq);
4213 
4214 	/* Free live entries before the NPA allocator is torn down, so NPA
4215 	 * addresses can still be unmapped and freed.
4216 	 */
4217 	amdgpu_ualink_teardown_imp_xa_entries(adev);
4218 	amdgpu_ualink_teardown_exp_xa_entries(adev);
4219 
4220 	amdgpu_ualink_npa_mm_fini(adev);
4221 
4222 	/* All three xarrays are empty by now. */
4223 	xa_destroy(&adev->ualink.exp_xa);
4224 	xa_destroy(&adev->ualink.imp_xa);
4225 	xa_destroy(&adev->ualink.handle_invalid_xa);
4226 
4227 	for (i = 0; i < AMDGPU_UALINK_ACCEL_MAX; i++)
4228 		mutex_destroy(&adev->ualink.conn_state[i].lock);
4229 
4230 	destroy_workqueue(adev->ualink.npa_wq);
4231 	amdgpu_vm_fini(adev, &adev->ualink.npa_vm);
4232 }
4233 
4234 /*
4235  * UALink remote interrupt and shootdown
4236  */
4237 
4238 /* UALINK ring buffer size, same for both remote shootdown and interrupt ring */
4239 #define AMDGPU_UALINK_RB_SIZE	4096
4240 
4241 #define AMDGPU_UALINK_METADATA_HEADER	0x4E485446
4242 
4243 /* 2MB NPA start address for 2MB page mapping */
4244 #define AMDGPU_UALINK_SOURCE_ALIAS_NPA_OFFSET SZ_2M
4245 
4246 struct amdgpu_ualink_metadata {
4247 	u32 header;
4248 
4249 	/*
4250 	 * "ring entries" as unit. So the ring-size-in-bytes could be calculated
4251 	 * as entry-size * 2^RBsize. This would make the minimum size a single
4252 	 * entry and the maximum size 32786 entries.
4253 	 *
4254 	 * u32 rb_size:4;
4255 	 * u32 reserved0:4;
4256 	 * u32 vmid:4;
4257 	 * u32 reserved1:20;
4258 	 */
4259 	u32 rb_size;
4260 
4261 	/* ring buffer base address for remote interrupt */
4262 	u64 ri_rb;
4263 
4264 	/* tlb invalidate ring buffer base address for remote shootdown */
4265 	u64 tlb_inv_rb;
4266 
4267 	/* remote interrupt Tail pointer, write pointer address */
4268 	u64 tailptr_ri;
4269 
4270 	/* TLB invalidate ring buffer's Tail pointer, write pointer address */
4271 	u64 tailptr_tlb_inv;
4272 };
4273 
4274 struct amdgpu_ualink_wb {
4275 	/* last finished command seq number */
4276 	u32 data;
4277 
4278 	/* command complete error code */
4279 	u32 status;
4280 
4281 	/* ring rptr updated by FW */
4282 	u64 rptr;
4283 };
4284 
4285 /*
4286  * For remote interrupt and shootdown
4287  */
4288 struct amdgpu_ualink_ring {
4289 	u32 rb_size;
4290 
4291 	/* writeback data */
4292 	u32 seq;
4293 
4294 	/* local copy */
4295 	u64 wptr, rptr;
4296 
4297 	/* NPA gart mapping for SDMA */
4298 	u64 rb_npa_gart;
4299 	u64 wptr_npa_gart;
4300 	u64 doorbell_npa_gart;
4301 
4302 	/* gart mapping node */
4303 	struct drm_mm_node mm_node_rb;
4304 	struct drm_mm_node mm_node_wptr;
4305 	struct drm_mm_node mm_node_doorbell;
4306 
4307 	/* seq, complete status write back cpu address */
4308 	struct amdgpu_ualink_wb *wb_cpu;
4309 
4310 	/* true if fw write back address updated successfully */
4311 	bool ready;
4312 };
4313 
4314 struct amdgpu_ualink_peer {
4315 	/* remote interrupt and shootdown uses same SDMA entity */
4316 	struct mutex lock;
4317 
4318 	/* SDMA engine to send remote command via NPA */
4319 	struct drm_sched_entity entity;
4320 
4321 	/* to select different DXS ports, cycles through different values */
4322 	u32 dxs_port;
4323 
4324 	struct amdgpu_ualink_ring interrupt;
4325 	struct amdgpu_ualink_ring shootdown;
4326 };
4327 
4328 struct amdgpu_ualink_remote {
4329 	/* ualink metadata passed to MPNHT FW */
4330 	struct amdgpu_bo		*metadata_bo;
4331 	u64				metadata_gpu_addr;
4332 	void				*metadata_cpu_addr;
4333 
4334 	/* ualink ring, tlb ring buffer, wptr */
4335 	struct amdgpu_bo		*ring_bo;
4336 	u64				rb_gpu_addr;
4337 	void				*rb_cpu_addr;
4338 
4339 	/* ualink rptr, wb data, statuss for address alias mode */
4340 	struct amdgpu_bo		*rptr_bo;
4341 	u64				rptr_gpu_addr;
4342 	void				*rptr_cpu_addr;
4343 	u64				rptr_npa;
4344 
4345 	/* address alias mode alloc npa address for shared wb */
4346 	struct drm_mm_node		rptr_mm_node;
4347 
4348 	/*
4349 	 * Owned snapshot of the vPod's active accelerator bitmap, taken at
4350 	 * sw_init time. Must NOT alias info->vpod.active_accel_bits, which
4351 	 * psp_ual_query_info() refreshes on every commit: aliasing it would let
4352 	 * teardown unmap a different set than setup mapped, leaking drm_mm nodes
4353 	 * in the shared GTT manager.
4354 	 */
4355 	DECLARE_BITMAP(active_accel_bits, AMDGPU_UALINK_ACCEL_MAX);
4356 	u32				num_accel;
4357 
4358 	/* remote GPUs ring buffer, read, write pointer local copy and gart mapping */
4359 	struct amdgpu_ualink_peer	peer[AMDGPU_UALINK_ACCEL_MAX];
4360 
4361 	/* use lsdma write to NPA address for remote interrupt */
4362 	bool			       use_lsdma;
4363 };
4364 
4365 static inline struct amdgpu_ualink_remote *to_remote(struct amdgpu_device *adev)
4366 {
4367 	return adev->ualink.remote;
4368 }
4369 
4370 /*
4371  * Returns true if the vPod membership most recently reported by firmware
4372  * (info->vpod.active_accel_bits, read back via psp_ual_query_info() on the
4373  * committing GPU) differs from the owned snapshot captured when this
4374  * accelerator was last activated (remote->active_accel_bits). Used to
4375  * decide whether an accelerator must be (re)built to match the new member
4376  * set. A NULL remote means the accelerator has never been activated (no
4377  * snapshot yet), which also counts as "changed" so it gets brought up.
4378  */
4379 static bool amdgpu_ualink_vpod_membership_changed(struct amdgpu_device *adev)
4380 {
4381 	struct amdgpu_ualink_remote *remote = to_remote(adev);
4382 
4383 	if (!remote)
4384 		return true;
4385 
4386 	return !bitmap_equal(remote->active_accel_bits,
4387 			     adev->ualink.info->vpod.active_accel_bits,
4388 			     AMDGPU_UALINK_ACCEL_MAX);
4389 }
4390 
4391 static inline u32 ualink_accel_id(struct amdgpu_device *adev)
4392 {
4393 	return adev->ualink.info->ppod.accel_id;
4394 }
4395 
4396 static inline enum amdgpu_ualink_addr_mode ualink_addr_mode(struct amdgpu_device *adev)
4397 {
4398 	return adev->ualink.info->vpod.addr_mode;
4399 }
4400 
4401 /*
4402  * address mode and NPA address for ring wptr, rptr, wb status, wb data
4403  *
4404  * source identification address mode
4405  *
4406  * we need to export different tail pointers for different remote GPU accel_id,
4407  * hence we need to allocate a whole page for each remote GPU separately.
4408  *
4409  * rptr, wb data, status share the whole page with wptr.
4410  *
4411  *     1 page reserved NPA address for 1 active remote GPU, max 255 pages
4412  *     starting address: wptr NPA address + accel_id * 4K
4413  *     offset:
4414  *         remote interrupt ring wptr 0
4415  *         remote shootdown ring wptr 8
4416  *         remote interrupt wb status 16
4417  *         remote interrupt wb data   20
4418  *         remote interrupt ring rptr 24
4419  *         remote shootdown wb status 32
4420  *         remote shootdown wb data   36
4421  *         remote shootdown ring rptr 40
4422  *
4423  * source aliasing address mode
4424  *
4425  * wptr for different remote GPU can share same reserved 1 page NPA address page.
4426  *
4427  * to save reserved NPA address space, rptr, wb data, status for different
4428  * remote GPU share same allocated 2 pages NPA address.
4429  *
4430  *     1 page reserved NPA address for wptr of all active remote GPUs
4431  *     offset:
4432  *         remote interrupt ring wptr accel_id * 16
4433  *         remote shootdown ring wptr accel_id * 16 + 8
4434  *
4435  *     2 page allocated NPA address for rptr, writeback of all active remote GPUs
4436  *     starting address: at accel_id * 32 for each remote GPU
4437  *     offset:
4438  *         remote interrupt wb status 0
4439  *         remote interrupt wb data   4
4440  *         remote interrupt ring rptr 8
4441  *         remote shootdown wb status 16
4442  *         remote shootdown wb data   20
4443  *         remote shootdown ring rptr 24
4444  */
4445 static inline u32 ualink_wptr_size(struct amdgpu_device *adev)
4446 {
4447 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT)
4448 		return AMDGPU_GPU_PAGE_SIZE;
4449 	else
4450 		return 0;	/* wptr uses the ring buffer for itself */
4451 }
4452 
4453 static inline u32 ualink_wb_size(struct amdgpu_device *adev)
4454 {
4455 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT)
4456 		return 0;	/* share same page with wptr */
4457 	else
4458 		return 2 * sizeof(struct amdgpu_ualink_wb);
4459 }
4460 
4461 static inline u32 ualink_wptr_offset(struct amdgpu_device *adev, u32 accel_id)
4462 {
4463 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT)
4464 		return 0;	/* one separate page per GPU */
4465 	else
4466 		return accel_id * 2 * sizeof(u64);	/* two pointers per GPU */
4467 }
4468 
4469 static inline u32 ualink_tlb_wptr_offset(struct amdgpu_device *adev, u32 accel_id)
4470 {
4471 	return ualink_wptr_offset(adev, accel_id) + sizeof(u64);
4472 }
4473 
4474 static inline u32 ualink_wb_offset(struct amdgpu_device *adev, u32 accel_id)
4475 {
4476 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT)
4477 		return 2 * sizeof(u64);	/* after two wptr pointers */
4478 	else
4479 		return accel_id * ualink_wb_size(adev);
4480 }
4481 
4482 static inline u32 ualink_tlb_wb_offset(struct amdgpu_device *adev, u32 accel_id)
4483 {
4484 	return ualink_wb_offset(adev, accel_id) + sizeof(struct amdgpu_ualink_wb);
4485 }
4486 
4487 static void amdgpu_ualink_flush_tlb(struct amdgpu_device *adev, u32 flush_type)
4488 {
4489 	u32 bit;
4490 
4491 	bit = AMDGPU_MMHUB0_START;
4492 
4493 	for_each_set_bit_from(bit, adev->vmhubs_mask, AMDGPU_MAX_VMHUBS)
4494 		amdgpu_gmc_flush_gpu_tlb(adev, adev->vm_manager.npa_vmid,
4495 					bit, flush_type);
4496 }
4497 
4498 /**
4499  * amdgpu_ualink_npa_vm_map_range - Map a range in the NPA VM
4500  * @adev: amdgpu device pointer
4501  * @bo: buffer object backing the mapping
4502  * @pte_flags: page table entry flags
4503  * @offset: offset into the buffer object in bytes
4504  * @size_in_pages: size of the range to map in pages
4505  * @npa_in_pages: NPA target address in pages
4506  *
4507  * Maps a buffer object range into the NPA VM page table at the specified
4508  * NPA address.
4509  *
4510  * Return: 0 on success, negative error code on failure
4511  */
4512 static int amdgpu_ualink_npa_vm_map_range(struct amdgpu_device *adev, struct amdgpu_bo *bo,
4513 				   u64 pte_flags, u64 offset, u64 size_in_pages,
4514 				   u64 npa_in_pages)
4515 {
4516 	struct amdgpu_vm *npa_vm = &adev->ualink.npa_vm;
4517 	int r;
4518 
4519 	dev_dbg(adev->dev, "offset 0x%llx size 0x%llx flags 0x%llx npa 0x%llx\n",
4520 		offset, size_in_pages << AMDGPU_GPU_PAGE_SHIFT, pte_flags,
4521 		npa_in_pages << AMDGPU_GPU_PAGE_SHIFT);
4522 
4523 	r = amdgpu_vm_update_range(adev, npa_vm, false, false, true,
4524 				   false, NULL, npa_in_pages,
4525 				   npa_in_pages + size_in_pages - 1,
4526 				   pte_flags, offset, adev->vm_manager.vram_base_offset,
4527 				   bo->tbo.resource, NULL, &npa_vm->last_update);
4528 	if (r)
4529 		dev_dbg(adev->dev, "failed %d to map npa 0x%llx to NPA VM\n", r,
4530 			npa_in_pages << AMDGPU_GPU_PAGE_SHIFT);
4531 	return r;
4532 }
4533 
4534 /**
4535  * amdgpu_npa_vm_unmap_range - Unmap a range from the NPA VM
4536  * @adev: amdgpu device pointer
4537  * @bo: buffer object backing the mapping
4538  * @pte_flags: page table entry flags
4539  * @offset: offset into the buffer object in bytes
4540  * @size_in_pages: size of the range to unmap in pages
4541  * @npa_in_pages: NPA target address in pages
4542  *
4543  * Removes a previously established mapping from the NPA VM page table.
4544  *
4545  * Return: 0 on success, negative error code on failure
4546  */
4547 static int amdgpu_ualink_npa_vm_unmap_range(struct amdgpu_device *adev, struct amdgpu_bo *bo,
4548 				     u64 pte_flags, u64 offset, u64 size_in_pages,
4549 				     u64 npa_in_pages)
4550 {
4551 	struct amdgpu_vm *npa_vm = &adev->ualink.npa_vm;
4552 	int r;
4553 
4554 	dev_dbg(adev->dev, "offset 0x%llx size 0x%llx flags 0x%llx npa 0x%llx\n",
4555 		offset, size_in_pages << AMDGPU_GPU_PAGE_SHIFT, pte_flags,
4556 		npa_in_pages << AMDGPU_GPU_PAGE_SHIFT);
4557 
4558 	r = amdgpu_vm_update_range(adev, npa_vm, false, false, true,
4559 				   false, NULL, npa_in_pages,
4560 				   npa_in_pages + size_in_pages - 1,
4561 				   pte_flags, offset, 0, bo->tbo.resource, NULL,
4562 				   &npa_vm->last_update);
4563 	if (r)
4564 		dev_dbg(adev->dev, "failed %d to unmap npa 0x%llx from NPA VM\n", r,
4565 			npa_in_pages << AMDGPU_GPU_PAGE_SHIFT);
4566 	return r;
4567 }
4568 
4569 /*
4570  * Reserved NPA space for remote shootdown and interrupt ring buffer,
4571  * write pointers, read pointers and writeback buffers
4572  *
4573  * NPA ring type: 0 = shootdown, 1 = interrupt, 2 = tailptr (wptr)
4574  */
4575 enum ring_buffer_type {
4576 	RB_TYPE_TLB_INV			= 0,
4577 	RB_TYPE_REMOTE_INTERRUPT	= 1,
4578 	RB_TYPE_TAILPTR			= 2
4579 };
4580 
4581 /**
4582  * amdgpu_ualink_npa_addr - Get reserved NPA address for ring buffer
4583  * @adev: amdgpu device pointer
4584  * @type: Ring buffer type (TLB_INV, REMOTE_INTERRUPT, or TAILPTR)
4585  * @src_accel_id: Source accelerator ID
4586  * @dst_accel_id: Destination accelerator ID
4587  *
4588  * Return: NPA address for the specified ring buffer type and GPUs
4589  */
4590 static u64 amdgpu_ualink_npa_addr(struct amdgpu_device *adev, u32 type,
4591 				  u32 src_accel_id, u32 dst_accel_id)
4592 {
4593 	u32 addr_mode = ualink_addr_mode(adev);
4594 	u64 npa;
4595 
4596 	WARN_ON_ONCE(src_accel_id >= AMDGPU_UALINK_ACCEL_MAX ||
4597 		     dst_accel_id >= AMDGPU_UALINK_ACCEL_MAX ||
4598 		     type > RB_TYPE_TAILPTR ||
4599 		     (addr_mode != AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT &&
4600 		     addr_mode != AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS));
4601 
4602 	switch (addr_mode) {
4603 	case AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT:
4604 		npa = (u64)src_accel_id << 41 | type << 12;
4605 		break;
4606 
4607 	case AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS:
4608 	default:
4609 		if (type == RB_TYPE_TAILPTR)
4610 			npa = (u64)dst_accel_id << 13;
4611 		else
4612 			npa = (u64)src_accel_id << 13 | type << 12;
4613 
4614 		/*
4615 		 * In order to avoid address conflicts between source-identification
4616 		 * and source-aliasing mode, add 2MB to the buffer addresses in
4617 		 * source-aliasing mode. This way in a misconfigured cluster, a GPU
4618 		 * configured in the wrong address mode will access unmapped NPA addresses
4619 		 * rather than the wrong buffer mappings.
4620 		 */
4621 		npa += AMDGPU_UALINK_SOURCE_ALIAS_NPA_OFFSET;
4622 		break;
4623 	}
4624 
4625 	dev_dbg(adev->dev, "addr mode %d from accel %d to accel %d type %d NPA 0x%llx\n",
4626 		addr_mode, src_accel_id, dst_accel_id, type, npa);
4627 
4628 	return npa;
4629 }
4630 
4631 /**
4632  * amdgpu_ualink_gart_npa_addr - Get GART-mapped NPA address for ring buffer
4633  * @adev: amdgpu device pointer
4634  * @type: Ring buffer type (TLB_INV, REMOTE_INTERRUPT, or TAILPTR)
4635  * @src_accel_id: Source accelerator ID
4636  * @dst_accel_id: Destination accelerator ID
4637  *
4638  * Computes the NPA address suitable for GART mapping by adding dst_accid_id to
4639  * NPA address to access remote by SDMA.
4640 
4641  * clears the source GPU ID bits from the NPA address which is set for
4642  * address-identification mode.
4643  *
4644  * Return: NPA address adjusted for GART mapping
4645  */
4646 
4647 #define AMDGPU_UALINK_GART_NPA_ADDR_GPUID_SHIFT		41
4648 #define AMDGPU_UALINK_GART_NPA_ADDR_GPUID_MASK		GENMASK_ULL(50, 41)
4649 
4650 static u64 amdgpu_ualink_gart_npa_addr(struct amdgpu_device *adev, u32 type,
4651 					u32 src_accel_id, u32 dst_accel_id)
4652 {
4653 	u64 npa;
4654 
4655 	npa = amdgpu_ualink_npa_addr(adev, type, src_accel_id, dst_accel_id);
4656 
4657 	/* wiping out source accelerator id */
4658 	npa &= ~AMDGPU_UALINK_GART_NPA_ADDR_GPUID_MASK;
4659 
4660 	return npa | ((u64)dst_accel_id << AMDGPU_UALINK_GART_NPA_ADDR_GPUID_SHIFT);
4661 }
4662 
4663 /**
4664  * amdgpu_ualink_reserve_npa_vm_and_bos - Reserve the NPA VM page directory and BOs
4665  * @adev: amdgpu device pointer
4666  * @bos: array of buffer objects to reserve
4667  * @n_bos: number of entries in @bos
4668  * @exec: drm_exec context to initialize and use for locking
4669  * @interruptible: true to use the interruptible dma_resv_lock
4670  *
4671  * Initializes @exec and uses it to lock all BOs in @bos together with the
4672  * NPA VM page directory, retrying on contention. On failure, @exec is
4673  * finalized and the error code is returned.
4674  *
4675  * Returns: 0 on success, negative error code on failure.
4676  */
4677 static int amdgpu_ualink_reserve_npa_vm_and_bos(struct amdgpu_device *adev,
4678 						struct amdgpu_bo *bos[], u32 n_bos,
4679 						struct drm_exec *exec,
4680 						bool interruptible)
4681 {
4682 	u32 flags = DRM_EXEC_IGNORE_DUPLICATES;
4683 	int i, r = 0;
4684 
4685 	if (interruptible)
4686 		flags |= DRM_EXEC_INTERRUPTIBLE_WAIT;
4687 
4688 	dev_dbg(adev->dev, "reserve NPA vm and %d bos\n", n_bos);
4689 
4690 	drm_exec_init(exec, flags, 0);
4691 
4692 	drm_exec_until_all_locked(exec) {
4693 		for (i = 0; i < n_bos; i++) {
4694 			r = drm_exec_lock_obj(exec, &bos[i]->tbo.base);
4695 			drm_exec_retry_on_contention(exec);
4696 			if (unlikely(r))
4697 				goto out;
4698 		}
4699 
4700 		r = amdgpu_vm_lock_pd(&adev->ualink.npa_vm, exec, 0);
4701 		drm_exec_retry_on_contention(exec);
4702 		if (unlikely(r))
4703 			goto out;
4704 	}
4705 
4706 out:
4707 	if (r)
4708 		drm_exec_fini(exec);
4709 	return r;
4710 
4711 }
4712 
4713 /**
4714  * amdgpu_ualink_unreserve_npa_vm_and_bos - Release the NPA VM page directory and BOs
4715  * @adev: amdgpu device pointer
4716  * @exec: drm_exec context previously initialized by
4717  *        amdgpu_ualink_reserve_npa_vm_and_bos()
4718  *
4719  * Finalizes @exec, releasing all locks on the NPA VM page directory and
4720  * the associated BOs acquired during reservation.
4721  */
4722 static void amdgpu_ualink_unreserve_npa_vm_and_bos(struct amdgpu_device *adev,
4723 						   struct drm_exec *exec)
4724 {
4725 	dev_dbg(adev->dev, "unreserve NPA vm and bos\n");
4726 	drm_exec_fini(exec);
4727 }
4728 
4729 /**
4730  * amdgpu_ualink_metadata_npa_unmapping - Tear down NPA address mappings
4731  * @adev: amdgpu device pointer
4732  *
4733  * Unmaps all NPA address mappings from the NPA VM for ring buffers,
4734  * write pointers, and read pointers. Waits for outstanding DMA fences
4735  * and flushes the TLB.
4736  */
4737 static void amdgpu_ualink_metadata_npa_unmapping(struct amdgpu_device *adev)
4738 {
4739 	struct amdgpu_ualink_remote *remote = to_remote(adev);
4740 	u64 timeout = msecs_to_jiffies(2000);
4741 	u32 dst_accel_id = ualink_accel_id(adev);
4742 	struct amdgpu_bo *bos[2];
4743 	u32 n_bos;
4744 	struct dma_fence *fence;
4745 	struct drm_exec exec;
4746 	u32 rptr_size, rptr_size_in_pages;
4747 	u32 rb_size, rb_size_in_pages;
4748 	u64 pte_flags = adev->gmc.noretry_flags;
4749 	u64 npa;
4750 	int r;
4751 
4752 	if (!remote->ring_bo)
4753 		return;
4754 
4755 	rb_size = AMDGPU_UALINK_RB_SIZE;
4756 	rb_size_in_pages = rb_size >> AMDGPU_GPU_PAGE_SHIFT;
4757 
4758 	bos[0] = remote->ring_bo;
4759 	n_bos = 1;
4760 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS) {
4761 		bos[1] = remote->rptr_bo;
4762 		n_bos = 2;
4763 	}
4764 
4765 	r = amdgpu_ualink_reserve_npa_vm_and_bos(adev, bos, n_bos, &exec, false);
4766 	if (unlikely(r))
4767 		return;
4768 
4769 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS) {
4770 		/* rptr npa mapping, up to allocated 2 pages npa address */
4771 		rptr_size = ualink_wb_size(adev);
4772 		rptr_size = AMDGPU_GPU_PAGE_ALIGN(rptr_size * remote->num_accel);
4773 		rptr_size_in_pages = rptr_size >> AMDGPU_GPU_PAGE_SHIFT;
4774 
4775 		npa = remote->rptr_npa;
4776 
4777 		amdgpu_ualink_npa_vm_unmap_range(adev, remote->rptr_bo,
4778 						 pte_flags, 0, rptr_size_in_pages,
4779 						 npa >> AMDGPU_GPU_PAGE_SHIFT);
4780 		amdgpu_ualink_npa_free_va(adev, &remote->rptr_mm_node);
4781 
4782 		/*
4783 		 * unmap wptr, remote interrupt, shootdown ring.
4784 		 * wptr page is part of the single 2MB mapping for remote GPUs
4785 		 * interrupt and shootdown ring buffer
4786 		 */
4787 		npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_TLB_INV,
4788 					     0, dst_accel_id);
4789 		amdgpu_ualink_npa_vm_unmap_range(adev, remote->ring_bo, pte_flags,
4790 						 0,
4791 						 2 * rb_size_in_pages * AMDGPU_UALINK_ACCEL_MAX,
4792 						 npa >> AMDGPU_GPU_PAGE_SHIFT);
4793 	} else {
4794 		u32 wptr_offset = 2 * rb_size * remote->num_accel;
4795 		u32 idx = 0;
4796 		u32 accel_id;
4797 
4798 		/* source identification mode */
4799 		for_each_set_bit(accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX) {
4800 			if (accel_id == dst_accel_id)
4801 				continue;
4802 
4803 			/* remote interrupt ring npa mapping */
4804 			npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_REMOTE_INTERRUPT,
4805 						     accel_id, dst_accel_id);
4806 			amdgpu_ualink_npa_vm_unmap_range(adev, remote->ring_bo,
4807 							 pte_flags, idx * 2 * rb_size,
4808 							 rb_size_in_pages,
4809 							 npa >> AMDGPU_GPU_PAGE_SHIFT);
4810 
4811 			/* remote shootdown ring npa mapping */
4812 			npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_TLB_INV, accel_id,
4813 						     dst_accel_id);
4814 			amdgpu_ualink_npa_vm_unmap_range(adev, remote->ring_bo,
4815 							 pte_flags, (idx * 2 + 1) * rb_size,
4816 							 rb_size_in_pages,
4817 							 npa >> AMDGPU_GPU_PAGE_SHIFT);
4818 
4819 			/* wptr, rptr npa mapping */
4820 			npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_TAILPTR, accel_id,
4821 						      dst_accel_id);
4822 			amdgpu_ualink_npa_vm_unmap_range(adev, remote->ring_bo,
4823 						  pte_flags, wptr_offset + idx * PAGE_SIZE,
4824 						  1, npa >> AMDGPU_GPU_PAGE_SHIFT);
4825 			idx++;
4826 		}
4827 	}
4828 
4829 	r = amdgpu_vm_update_pdes(adev, &adev->ualink.npa_vm, false);
4830 	if (r) {
4831 		dev_dbg(adev->dev, "failed %d to update directories\n", r);
4832 		goto out_unreserve;
4833 	}
4834 
4835 	fence = dma_fence_get(adev->ualink.npa_vm.last_update);
4836 	if (fence) {
4837 		r = dma_fence_wait_timeout(fence, true, timeout);
4838 		dma_fence_put(fence);
4839 		if (r <= 0)
4840 			dev_dbg(adev->dev, "failed %d to dma fence wait\n", r);
4841 	}
4842 
4843 	amdgpu_ualink_flush_tlb(adev, TLB_FLUSH_HEAVYWEIGHT);
4844 out_unreserve:
4845 	amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
4846 }
4847 
4848 /**
4849  * amdgpu_ualink_metadata_npa_mapping - Setup NPA address mapping in VM
4850  * @adev: amdgpu device pointer
4851  *
4852  * Maps NPA addresses to GPA for metadata ring buffers, write pointers,
4853  * on NPA VMID 15.
4854  *
4855  * Return: 0 on success, negative error code on failure
4856  */
4857 static int amdgpu_ualink_metadata_npa_mapping(struct amdgpu_device *adev)
4858 {
4859 	struct amdgpu_ualink_remote *remote = to_remote(adev);
4860 	u32 dst_accel_id = ualink_accel_id(adev);
4861 	u64 timeout = msecs_to_jiffies(2000);
4862 	struct amdgpu_bo *bos[2];
4863 	u32 n_bos;
4864 	struct dma_fence *fence;
4865 	struct drm_exec exec;
4866 	u32 rb_size, rb_size_in_pages;
4867 	u64 npa, npa_in_pages, pte_flags;
4868 	int r;
4869 
4870 	rb_size = AMDGPU_UALINK_RB_SIZE;
4871 	rb_size_in_pages = rb_size >> AMDGPU_GPU_PAGE_SHIFT;
4872 
4873 	bos[0] = remote->ring_bo;
4874 	n_bos = 1;
4875 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS) {
4876 		bos[1] = remote->rptr_bo;
4877 		n_bos = 2;
4878 	}
4879 
4880 	r = amdgpu_ualink_reserve_npa_vm_and_bos(adev, bos, n_bos, &exec, false);
4881 	if (unlikely(r))
4882 		return r;
4883 
4884 	pte_flags = amdgpu_ttm_tt_pte_flags(adev, remote->ring_bo->tbo.ttm,
4885 					    remote->ring_bo->tbo.resource);
4886 	dev_dbg(adev->dev, "init pte_flags 0x%llx\n", pte_flags);
4887 
4888 	amdgpu_gmc_get_vm_pte(adev, &adev->ualink.npa_vm, remote->ring_bo,
4889 			      AMDGPU_VM_MTYPE_DEFAULT, &pte_flags);
4890 	dev_dbg(adev->dev, "after get coherent pte_flags 0x%llx\n", pte_flags);
4891 
4892 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS) {
4893 		u32 rptr_size, rptr_size_in_pages;
4894 
4895 		/* rptr npa mapping, up to allocated 2 pages npa address */
4896 		rptr_size = ualink_wb_size(adev);
4897 		rptr_size = AMDGPU_GPU_PAGE_ALIGN(rptr_size * remote->num_accel);
4898 		rptr_size_in_pages = rptr_size >> AMDGPU_GPU_PAGE_SHIFT;
4899 
4900 		r = amdgpu_ualink_npa_alloc_va(adev, &remote->rptr_mm_node,
4901 					       0, 0, 0,
4902 					       rptr_size_in_pages);
4903 		if (r)
4904 			goto out;
4905 
4906 		npa_in_pages = remote->rptr_mm_node.start;
4907 
4908 		dev_dbg(adev->dev, "source aliasing rptr alloc 0x%llx and map to npa vm\n",
4909 			npa_in_pages << AMDGPU_GPU_PAGE_SHIFT);
4910 
4911 		r = amdgpu_ualink_npa_vm_map_range(adev, remote->rptr_bo, pte_flags, 0,
4912 						   rptr_size_in_pages,
4913 						   npa_in_pages);
4914 		if (r)
4915 			goto error_npa_mapping;
4916 
4917 		remote->rptr_npa = npa_in_pages << AMDGPU_GPU_PAGE_SHIFT;
4918 
4919 		/* wptr, remote interrupt, shootdown ring, single big 2MB mapping */
4920 		npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_TLB_INV,
4921 					     0, dst_accel_id);
4922 		r = amdgpu_ualink_npa_vm_map_range(adev, remote->ring_bo, pte_flags,
4923 						   0,
4924 						   2 * rb_size_in_pages * AMDGPU_UALINK_ACCEL_MAX,
4925 						   npa >> AMDGPU_GPU_PAGE_SHIFT);
4926 		if (r)
4927 			goto error_npa_mapping;
4928 
4929 	} else {
4930 		u32 wptr_offset = 2 * rb_size * remote->num_accel;
4931 		u32 accel_id, idx = 0;
4932 
4933 		/* Source identification mode */
4934 		for_each_set_bit(accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX) {
4935 			if (accel_id == dst_accel_id)
4936 				continue;
4937 
4938 			/* remote interrupt ring npa mapping */
4939 			npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_REMOTE_INTERRUPT,
4940 						      accel_id, dst_accel_id);
4941 			r = amdgpu_ualink_npa_vm_map_range(adev, remote->ring_bo, pte_flags,
4942 							   idx * 2 * rb_size,
4943 							   rb_size_in_pages,
4944 							   npa >> AMDGPU_GPU_PAGE_SHIFT);
4945 			if (r)
4946 				goto error_npa_mapping;
4947 
4948 			/* remote shootdown ring npa mapping */
4949 			npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_TLB_INV, accel_id,
4950 						     dst_accel_id);
4951 			r = amdgpu_ualink_npa_vm_map_range(adev, remote->ring_bo, pte_flags,
4952 							   (idx * 2 + 1) * rb_size,
4953 							   rb_size_in_pages,
4954 							   npa >> AMDGPU_GPU_PAGE_SHIFT);
4955 			if (r)
4956 				goto error_npa_mapping;
4957 
4958 			/* wptr, rptr npa mapping */
4959 			npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_TAILPTR, accel_id,
4960 						     dst_accel_id);
4961 			r = amdgpu_ualink_npa_vm_map_range(adev, remote->ring_bo,
4962 							   pte_flags,
4963 							   wptr_offset + idx * PAGE_SIZE,
4964 							   1, npa >> AMDGPU_GPU_PAGE_SHIFT);
4965 			if (r)
4966 				goto error_npa_mapping;
4967 
4968 			idx++;
4969 		}
4970 	}
4971 
4972 	r = amdgpu_vm_update_pdes(adev, &adev->ualink.npa_vm, false);
4973 	if (r) {
4974 		dev_dbg(adev->dev, "failed %d to update directories\n", r);
4975 		goto error_npa_mapping;
4976 	}
4977 
4978 	/* TODO: only wait the last fence, then flush TLB */
4979 	fence = dma_fence_get(adev->ualink.npa_vm.last_update);
4980 	if (fence) {
4981 		r = dma_fence_wait_timeout(fence, true, timeout);
4982 		dma_fence_put(fence);
4983 		if (r <= 0)
4984 			dev_dbg(adev->dev, "failed %d to dma fence wait\n", r);
4985 	}
4986 
4987 	amdgpu_ualink_flush_tlb(adev, TLB_FLUSH_HEAVYWEIGHT);
4988 
4989 	amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
4990 	return 0;
4991 
4992 error_npa_mapping:
4993 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
4994 		amdgpu_ualink_npa_free_va(adev, &remote->rptr_mm_node);
4995 	if (r)
4996 		dev_dbg(adev->dev, "failed %d to map NPA vm\n", r);
4997 
4998 out:
4999 	amdgpu_ualink_unreserve_npa_vm_and_bos(adev, &exec);
5000 
5001 	return r;
5002 }
5003 
5004 /**
5005  * amdgpu_ualink_sdma_entities_init - Initialize SDMA job scheduler entities
5006  * @adev: amdgpu device pointer
5007  *
5008  * Sets up SDMA job scheduler entities for remote interrupt and shootdown.
5009  * Each entity uses one SDMA scheduler/ring.
5010  *
5011  * Return: 0 on success, negative error code on failure
5012  */
5013 static int amdgpu_ualink_sdma_entities_init(struct amdgpu_device *adev)
5014 {
5015 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5016 	struct drm_gpu_scheduler *sched;
5017 	u32 accel_id;
5018 	int i = 0, r;
5019 
5020 	dev_dbg(adev->dev, "enter\n");
5021 
5022 	for_each_set_bit(accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX) {
5023 		sched = &adev->sdma.instance[accel_id % adev->sdma.num_instances].ring.sched;
5024 
5025 		r = drm_sched_entity_init(&remote->peer[accel_id].entity, DRM_SCHED_PRIORITY_HIGH,
5026 					  &sched, 1, NULL);
5027 		if (r)
5028 			goto out_free;
5029 		i++;
5030 	}
5031 
5032 	remote->use_lsdma = true;
5033 
5034 	dev_dbg(adev->dev, "exit\n");
5035 	return 0;
5036 
5037 out_free:
5038 	for_each_set_bit(accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX) {
5039 		if (i--)
5040 			drm_sched_entity_destroy(&remote->peer[accel_id].entity);
5041 		else
5042 			break;
5043 	}
5044 
5045 	return r;
5046 }
5047 
5048 static void amdgpu_ualink_sdma_entities_fini(struct amdgpu_device *adev)
5049 {
5050 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5051 	u32 accel_id;
5052 
5053 	dev_dbg(adev->dev, "enter\n");
5054 	for_each_set_bit(accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX)
5055 		drm_sched_entity_destroy(&remote->peer[accel_id].entity);
5056 	dev_dbg(adev->dev, "exit\n");
5057 }
5058 
5059 /**
5060  * amdgpu_ualink_gart_map - Allocate GART entry and map NPA address
5061  * @adev: amdgpu device pointer
5062  * @npages: Number of pages to map
5063  * @npa: NPA address to map
5064  * @mm_node: DRM memory manager node for GART allocation
5065  * @pte_flags: the GART mapping flags
5066  *
5067  * Allocates GART entries and sets up NPA address mapping without TTM BO.
5068  *
5069  * Return: 0 on success, negative error code on failure
5070  */
5071 static int amdgpu_ualink_gart_map(struct amdgpu_device *adev, u64 npages,
5072 				   u64 npa, struct drm_mm_node *mm_node,
5073 				   u64 pte_flags)
5074 {
5075 	struct ttm_resource_manager *man =
5076 				ttm_manager_type(&adev->mman.bdev, TTM_PL_TT);
5077 	struct amdgpu_gtt_mgr *mgr =
5078 				container_of(man, struct amdgpu_gtt_mgr, manager);
5079 	dma_addr_t *dma_addr;
5080 	int i, r;
5081 
5082 	dev_dbg(adev->dev, "npa 0x%llx npages 0x%llx\n", npa, npages);
5083 
5084 	if (npages > 1) {
5085 		dma_addr = kmalloc_array(npages, sizeof(*dma_addr), GFP_KERNEL);
5086 		if (!dma_addr)
5087 			return -ENOMEM;
5088 
5089 		for (i = 0; i < npages; i++)
5090 			dma_addr[i] = npa + i * AMDGPU_GPU_PAGE_SIZE;
5091 	} else {
5092 		dma_addr = (dma_addr_t *)&npa;
5093 	}
5094 
5095 	r = amdgpu_gtt_mgr_alloc_entries(mgr, mm_node, npages, DRM_MM_INSERT_BEST);
5096 	if (r)
5097 		goto out;
5098 	amdgpu_gart_bind(adev, mm_node->start << AMDGPU_GPU_PAGE_SHIFT, npages, dma_addr,
5099 			 pte_flags);
5100 
5101 out:
5102 	dev_dbg(adev->dev, "npa 0x%llx mapped to 0x%llx npages 0x%llx r=%d\n",
5103 		npa, mm_node->start << AMDGPU_GPU_PAGE_SHIFT, npages, r);
5104 
5105 	if (npages > 1)
5106 		kfree(dma_addr);
5107 	return r;
5108 }
5109 
5110 /**
5111  * amdgpu_ualink_gart_unmap - Unmap and free GART entry
5112  * @adev: amdgpu device pointer
5113  * @npages: Number of pages to unmap
5114  * @mm_node: DRM memory manager node for GART allocation
5115  *
5116  * Unbinds GART mapping and frees allocated entries.
5117  */
5118 static void amdgpu_ualink_gart_unmap(struct amdgpu_device *adev, u64 npages,
5119 				      struct drm_mm_node *mm_node)
5120 {
5121 	struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev, TTM_PL_TT);
5122 	struct amdgpu_gtt_mgr *mgr =
5123 				container_of(man, struct amdgpu_gtt_mgr, manager);
5124 
5125 	dev_dbg(adev->dev, "0x%llx npages 0x%llx\n", mm_node->start << AMDGPU_GPU_PAGE_SHIFT,
5126 		npages);
5127 
5128 	if (!drm_mm_node_allocated(mm_node))
5129 		return;
5130 	amdgpu_gart_unbind(adev, mm_node->start << AMDGPU_GPU_PAGE_SHIFT, npages);
5131 	amdgpu_gtt_mgr_free_entries(mgr, mm_node);
5132 }
5133 
5134 /**
5135  * amdgpu_ualink_metadata_fini - Clean up ualink metadata structures
5136  * @adev: amdgpu device pointer
5137  *
5138  * Unmaps NPA addresses and frees all allocated buffers for metadata,
5139  * ring buffers, and pointers.
5140  */
5141 static void amdgpu_ualink_metadata_fini(struct amdgpu_device *adev)
5142 {
5143 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5144 
5145 	dev_dbg(adev->dev, "accel_id %u\n", ualink_accel_id(adev));
5146 	amdgpu_bo_free_kernel(&remote->rptr_bo, &remote->rptr_gpu_addr,
5147 				      &remote->rptr_cpu_addr);
5148 	amdgpu_bo_free_kernel(&remote->ring_bo, &remote->rb_gpu_addr,
5149 			      &remote->rb_cpu_addr);
5150 	amdgpu_bo_free_kernel(&remote->metadata_bo, &remote->metadata_gpu_addr,
5151 			      &remote->metadata_cpu_addr);
5152 }
5153 
5154 /**
5155  * amdgpu_ualink_metadata_init - Initialize ualink metadata structures
5156  * @adev: amdgpu device pointer
5157  *
5158  * Allocates and initializes metadata structures, ring buffers, and write/read
5159  * pointers for multi-GPU ualink. Communicates with firmware to load metadata.
5160  *
5161  * Return: 0 on success, negative error code on failure
5162  */
5163 static int amdgpu_ualink_metadata_init(struct amdgpu_device *adev)
5164 {
5165 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5166 	struct amdgpu_ualink_metadata *metadata;
5167 	u32 size, rb_size, wptr_size, rptr_size, metadata_size;
5168 	u64 rb_gpu_addr, wptr_gpu_addr;
5169 	u32 status, accel_id;
5170 	int r;
5171 
5172 	bitmap_copy(remote->active_accel_bits,
5173 		    adev->ualink.info->vpod.active_accel_bits,
5174 		    AMDGPU_UALINK_ACCEL_MAX);
5175 	dev_dbg(adev->dev, "%d active accelerators config in vpod\n",
5176 		bitmap_weight(remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX));
5177 
5178 	/*
5179 	 * allocate metadata entries and ring buffer for all remote GPUs,
5180 	 * to get 2MB page ring buffer NPA mapping for remote access.
5181 	 */
5182 	remote->num_accel = AMDGPU_UALINK_ACCEL_MAX;
5183 
5184 	status = adev->ualink.msg_ctl->check_status(adev);
5185 	if (status != AMDGPU_NHT_FW_ST_PREINIT &&
5186 	    status != AMDGPU_NHT_FW_ST_HALT) {
5187 		dev_dbg(adev->dev, "fw status 0x%x not preinit or halt\n", status);
5188 		return -ENODEV;
5189 	}
5190 
5191 	dev_dbg(adev->dev, "accel_id %u addr_mode %d fw status 0x%x\n",
5192 		ualink_accel_id(adev), ualink_addr_mode(adev), status);
5193 
5194 	/* Alloc metadata structure for all GPUs */
5195 	metadata_size = sizeof(struct amdgpu_ualink_metadata) * AMDGPU_UALINK_ACCEL_MAX;
5196 	metadata_size = AMDGPU_GPU_PAGE_ALIGN(metadata_size);
5197 
5198 	dev_dbg(adev->dev, "metadata size 0x%x\n", metadata_size);
5199 
5200 	/* pinned system memory */
5201 	r = amdgpu_bo_create_kernel(adev, metadata_size, PAGE_SIZE,
5202 				    AMDGPU_GEM_DOMAIN_GTT,
5203 				    &remote->metadata_bo, &remote->metadata_gpu_addr,
5204 				    &remote->metadata_cpu_addr);
5205 	if (r)
5206 		goto out;
5207 
5208 	memset(remote->metadata_cpu_addr, 0, metadata_size);
5209 	metadata = remote->metadata_cpu_addr;
5210 
5211 	dev_dbg(adev->dev, "metadata gpu address 0x%llx\n", remote->metadata_gpu_addr);
5212 
5213 	/* Allocate ring buffers, wptr for remote interrupt and shootdown */
5214 	rb_size = AMDGPU_GPU_PAGE_ALIGN(2 * AMDGPU_UALINK_RB_SIZE);
5215 	wptr_size = ualink_wptr_size(adev);
5216 	size = (rb_size + wptr_size) * remote->num_accel;
5217 	size = AMDGPU_GPU_PAGE_ALIGN(size);
5218 
5219 	dev_dbg(adev->dev, "rb_size 0x%x wptr_size 0x%x total alloc size 0x%x\n",
5220 		rb_size, wptr_size, size);
5221 
5222 	/* pinned VRAM */
5223 	r = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
5224 				    AMDGPU_GEM_DOMAIN_VRAM,
5225 				    &remote->ring_bo,
5226 				    &remote->rb_gpu_addr,
5227 				    &remote->rb_cpu_addr);
5228 	if (r)
5229 		goto out;
5230 
5231 	memset(remote->rb_cpu_addr, 0, size);
5232 
5233 	dev_dbg(adev->dev, "rb gpu addr 0x%llx cpu addr 0x%p vram_start 0x%llx vram_base 0x%llx\n",
5234 		remote->rb_gpu_addr, remote->rb_cpu_addr, adev->gmc.vram_start,
5235 		adev->vm_manager.vram_base_offset);
5236 
5237 	/*
5238 	 * address aliasing mode, shared wptr pagee left is not enough for wb data,
5239 	 * wb status and rptr, alloc another BO, and then alloc npa address and map
5240 	 * to npa vm, for remote to access.
5241 	 *
5242 	 * No gart mapping required for wb data, status and rptr because this is
5243 	 * updated by firmware.
5244 	 */
5245 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS) {
5246 		rptr_size = AMDGPU_GPU_PAGE_ALIGN(ualink_wb_size(adev) * remote->num_accel);
5247 		dev_dbg(adev->dev, "source aliasing mode rptr_size 0x%x\n", rptr_size);
5248 
5249 		/* pinned VRAM */
5250 		r = amdgpu_bo_create_kernel(adev, rptr_size, PAGE_SIZE,
5251 					    AMDGPU_GEM_DOMAIN_VRAM,
5252 					    &remote->rptr_bo,
5253 					    &remote->rptr_gpu_addr,
5254 					    &remote->rptr_cpu_addr);
5255 		if (r)
5256 			goto out;
5257 
5258 		memset(remote->rptr_cpu_addr, 0, rptr_size);
5259 
5260 		dev_dbg(adev->dev, "source aliasing rptr gpu addr 0x%llx cpu addr 0x%p\n",
5261 			remote->rptr_gpu_addr, remote->rptr_cpu_addr);
5262 	}
5263 
5264 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_ALIAS)
5265 		wptr_gpu_addr = remote->rb_gpu_addr + rb_size * ualink_accel_id(adev);
5266 
5267 	for_each_set_bit(accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX) {
5268 		dev_dbg(adev->dev, "init for accel_id %u\n", accel_id);
5269 
5270 		if (accel_id == ualink_accel_id(adev))
5271 			continue;
5272 
5273 		rb_gpu_addr = remote->rb_gpu_addr + rb_size * accel_id;
5274 
5275 		if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT) {
5276 			wptr_gpu_addr = remote->rb_gpu_addr + rb_size * remote->num_accel;
5277 			wptr_gpu_addr += wptr_size * accel_id;
5278 		}
5279 
5280 		metadata[accel_id].header = AMDGPU_UALINK_METADATA_HEADER;
5281 		metadata[accel_id].rb_size = fls(AMDGPU_UALINK_RB_SIZE / 64) - 1;
5282 
5283 		/*
5284 		 * remote shootdown type is 0, remote command type is 1
5285 		 * with 2MB ring buffer mapping, remote shootdown ring NPA is before interrupt
5286 		 */
5287 		metadata[accel_id].ri_rb = rb_gpu_addr + AMDGPU_UALINK_RB_SIZE;
5288 		metadata[accel_id].tlb_inv_rb = rb_gpu_addr;
5289 
5290 		metadata[accel_id].tailptr_ri = wptr_gpu_addr +
5291 						ualink_wptr_offset(adev, accel_id);
5292 		metadata[accel_id].tailptr_tlb_inv = wptr_gpu_addr +
5293 						     ualink_tlb_wptr_offset(adev, accel_id);
5294 
5295 		dev_dbg(adev->dev, "init from accel_id %u to accel_id %u, rb_size 0x%x\n",
5296 			accel_id, ualink_accel_id(adev), metadata[accel_id].rb_size);
5297 		dev_dbg(adev->dev, "rb 0x%llx tlb rb 0x%llx\n",
5298 			metadata[accel_id].ri_rb, metadata[accel_id].tlb_inv_rb);
5299 		dev_dbg(adev->dev, "rb wptr at 0x%llx tlb wptr at 0x%llx\n",
5300 			metadata[accel_id].tailptr_ri, metadata[accel_id].tailptr_tlb_inv);
5301 	}
5302 
5303 	r = adev->ualink.msg_ctl->send_metadata(adev,
5304 						    remote->metadata_gpu_addr,
5305 						    AMDGPU_UALINK_ACCEL_MAX << 8);
5306 
5307 out:
5308 	if (r)
5309 		amdgpu_ualink_metadata_fini(adev);
5310 
5311 	dev_dbg(adev->dev, "ret 0x%x\n", r);
5312 	return r;
5313 }
5314 
5315 /*
5316  * nHT Firmware Error code
5317  *
5318  * Success				0x0
5319  * FIFO overflow			0x1
5320  * Invalid RB command			0x2
5321  * Timeout				0x3
5322  * Invalid metadata entry		0x4
5323  * RB overflow				0x5
5324  * Invalid wptr address			0x6
5325  * Interrupt cookie send failure	0x7
5326  * Invalid RB address			0x8
5327  * Invalid writeback address		0x9
5328  */
5329 static void amdgpu_ualink_remote_error(struct amdgpu_device *adev, u32 status)
5330 {
5331 	const char *fw_err_code_msg[] = {
5332 		"Unknown FW error status",
5333 		"FIFO overflow",		/* error code 1 */
5334 		"Invalid RB command",
5335 		"Timeout",
5336 		"Invalid metadata entry",
5337 		"RB overflow",
5338 		"Invalid wptr address",
5339 		"Interrupt cookie send failure",
5340 		"Invalid RB address",
5341 		"Invalid writeback address"	/* error code 9 */
5342 		};
5343 
5344 	if (status >= ARRAY_SIZE(fw_err_code_msg))
5345 		status = 0;
5346 
5347 	dev_err(adev->dev, "remote error %s\n", fw_err_code_msg[status]);
5348 	return;
5349 }
5350 
5351 /**
5352  * amdgpu_ualink_remote_wait_timeout - Wait for remote operation completion
5353  * @remote_accel_id: remote accelator id to wait for reply
5354  * @adev: amdgpu device pointer
5355  * @wb_cpu: CPU virtual address of writeback buffer
5356  * @seq: Sequence number to wait for
5357  *
5358  * Polls the writeback buffer waiting for the sequence number to reach or
5359  * exceed the expected value. The writeback buffer contains status and data
5360  * fields updated by firmware to indicate completion and error conditions.
5361  *
5362  * Return: 0 on success
5363  *         -ETIME on timeout
5364  *         -ECOMM on firmware return error status
5365  */
5366 static long amdgpu_ualink_remote_wait_timeout(struct amdgpu_device *adev,
5367 					      u32 remote_accel_id,
5368 					      struct amdgpu_ualink_wb *wb_cpu,
5369 					      u32 seq)
5370 {
5371 	/* 2 seconds timeout, long enough for FW to reply */
5372 	ktime_t timeout = ktime_add_us(ktime_get(), 2 * USEC_PER_SEC);
5373 	u32 status, data;
5374 	u64 rptr;
5375 
5376 	while (true) {
5377 		data = READ_ONCE(wb_cpu->data);
5378 		if (data >= seq) {
5379 			status = READ_ONCE(wb_cpu->status);
5380 			rptr = READ_ONCE(wb_cpu->rptr);
5381 			break;
5382 		}
5383 
5384 		if (ktime_after(ktime_get(), timeout)) {
5385 			dev_dbg(adev->dev, "remote %d wait timeout\n", remote_accel_id);
5386 			return -ETIME;
5387 		}
5388 
5389 		usleep_range(10, 50);
5390 	}
5391 
5392 	if (status) {
5393 		dev_dbg(adev->dev, "remote %u status 0x%x wb data 0x%x seq 0x%x rptr 0x%llx\n",
5394 			remote_accel_id, status, data, seq, rptr);
5395 
5396 		amdgpu_ualink_remote_error(adev, status);
5397 		return -ECOMM;
5398 	}
5399 
5400 	dev_dbg(adev->dev, "remote %u succeed seq 0x%x wb data 0x%x rptr 0x%llx\n",
5401 		remote_accel_id, seq, data, rptr);
5402 	return 0;
5403 }
5404 
5405 #define AMDGPU_UALINK_REMOTE_OP_TLB_INV		0x1
5406 #define AMDGPU_UALINK_REMOTE_OP_INT		0x2
5407 #define AMDGPU_UALINK_REMOTE_OP_UPDATE_WB	0x3
5408 
5409 static void amdgpu_ualink_emit_shootdown(u32 **cpu_addr_p, u32 wb_data,
5410 					 u32 dw0,  u32 dw1, u32 dw2, u32 dw3)
5411 {
5412 	u64 addr = (((u64)dw1 << 32) | (u64)dw2) << AMDGPU_GPU_PAGE_SHIFT;
5413 	u32 *cpu_addr = *cpu_addr_p;
5414 	u32 flush_type = dw0;
5415 	u32 size_in_pages = dw3;
5416 	u32 cmd;
5417 
5418 	cmd = AMDGPU_UALINK_REMOTE_OP_TLB_INV;
5419 	cmd |= 1 << 28;	/* headptr update */
5420 	cmd |= 1 << 29;	/* wb enable */
5421 
5422 	*cpu_addr++ = cmd;
5423 	*cpu_addr++ = wb_data;
5424 	*cpu_addr++ = 0;
5425 	*cpu_addr++ = 0;
5426 	*cpu_addr++ = 0;
5427 	*cpu_addr++ = 0;
5428 	*cpu_addr++ = 0; /* metadata */
5429 	*cpu_addr++ = 0; /* metadata */
5430 
5431 	pr_debug("NPA addr 0x%llx npages 0x%x\n", addr, size_in_pages);
5432 
5433 	/* Always shootdown everything with full address size s-field coding */
5434 	addr = GENMASK_ULL(51, 11);
5435 
5436 	*cpu_addr++ = lower_32_bits(addr) | flush_type;
5437 	*cpu_addr++ = upper_32_bits(addr);
5438 
5439 	*cpu_addr++ = 0;
5440 	*cpu_addr++ = 0;
5441 	*cpu_addr++ = 0;
5442 	*cpu_addr++ = 0;
5443 	*cpu_addr++ = 0;
5444 	*cpu_addr++ = 0;
5445 	*cpu_addr_p = cpu_addr;
5446 }
5447 
5448 static void amdgpu_ualink_emit_interrupt(u32 **cpu_addr_p, u32 wb_data,
5449 					 u32 dw0, u32 dw1, u32 dw2, u32 dw3)
5450 {
5451 	u32 *cpu_addr = *cpu_addr_p;
5452 	u32 cmd;
5453 
5454 	cmd = AMDGPU_UALINK_REMOTE_OP_INT;
5455 	cmd |= 1 << 28;	/* headptr_update */
5456 	cmd |= 1 << 29; /* wb enable */
5457 
5458 	*cpu_addr++ = cmd;
5459 	*cpu_addr++ = wb_data;
5460 	*cpu_addr++ = 0;
5461 	*cpu_addr++ = 0;
5462 	*cpu_addr++ = 0;
5463 	*cpu_addr++ = 0;
5464 	*cpu_addr++ = 0; /* metadata */
5465 	*cpu_addr++ = 0; /* metadata */
5466 	/* updated by f/w, overwrite PASID with GPU ID */
5467 	*cpu_addr++ = 0;
5468 	*cpu_addr++ = 0;
5469 	*cpu_addr++ = 0;
5470 	*cpu_addr++ = 0;
5471 	/* IH ContextID 4 dwords */
5472 	*cpu_addr++ = dw0;
5473 	*cpu_addr++ = dw1;
5474 	*cpu_addr++ = dw2;
5475 	*cpu_addr++ = dw3;
5476 	*cpu_addr_p = cpu_addr;
5477 }
5478 
5479 static void amdgpu_ualink_emit_update_wb_addr(u32 **cpu_addr_p, u32 wb_data,
5480 					      u32 dw0, u32 dw1, u32 dw2, u32 dw3)
5481 {
5482 	u32 *cpu_addr = *cpu_addr_p;
5483 	u32 cmd;
5484 
5485 	cmd = AMDGPU_UALINK_REMOTE_OP_UPDATE_WB;
5486 	cmd |= 1 << 28;	/* headptr update */
5487 	cmd |= 1 << 29;	/* wb enable */
5488 
5489 	*cpu_addr++ = cmd;
5490 	*cpu_addr++ = wb_data;
5491 	*cpu_addr++ = dw1 & 0xFFFFFFFC;	/* lower32 wb_npa */
5492 	*cpu_addr++ = dw0 & 0xFFFFF;	/* upper32 wb_npa */
5493 	*cpu_addr++ = 0;
5494 	*cpu_addr++ = 0;
5495 	*cpu_addr++ = 0; /* metadata */
5496 	*cpu_addr++ = 0; /* metadata */
5497 	*cpu_addr++ = 0;
5498 	*cpu_addr++ = 0;
5499 	*cpu_addr++ = 0;
5500 	*cpu_addr++ = 0;
5501 	*cpu_addr++ = 0;
5502 	*cpu_addr++ = 0;
5503 	*cpu_addr++ = 0;
5504 	*cpu_addr++ = 0;
5505 	*cpu_addr_p = cpu_addr;
5506 }
5507 
5508 /*
5509  * Function proto to generate packet using above different emit_ functions
5510  */
5511 typedef void (*ualink_emit_packet)(u32 **cpu_addr_p, u32 wb, u32 dw0,
5512 				   u32 dw1, u32 dw2, u32 dw3);
5513 
5514 static int amdgpu_ualink_send_command(struct amdgpu_device *adev,
5515 				      u32 remote_accel_id,
5516 				      struct amdgpu_ualink_ring *ring,
5517 				      struct amdgpu_ualink_wb *wb_cpu,
5518 				      ualink_emit_packet emit_func,
5519 				      u32 dw0, u32 dw1, u32 dw2, u32 dw3)
5520 {
5521 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5522 	struct amdgpu_ualink_peer *peer;
5523 	struct amdgpu_ring *sdma_ring;
5524 	struct dma_fence *fence;
5525 	struct amdgpu_job *job;
5526 	struct amdgpu_ib *ib;
5527 	u32 seq, ndw, ndw_copy_cmd, rem;
5528 	u64 doorbell_npa_gart;
5529 	u32 *src_cpu;
5530 	u64 src;
5531 	int r;
5532 
5533 	/* Refuse sends unless active */
5534 	if (adev->ualink.info->accel_state != AMDGPU_UALINK_ACCEL_STATE_ACTIVE)
5535 		return -ESHUTDOWN;
5536 
5537 	peer = &remote->peer[remote_accel_id];
5538 
5539 	/*
5540 	 * 3 sdma copy commands: write data to ring buffer, update wptr, ring doorbell
5541 	 *
5542 	 * insert 2 NOP commands to break SDMA back-to-back copy command overlap, to
5543 	 * ensure the ordering of 3 sdma copy commands execution.
5544 	 */
5545 
5546 	/* buffer after sdma commands, starting at 8 dwords boundary */
5547 	ndw_copy_cmd = ALIGN(3 * adev->mman.buffer_funcs->copy_num_dw + 2, 8);
5548 
5549 	 /* remote command 16 dwords, wptr 2 dwords, doorbell 1 dword */
5550 	ndw = ndw_copy_cmd + 16 + 2 + 1;
5551 	r = amdgpu_job_alloc_with_ib(adev, &peer->entity, AMDGPU_FENCE_OWNER_VM,
5552 				     ndw * 4, AMDGPU_IB_POOL_IMMEDIATE,
5553 				     AMDGPU_KERNEL_JOB_ID_TTM_COPY_BUFFER, &job);
5554 	if (r)
5555 		return r;
5556 
5557 	mutex_lock(&peer->lock);
5558 
5559 	ring->rptr = READ_ONCE(wb_cpu->rptr);
5560 
5561 	if (WARN_ON_ONCE(ring->rptr > ring->wptr)) {
5562 		dev_err(adev->dev, "accel_id %u ring overflow wptr 0x%llx rptr 0x%llx\n",
5563 			remote_accel_id, ring->wptr, ring->rptr);
5564 		r = -EFAULT;
5565 		goto unlock_free;
5566 	}
5567 
5568 	if ((ring->wptr + 1 - ring->rptr) >= ring->rb_size) {
5569 		dev_err(adev->dev, "accel_id %u command ring full wptr 0x%llx rptr 0x%llx\n",
5570 			remote_accel_id, ring->wptr, ring->rptr);
5571 		r = -ENOSPC;
5572 		goto unlock_free;
5573 	}
5574 
5575 	ib = &job->ibs[0];
5576 	src = ib->gpu_addr + ndw_copy_cmd * 4;
5577 	src_cpu = ib->ptr + ndw_copy_cmd;
5578 
5579 	seq = ++ring->seq;
5580 
5581 	div_u64_rem(ring->wptr, ring->rb_size, &rem);
5582 	dev_dbg(adev->dev, "src 0x%llx to npa gart rb 0x%llx wptr 0x%llx doorbell 0x%llx seq 0x%x\n",
5583 		src, ring->rb_npa_gart + rem * 64,
5584 		ring->wptr_npa_gart, ring->doorbell_npa_gart, seq);
5585 
5586 	dev_dbg(adev->dev, "ring wptr 0x%llx rptr 0x%llx\n", ring->wptr, ring->rptr);
5587 
5588 	/* remote command packet */
5589 	emit_func(&src_cpu, seq, dw0, dw1, dw2, dw3);
5590 
5591 	/* wptr value */
5592 	*src_cpu++ = lower_32_bits(ring->wptr + 1);
5593 	*src_cpu++ = upper_32_bits(ring->wptr + 1);
5594 
5595 	/* doorbell value */
5596 	*src_cpu++ = lower_32_bits(ring->wptr + 1);
5597 
5598 	/*
5599 	 * Add an offset to the doorbell address that cycles through different
5600 	 * values of bit 11:8 to use different DXS ports.
5601 	 */
5602 	peer->dxs_port = (peer->dxs_port + 1) & 0xF;
5603 	doorbell_npa_gart = ring->doorbell_npa_gart | (peer->dxs_port << 8);
5604 	dev_dbg(adev->dev, "dxs_port 0x%x, doorbell_npa_gart 0x%llx -> 0x%llx\n",
5605 		peer->dxs_port, ring->doorbell_npa_gart, doorbell_npa_gart);
5606 
5607 	dev_dbg(adev->dev, "use %s\n", remote->use_lsdma ? "lsdma" : "sdma");
5608 
5609 	if (remote->use_lsdma) {
5610 		div_u64_rem(ring->wptr, ring->rb_size, &rem);
5611 		r = amdgpu_lsdma_copy_mem(adev, src,
5612 					  ring->rb_npa_gart + rem * 64,
5613 					  64);
5614 		if (!r)
5615 			r = amdgpu_lsdma_copy_mem(adev, src + 64,
5616 						  ring->wptr_npa_gart, 8);
5617 		if (!r)
5618 			r = amdgpu_lsdma_copy_mem(adev, src + 72,
5619 						  doorbell_npa_gart, 4);
5620 
5621 		amdgpu_job_free(job);
5622 
5623 		/* Copy failed: command never reached the remote, so no
5624 		 * writeback will arrive. Return now instead of polling the
5625 		 * completion for the full remote timeout.
5626 		 */
5627 		if (r) {
5628 			dev_dbg(adev->dev,
5629 				"remote %u lsdma copy failed (r %d), skip completion wait\n",
5630 				remote_accel_id, r);
5631 			mutex_unlock(&peer->lock);
5632 			return r;
5633 		}
5634 
5635 		goto out_wait_complete;
5636         }
5637 
5638 	sdma_ring = &adev->sdma.instance[0].ring;
5639 
5640 	/*
5641 	 * SDMA commands copy from ib to NPA, insert NOPs to ensure SDMA copy commands
5642 	 * execution doesn't overlap, doorbell update is after data and wptr update
5643 	 * finished.
5644 	 */
5645 	div_u64_rem(ring->wptr, ring->rb_size, &rem);
5646 	amdgpu_emit_copy_buffer(adev, ib, src,
5647 				ring->rb_npa_gart + rem * 64,
5648 				64, 0);
5649 
5650 	ib->ptr[ib->length_dw++] = sdma_ring->funcs->nop;
5651 
5652 	amdgpu_emit_copy_buffer(adev, ib, src + 64, ring->wptr_npa_gart, 8, 0);
5653 
5654 	ib->ptr[ib->length_dw++] = sdma_ring->funcs->nop;
5655 
5656 	amdgpu_emit_copy_buffer(adev, ib, src + 72, doorbell_npa_gart, 4, 0);
5657 
5658 	amdgpu_ring_pad_ib(sdma_ring, ib);
5659 	WARN_ON(ib->length_dw > ndw_copy_cmd);
5660 
5661 	fence = amdgpu_job_submit(job);
5662 	r = dma_fence_wait_timeout(fence, false, AMDGPU_FENCE_JIFFIES_TIMEOUT);
5663 	dma_fence_put(fence);
5664 	if (r <= 0) {
5665 		dev_dbg(adev->dev, "remote %u sdma fence wait return r %d\n",
5666 			remote_accel_id, r);
5667 
5668 		if (r == 0)
5669 			r = -ETIME;
5670 
5671 		mutex_unlock(&peer->lock);
5672 		return r;
5673 	}
5674 
5675 out_wait_complete:
5676 	/*
5677 	 * poll remote completion writeback data
5678 	 */
5679 	r = amdgpu_ualink_remote_wait_timeout(adev, remote_accel_id, wb_cpu, seq);
5680 
5681 	/* increase local copy ring wptr, only if FW not timeout */
5682 	if (r != -ETIME)
5683 		ring->wptr++;
5684 
5685 	/*
5686 	 * Release ring lock after the remote FW handle command completes to
5687 	 * prevent race conditions.
5688 	 */
5689 	mutex_unlock(&peer->lock);
5690 	return r;
5691 
5692 
5693 unlock_free:
5694 	mutex_unlock(&peer->lock);
5695 	amdgpu_job_free(job);
5696 	dev_dbg(adev->dev, "ret r = %d\n", r);
5697 	return r;
5698 }
5699 
5700 static void amdgpu_ualink_get_wb_addr(struct amdgpu_device *adev,
5701 				      u32 remote_accel_id,
5702 				      struct amdgpu_ualink_wb **wb_cpu,
5703 				      u64 *wb_npa, u32 type)
5704 {
5705 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5706 	u32 accel_id = ualink_accel_id(adev);
5707 	u32 rb_size = AMDGPU_GPU_PAGE_ALIGN(2 * AMDGPU_UALINK_RB_SIZE);
5708 	uintptr_t wb;
5709 	u64 npa;
5710 	u32 offset = 0;
5711 
5712 	if (ualink_addr_mode(adev) == AMDGPU_UALINK_ADDR_MODE_SOURCE_IDENT) {
5713 		wb = (uintptr_t)remote->rb_cpu_addr + rb_size * remote->num_accel;
5714 		npa = amdgpu_ualink_npa_addr(adev, RB_TYPE_TAILPTR,
5715 					     remote_accel_id, accel_id);
5716 	} else {
5717 		wb = (uintptr_t)remote->rptr_cpu_addr;
5718 		npa = remote->rptr_npa;
5719 		npa |= (u64)accel_id << AMDGPU_UALINK_GART_NPA_ADDR_GPUID_SHIFT;
5720 	}
5721 
5722 	if (type == RB_TYPE_TLB_INV)
5723 		offset = ualink_tlb_wb_offset(adev, remote_accel_id);
5724 	else if (type == RB_TYPE_REMOTE_INTERRUPT)
5725 		offset = ualink_wb_offset(adev, remote_accel_id);
5726 
5727 	*wb_cpu = (struct amdgpu_ualink_wb *)(wb + offset);
5728 	if (wb_npa)
5729 		*wb_npa = npa + offset;
5730 
5731 	dev_dbg(adev->dev, "source %d remote %d wb npa 0x%llx\n", accel_id,
5732 		remote_accel_id, npa + offset);
5733 }
5734 
5735 static int amdgpu_ualink_update_wb_address(struct amdgpu_device *adev,
5736 					   u32 remote_accel_id, u32 ring_type)
5737 {
5738 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5739 	struct amdgpu_ualink_peer *peer;
5740 	struct amdgpu_ualink_ring *ring;
5741 	struct amdgpu_ualink_wb *wb_cpu;
5742 	u64 wb_npa;
5743 	int r;
5744 
5745 	peer = &remote->peer[remote_accel_id];
5746 	if (ring_type == RB_TYPE_REMOTE_INTERRUPT)
5747 		ring = &peer->interrupt;
5748 	else if (ring_type == RB_TYPE_TLB_INV)
5749 		ring = &peer->shootdown;
5750 	else
5751 		return -EINVAL;
5752 
5753 	amdgpu_ualink_get_wb_addr(adev, remote_accel_id, &wb_cpu, &wb_npa,
5754 				  ring_type);
5755 
5756 	r = amdgpu_ualink_send_command(adev, remote_accel_id, ring, wb_cpu,
5757 				       amdgpu_ualink_emit_update_wb_addr,
5758 				       upper_32_bits(wb_npa),
5759 				       lower_32_bits(wb_npa),
5760 				       0, 0);
5761 	if (!r) {
5762 		ring->wb_cpu = wb_cpu;
5763 		ring->ready = true;
5764 	}
5765 	return r;
5766 }
5767 
5768 /**
5769  * amdgpu_ualink_remote_shootdown - Send a remote TLB invalidation request
5770  * @adev: amdgpu device pointer
5771  * @remote_accel_id: accelerator ID of the remote GPU to shootdown
5772  * @addr: page-aligned address to invalidate
5773  * @size_in_pages: number of pages to invalidate, 0 to invalidate entire TLB
5774  * @flush_type: type of TLB flush to perform
5775  *
5776  * Sends a remote TLB shootdown command to the specified peer GPU via the
5777  * UALink ring buffer. The address and size are translated using the S-field
5778  * encoding before being written to the ring.
5779  *
5780  * Return: 0 on success, negative error code on failure
5781  */
5782 static int amdgpu_ualink_remote_shootdown(struct amdgpu_device *adev,
5783 				   u32 remote_accel_id, u64 addr,
5784 				   u32 size_in_pages, u32 flush_type)
5785 {
5786 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5787 	struct amdgpu_ualink_peer *peer;
5788 	struct amdgpu_ualink_ring *ring;
5789 	int r;
5790 
5791 	dev_dbg(adev->dev, "skip remote shootdown to remote_accel_id %u\n",
5792 		remote_accel_id);
5793 	return 0;
5794 
5795 	peer = &remote->peer[remote_accel_id];
5796 	ring = &peer->shootdown;
5797 	if (!ring->ready) {
5798 		dev_dbg(adev->dev, "accel_id %u ring not ready\n", remote_accel_id);
5799 		r = amdgpu_ualink_update_wb_address(adev, remote_accel_id,
5800 						    RB_TYPE_TLB_INV);
5801 		if (r)
5802 			return r;
5803 	}
5804 
5805 	r = amdgpu_ualink_send_command(adev, remote_accel_id, ring, ring->wb_cpu,
5806 				       amdgpu_ualink_emit_shootdown,
5807 				       flush_type, upper_32_bits(addr),
5808 				       lower_32_bits(addr), size_in_pages);
5809 	return r;
5810 }
5811 
5812 /**
5813  * amdgpu_ualink_remote_interrupt - Send a remote interrupt to a peer GPU
5814  * @adev: amdgpu device pointer
5815  * @remote_accel_id: accelerator ID of the remote GPU to interrupt
5816  * @dw0: IH context ID dword 0
5817  * @dw1: IH context ID dword 1
5818  * @dw2: IH context ID dword 2
5819  * @dw3: IH context ID dword 3
5820  *
5821  * Sends a remote interrupt command to the specified peer GPU via the
5822  * UALink ring buffer. The four context ID dwords are delivered to the
5823  * remote GPU's interrupt handler.
5824  *
5825  * Return: 0 on success, negative error code on failure
5826  */
5827 static int amdgpu_ualink_remote_interrupt(struct amdgpu_device *adev,
5828 				   u32 remote_accel_id, u32 dw0, u32 dw1,
5829 				   u32 dw2, u32 dw3)
5830 {
5831 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5832 	struct amdgpu_ualink_peer *peer;
5833 	struct amdgpu_ualink_ring *ring;
5834 	int r;
5835 
5836 	peer = &remote->peer[remote_accel_id];
5837 	ring = &peer->interrupt;
5838 	if (!ring->ready) {
5839 		dev_dbg(adev->dev, "accel_id %u ring not ready\n", remote_accel_id);
5840 		r = amdgpu_ualink_update_wb_address(adev, remote_accel_id,
5841 						    RB_TYPE_REMOTE_INTERRUPT);
5842 		if (r)
5843 			return r;
5844 	}
5845 
5846 	r = amdgpu_ualink_send_command(adev, remote_accel_id, ring, ring->wb_cpu,
5847 				       amdgpu_ualink_emit_interrupt,
5848 				       dw0, dw1, dw2, dw3);
5849 	return r;
5850 }
5851 
5852 /**
5853  * amdgpu_ualink_peer_remote_init - Initialize remote peer GPU connections
5854  * @adev: amdgpu device pointer
5855  *
5856  * Sets up ring buffers, GART mappings, and control structures for
5857  * communicating with remote GPUs in the fabric.
5858  *
5859  * Return: 0 on success, negative error code on failure
5860  */
5861 static int amdgpu_ualink_peer_remote_init(struct amdgpu_device *adev)
5862 {
5863 	u32 rb_pages = AMDGPU_UALINK_RB_SIZE >> AMDGPU_GPU_PAGE_SHIFT;
5864 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5865 	struct amdgpu_bo *bo = remote->ring_bo;
5866 	struct amdgpu_ualink_peer *peer;
5867 	struct amdgpu_ualink_ring *interrupt;
5868 	struct amdgpu_ualink_ring *shootdown;
5869 	u32 src_accel_id = ualink_accel_id(adev);
5870 	u32 dst_accel_id;
5871 	u64 npa, flags;
5872 	int r = 0;
5873 
5874 	/* NPA mapping PTE flags VSCT = 0011 */
5875 	flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, bo->tbo.resource);
5876 	flags |= AMDGPU_PTE_SNOOPED | AMDGPU_PTE_PRT_GFX12 | AMDGPU_PTE_BUS_ATOMICS;
5877 	flags &= ~AMDGPU_PTE_VALID;
5878 	/* PTE.X=0 turn off RPC checks for RBs, wptr and doorbell NPA address */
5879 	flags &= ~AMDGPU_PTE_EXECUTABLE;
5880 
5881 	dev_dbg(adev->dev, "src_accel_id %u gart mapping flags 0x%llx\n",
5882 		src_accel_id, flags);
5883 
5884 	for_each_set_bit(dst_accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX) {
5885 		if (dst_accel_id == src_accel_id)
5886 			continue;
5887 
5888 		dev_dbg(adev->dev, "peer_remote to dst_accel_id %u\n", dst_accel_id);
5889 
5890 		peer = &remote->peer[dst_accel_id];
5891 		mutex_init(&peer->lock);
5892 
5893 		interrupt = &peer->interrupt;
5894 		shootdown = &peer->shootdown;
5895 
5896 		/* ring buffer npa gart mapping */
5897 		npa = amdgpu_ualink_gart_npa_addr(adev, RB_TYPE_REMOTE_INTERRUPT,
5898 						   src_accel_id, dst_accel_id);
5899 		r = amdgpu_ualink_gart_map(adev, rb_pages, npa, &interrupt->mm_node_rb, flags);
5900 		if (r)
5901 			break;
5902 		interrupt->rb_npa_gart = adev->gmc.gart_start +
5903 					 (interrupt->mm_node_rb.start << AMDGPU_GPU_PAGE_SHIFT);
5904 
5905 		dev_dbg(adev->dev, "rb npa 0x%llx mapped on gart 0x%llx\n",
5906 			npa, interrupt->rb_npa_gart);
5907 
5908 		/* tlb invalidate ring buffer npa gart mapping */
5909 		npa = amdgpu_ualink_gart_npa_addr(adev, RB_TYPE_TLB_INV, src_accel_id,
5910 						  dst_accel_id);
5911 		r = amdgpu_ualink_gart_map(adev, rb_pages, npa, &shootdown->mm_node_rb, flags);
5912 		if (r)
5913 			break;
5914 		shootdown->rb_npa_gart = adev->gmc.gart_start +
5915 					 (shootdown->mm_node_rb.start << AMDGPU_GPU_PAGE_SHIFT);
5916 
5917 		dev_dbg(adev->dev, "tlb rb npa 0x%llx mapped on gart 0x%llx\n",
5918 			npa, shootdown->rb_npa_gart);
5919 
5920 		/* wptr npa gart mapping */
5921 		npa = amdgpu_ualink_gart_npa_addr(adev, RB_TYPE_TAILPTR, src_accel_id,
5922 						  dst_accel_id);
5923 		r = amdgpu_ualink_gart_map(adev, 1, npa, &interrupt->mm_node_wptr, flags);
5924 		if (r)
5925 			break;
5926 
5927 		interrupt->wptr_npa_gart = adev->gmc.gart_start +
5928 					   (interrupt->mm_node_wptr.start << AMDGPU_GPU_PAGE_SHIFT)
5929 					    + ualink_wptr_offset(adev, src_accel_id);
5930 		shootdown->wptr_npa_gart = adev->gmc.gart_start +
5931 					   (interrupt->mm_node_wptr.start << AMDGPU_GPU_PAGE_SHIFT)
5932 					    + ualink_tlb_wptr_offset(adev, src_accel_id);
5933 
5934 		dev_dbg(adev->dev, "rb wptr npa 0x%llx on gart 0x%llx, tlb wptr on gart 0x%llx\n",
5935 			npa, interrupt->wptr_npa_gart, shootdown->wptr_npa_gart);
5936 
5937 		/*
5938 		 * doorbell npa gart mapping, doorbell NPA address coding
5939 		 *
5940 		 * ReqAddr[51:40] = 0xFFF
5941 		 * ReqAddr[39:30] = GPU accel_id
5942 		 * ReqAddr[29:12] = 18'h00000
5943 		 * ReqAddr[11:8]  = Random value
5944 		 * ReqAddr[7:6]   = PMI Index
5945 		 *     0 - PMI0 Remote Interrupt
5946 		 *     1 - PMI1 Remote TLB Shootdown
5947 		 * ReqAddr[5:0]   = 6'h0
5948 		 */
5949 		npa = 0xFFFULL << 40 | (u64)dst_accel_id << 30;
5950 		r = amdgpu_ualink_gart_map(adev, 1, npa, &interrupt->mm_node_doorbell, flags);
5951 		if (r)
5952 			break;
5953 
5954 		interrupt->doorbell_npa_gart = adev->gmc.gart_start +
5955 			(interrupt->mm_node_doorbell.start << AMDGPU_GPU_PAGE_SHIFT);
5956 
5957 		dev_dbg(adev->dev, "rb doorbell npa 0x%llx mapped on gart 0x%llx\n",
5958 			npa, interrupt->doorbell_npa_gart);
5959 
5960 		shootdown->doorbell_npa_gart = adev->gmc.gart_start+
5961 			(interrupt->mm_node_doorbell.start << AMDGPU_GPU_PAGE_SHIFT) + (1 << 6);
5962 
5963 		dev_dbg(adev->dev, "tlb doorbell npa 0x%llx mapped on gart 0x%llx\n",
5964 			npa, shootdown->doorbell_npa_gart);
5965 
5966 		interrupt->rb_size = AMDGPU_UALINK_RB_SIZE / 64;
5967 		interrupt->wptr = 0;
5968 		interrupt->rptr = 0;
5969 		interrupt->seq = 0;
5970 
5971 		shootdown->rb_size = AMDGPU_UALINK_RB_SIZE / 64;
5972 		shootdown->wptr = 0;
5973 		shootdown->rptr = 0;
5974 		shootdown->seq = 0;
5975 	}
5976 
5977 	dev_dbg(adev->dev, "peer remote init done r=%d\n", r);
5978 	return r;
5979 }
5980 
5981 /**
5982  * amdgpu_ualink_peer_remote_fini - Clean up remote peer GPU connections
5983  * @adev: amdgpu device pointer
5984  *
5985  * Unmaps GART entries and frees resources for remote GPU communication.
5986  */
5987 static void amdgpu_ualink_peer_remote_fini(struct amdgpu_device *adev)
5988 {
5989 	u32 rb_pages = AMDGPU_UALINK_RB_SIZE >> AMDGPU_GPU_PAGE_SHIFT;
5990 	struct amdgpu_ualink_remote *remote = to_remote(adev);
5991 	u32 src_accel_id = ualink_accel_id(adev);
5992 	u32 dst_accel_id;
5993 	struct amdgpu_ualink_peer *peer;
5994 	struct amdgpu_ualink_ring *ring;
5995 
5996 	dev_dbg(adev->dev, "src_accel_id %u\n", src_accel_id);
5997 
5998 	for_each_set_bit(dst_accel_id, remote->active_accel_bits, AMDGPU_UALINK_ACCEL_MAX) {
5999 		dev_dbg(adev->dev, "dst_accel_id %u\n", dst_accel_id);
6000 		if (dst_accel_id == src_accel_id)
6001 			continue;
6002 
6003 		peer = &remote->peer[dst_accel_id];
6004 		mutex_destroy(&peer->lock);
6005 
6006 		ring = &peer->interrupt;
6007 		amdgpu_ualink_gart_unmap(adev, rb_pages, &ring->mm_node_rb);
6008 		amdgpu_ualink_gart_unmap(adev, 1, &ring->mm_node_wptr);
6009 		amdgpu_ualink_gart_unmap(adev, 1, &ring->mm_node_doorbell);
6010 
6011 		ring = &peer->shootdown;
6012 		amdgpu_ualink_gart_unmap(adev, rb_pages, &ring->mm_node_rb);
6013 	}
6014 }
6015 
6016 /**
6017  * amdgpu_ualink_sw_init - Initialize UALink software resources
6018  * @adev: amdgpu device pointer
6019  *
6020  * Performs full UALink software initialization including metadata allocation,
6021  * NPA address mapping, SDMA scheduler entity setup, and remote peer GPU
6022  * connection initialization. On failure, all previously initialized resources
6023  * are cleaned up.
6024  *
6025  * Return: 0 on success, negative error code on failure
6026  */
6027 int amdgpu_ualink_sw_init(struct amdgpu_device *adev)
6028 {
6029 	struct amdgpu_ualink_remote *remote;
6030 	int r;
6031 
6032 	remote = kzalloc(sizeof(*remote), GFP_KERNEL);
6033 	if (!remote)
6034 		return -ENOMEM;
6035 	adev->ualink.remote = remote;
6036 
6037 	r = amdgpu_ualink_metadata_init(adev);
6038 	if (r)
6039 		goto out;
6040 
6041 	r = amdgpu_ualink_metadata_npa_mapping(adev);
6042 	if (r)
6043 		goto out_metadata_fini;
6044 
6045 	r = amdgpu_ualink_sdma_entities_init(adev);
6046 	if (r)
6047 		goto out_npa_unmap;
6048 
6049 	r = amdgpu_ualink_peer_remote_init(adev);
6050 	if (r)
6051 		goto out_sdma_entities_fini;
6052 
6053 	dev_dbg(adev->dev, "ualink sw init succeed\n");
6054 	return 0;
6055 
6056 out_sdma_entities_fini:
6057 	amdgpu_ualink_sdma_entities_fini(adev);
6058 out_npa_unmap:
6059 	amdgpu_ualink_metadata_npa_unmapping(adev);
6060 out_metadata_fini:
6061 	amdgpu_ualink_metadata_fini(adev);
6062 out:
6063 	kfree(adev->ualink.remote);
6064 	adev->ualink.remote = NULL;
6065 	dev_dbg(adev->dev, "ualink sw init failed %d\n", r);
6066 	return r;
6067 }
6068 
6069 /**
6070  * amdgpu_ualink_sw_fini - Tear down UALink software resources
6071  * @adev: amdgpu device pointer
6072  *
6073  * Cleans up all UALink software resources in reverse order of initialization:
6074  * remote peer connections, SDMA entities, NPA mappings, and metadata.
6075  */
6076 void amdgpu_ualink_sw_fini(struct amdgpu_device *adev)
6077 {
6078 	dev_dbg(adev->dev, "halt accel_id %u addr_mode %d\n", ualink_accel_id(adev),
6079 		ualink_addr_mode(adev));
6080 
6081 	adev->ualink.msg_ctl->send_halt(adev);
6082 
6083 	amdgpu_ualink_peer_remote_fini(adev);
6084 	amdgpu_ualink_sdma_entities_fini(adev);
6085 	amdgpu_ualink_metadata_npa_unmapping(adev);
6086 	amdgpu_ualink_metadata_fini(adev);
6087 	kfree(adev->ualink.remote);
6088 	adev->ualink.remote = NULL;
6089 }
6090 
6091 int ualink_send_hello(struct amdgpu_device *adev, u32 remote_accel_id)
6092 {
6093 	return amdgpu_ualink_send_hello_msg(adev, remote_accel_id);
6094 }
6095 
6096 /*
6097  * The low bits of handle_lo carry the message-header field on the wire.
6098  * Strip those bits and splice in @acc_id to recover the
6099  * fully-qualified handle_lo value.
6100  */
6101 static inline u64 amdgpu_ualink_reassemble_handle(u64 handle_lo, u32 acc_id)
6102 {
6103 	return (handle_lo & ~AMDGPU_UALINK_MESSAGE_HEADER_MASK) |
6104 	       (acc_id & AMDGPU_UALINK_HANDLE_ACCID_MASK);
6105 }
6106 
6107 static int amdgpu_ualink_process_irq(struct amdgpu_device *adev,
6108 				     struct amdgpu_irq_src *source,
6109 				     struct amdgpu_iv_entry *entry)
6110 {
6111 	u32 sender_acc_id, receiver_acc_id, msg_type, src_acc_id;
6112 	enum amdgpu_ualink_accel_state accel_state;
6113 	struct amdgpu_ualink_handle handle;
6114 	u32 size, npa_addr, fail_reason;
6115 	u32 dw0, dw1, dw2, dw3;
6116 	u32 local_acc_id;
6117 	int handled = 1;
6118 
6119 	if (unlikely(adev->ualink.mgr_state != AMDGPU_UALINK_INIT_COMPLETE)) {
6120 		dev_dbg(adev->dev,
6121 			"UALink manager not initialized, dropping irq\n");
6122 		return handled;
6123 	}
6124 
6125 	/* Only handle interrupts while ACTIVE. Otherwise (e.g. during teardown)
6126 	 * consume stale ring entries but drop them, so they don't touch state
6127 	 * being freed.
6128 	 */
6129 	accel_state = adev->ualink.info->accel_state;
6130 	if (accel_state != AMDGPU_UALINK_ACCEL_STATE_ACTIVE) {
6131 		dev_dbg(adev->dev,
6132 			"Dropping stale UALink interrupt, accel_state %d\n",
6133 			accel_state);
6134 		return handled;
6135 	}
6136 
6137 	dev_dbg(adev->dev, "%s client_id 0x%x src_id 0x%x ih\n",
6138 		entry->ih == &adev->irq.ih ? "ring" : "ualink soft ring",
6139 		entry->client_id, entry->src_id);
6140 
6141 	/* ContextID 4 dwords */
6142 	src_acc_id = entry->pasid;
6143 	dw0 = entry->src_data[0];
6144 	dw1 = entry->src_data[1];
6145 	dw2 = entry->src_data[2];
6146 	dw3 = entry->src_data[3];
6147 
6148 	/* Copy IH entry into ualink soft ring. */
6149 	if (entry->ih == &adev->irq.ih) {
6150 		dev_dbg(adev->dev, "src accel_id %u context id 0x%x 0x%x 0x%x 0x%x\n",
6151 			src_acc_id, dw0, dw1, dw2, dw3);
6152 		dev_dbg(adev->dev, "delegate to ualink irq soft ring\n");
6153 		amdgpu_irq_ualink_delegate(adev, entry, 8);
6154 		return handled;
6155 	}
6156 
6157 	msg_type = dw0 & AMDGPU_UALINK_MESSAGE_HEADER_MASK;
6158 	local_acc_id = adev->ualink.info->ppod.accel_id;
6159 	dev_dbg(adev->dev, "Got MSG: remote acc_id %u msg_type %u\n",
6160 		src_acc_id, msg_type);
6161 
6162 	/* Debug hook: if the bit corresponding to this msg_type is set in
6163 	 * drop_msg_bitmap, drop this single packet and clear the bit so that
6164 	 * any subsequent incoming messages are processed normally. Used to
6165 	 * exercise the connection reset/recovery paths via debugfs.
6166 	 */
6167 	if (msg_type < BITS_PER_LONG &&
6168 	    test_and_clear_bit(msg_type, &adev->ualink.drop_msg_bitmap)) {
6169 		dev_warn(adev->dev,
6170 			 "DROP MSG (debugfs): src acc_id %u msg_type %u dw[0-3] 0x%x 0x%x 0x%x 0x%x\n",
6171 			 src_acc_id, msg_type, dw0, dw1, dw2, dw3);
6172 		return handled;
6173 	}
6174 
6175 	switch (msg_type) {
6176 	case AMDGPU_UALINK_HELLO_MSG:
6177 		receiver_acc_id = (dw0 >> AMDGPU_UALINK_HELLO_MSG_RECV_ACCID_SHIFT) &
6178 					AMDGPU_UALINK_HELLO_MSG_ACCID_MASK;
6179 		sender_acc_id = (dw0 >> AMDGPU_UALINK_HELLO_MSG_SENDER_ACCID_SHIFT) &
6180 					AMDGPU_UALINK_HELLO_MSG_ACCID_MASK;
6181 		dev_dbg(adev->dev,
6182 			"Got HELLO MSG: src acc_id %u receiver_acc_id %u sender_acc_id %u\n",
6183 			src_acc_id, receiver_acc_id, sender_acc_id);
6184 		amdgpu_ualink_process_hello_msg(adev, receiver_acc_id, sender_acc_id,
6185 						src_acc_id);
6186 		break;
6187 	case AMDGPU_UALINK_HELLO_ACK_MSG:
6188 		dev_dbg(adev->dev,
6189 			"Got HELLO-ACK MSG: remote acc_id %u\n", src_acc_id);
6190 		amdgpu_ualink_process_hello_ack_msg(adev, src_acc_id);
6191 		break;
6192 	case AMDGPU_UALINK_NPA_REQ_MSG:
6193 		memcpy(&handle, entry->src_data, sizeof(struct amdgpu_ualink_handle));
6194 		handle.handle_lo = amdgpu_ualink_reassemble_handle(handle.handle_lo,
6195 								   local_acc_id);
6196 		dev_dbg(adev->dev,
6197 			"Got NPA-REQ MSG: remote acc_id %u handle %llx:%llx\n",
6198 			src_acc_id, handle.handle_hi, handle.handle_lo);
6199 		amdgpu_ualink_process_npa_req_msg(adev, src_acc_id, handle);
6200 		break;
6201 	case AMDGPU_UALINK_NPA_RSP_MSG:
6202 		memcpy(&handle.handle_lo, entry->src_data, sizeof(handle.handle_lo));
6203 		handle.handle_lo = amdgpu_ualink_reassemble_handle(handle.handle_lo,
6204 								   src_acc_id);
6205 		size = entry->src_data[2];
6206 		npa_addr = entry->src_data[3];
6207 		dev_dbg(adev->dev,
6208 			"Got NPA-RSP MSG: remote acc_id %u handle_lo %llx size 0x%x npa_addr 0x%x\n",
6209 			src_acc_id, handle.handle_lo, size, npa_addr);
6210 		amdgpu_ualink_process_npa_rsp_msg(adev, src_acc_id,
6211 						  handle.handle_lo,
6212 						  npa_addr, size);
6213 		break;
6214 	case AMDGPU_UALINK_NPA_FAIL_MSG:
6215 		memcpy(&handle.handle_lo, entry->src_data, sizeof(handle.handle_lo));
6216 		handle.handle_lo = amdgpu_ualink_reassemble_handle(handle.handle_lo,
6217 								   src_acc_id);
6218 		fail_reason = entry->src_data[2] &
6219 				AMDGPU_UALINK_NPA_FAIL_MSG_FAIL_REASON_MASK;
6220 		dev_dbg(adev->dev,
6221 			"Got NPA-FAIL MSG: remote acc_id %u handle_lo %llx fail_reason %u\n",
6222 			src_acc_id, handle.handle_lo, fail_reason);
6223 		amdgpu_ualink_process_npa_fail_msg(adev, src_acc_id,
6224 						   handle.handle_lo,
6225 						   fail_reason);
6226 		break;
6227 	case AMDGPU_UALINK_NPA_REVOKE_MSG:
6228 		memcpy(&handle, entry->src_data, sizeof(struct amdgpu_ualink_handle));
6229 		handle.handle_lo = amdgpu_ualink_reassemble_handle(handle.handle_lo,
6230 								   src_acc_id);
6231 		dev_dbg(adev->dev,
6232 			"Got NPA-REVOKE MSG: remote acc_id %u handle %llx:%llx\n",
6233 			src_acc_id, handle.handle_hi, handle.handle_lo);
6234 		amdgpu_ualink_process_npa_revoke_msg(adev, src_acc_id, handle);
6235 		break;
6236 	case AMDGPU_UALINK_NPA_RELEASE_MSG:
6237 		memcpy(&handle, entry->src_data, sizeof(struct amdgpu_ualink_handle));
6238 		handle.handle_lo = amdgpu_ualink_reassemble_handle(handle.handle_lo,
6239 								   local_acc_id);
6240 		dev_dbg(adev->dev,
6241 			"Got NPA-RELEASE MSG: remote acc_id %u handle %llx:%llx\n",
6242 			src_acc_id, handle.handle_hi, handle.handle_lo);
6243 		amdgpu_ualink_process_npa_release_msg(adev, src_acc_id, handle);
6244 		break;
6245 	default:
6246 		dev_err(adev->dev, "Unknown message type (%u)\n", msg_type);
6247 		break;
6248 	}
6249 
6250 	return handled;
6251 }
6252 
6253 static int amdgpu_ualink_set_irq_state(struct amdgpu_device *adev,
6254 					struct amdgpu_irq_src *source,
6255 					u32 type,
6256 					enum amdgpu_interrupt_state state)
6257 {
6258 	/*
6259 	 * Don't set register to enable/disable nHT controller interrupt.
6260 	 *
6261 	 * F/W running on MP2, which can always send cookie to IH block to
6262 	 * interrupt driver.
6263 	 */
6264 	dev_dbg(adev->dev, "ualink interrupt %s\n",
6265 		state == AMDGPU_IRQ_STATE_ENABLE ? "enable" : "disable");
6266 	return 0;
6267 }
6268 
6269 static const struct amdgpu_irq_src_funcs ualink_irq_funcs = {
6270 	.set = amdgpu_ualink_set_irq_state,
6271 	.process = amdgpu_ualink_process_irq,
6272 };
6273 
6274 /**
6275  * amdgpu_ualink_init_interrupt - register the UALink IRQ source
6276  * @adev: amdgpu device pointer
6277  * @client_id: IH client ID for the interrupt source
6278  * @src_id: source ID for the interrupt source
6279  *
6280  * Registers the UALink interrupt source with the IH subsystem.
6281  *
6282  * Return: 0 on success, negative error code on failure
6283  */
6284 int amdgpu_ualink_init_interrupt(struct amdgpu_device *adev,
6285 				 unsigned int client_id, unsigned int src_id)
6286 {
6287 	int r;
6288 
6289 	dev_dbg(adev->dev, "init ualink irq client_id 0x%x src_id 0x%x\n",
6290 		client_id, src_id);
6291 
6292 	adev->ualink.irq.num_types = 1;
6293 	adev->ualink.irq.funcs = &ualink_irq_funcs;
6294 
6295 	r = amdgpu_irq_add_id(adev, client_id, src_id, &adev->ualink.irq);
6296 	return r;
6297 }
6298 
6299