1 /*
2  * Copyright 2019 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  */
23 
24 #include <linux/firmware.h>
25 
26 #include "amdgpu_mes.h"
27 #include "amdgpu.h"
28 #include "soc15_common.h"
29 #include "amdgpu_mes_ctx.h"
30 
31 #define AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS 1024
32 #define AMDGPU_ONE_DOORBELL_SIZE 8
33 
34 int amdgpu_mes_doorbell_process_slice(struct amdgpu_device *adev)
35 {
36 	return roundup(AMDGPU_ONE_DOORBELL_SIZE *
37 		       AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS,
38 		       PAGE_SIZE);
39 }
40 
41 int amdgpu_mes_alloc_process_doorbells(struct amdgpu_device *adev,
42 				      unsigned int *doorbell_index)
43 {
44 	int r = ida_simple_get(&adev->mes.doorbell_ida, 2,
45 			       adev->mes.max_doorbell_slices,
46 			       GFP_KERNEL);
47 	if (r > 0)
48 		*doorbell_index = r;
49 
50 	return r;
51 }
52 
53 void amdgpu_mes_free_process_doorbells(struct amdgpu_device *adev,
54 				      unsigned int doorbell_index)
55 {
56 	if (doorbell_index)
57 		ida_simple_remove(&adev->mes.doorbell_ida, doorbell_index);
58 }
59 
60 unsigned int amdgpu_mes_get_doorbell_dw_offset_in_bar(
61 					struct amdgpu_device *adev,
62 					uint32_t doorbell_index,
63 					unsigned int doorbell_id)
64 {
65 	return ((doorbell_index *
66 		amdgpu_mes_doorbell_process_slice(adev)) / sizeof(u32) +
67 		doorbell_id * 2);
68 }
69 
70 static int amdgpu_mes_queue_doorbell_get(struct amdgpu_device *adev,
71 					 struct amdgpu_mes_process *process,
72 					 int ip_type, uint64_t *doorbell_index)
73 {
74 	unsigned int offset, found;
75 
76 	if (ip_type == AMDGPU_RING_TYPE_SDMA) {
77 		offset = adev->doorbell_index.sdma_engine[0];
78 		found = find_next_zero_bit(process->doorbell_bitmap,
79 					   AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS,
80 					   offset);
81 	} else {
82 		found = find_first_zero_bit(process->doorbell_bitmap,
83 					    AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS);
84 	}
85 
86 	if (found >= AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS) {
87 		DRM_WARN("No doorbell available\n");
88 		return -ENOSPC;
89 	}
90 
91 	set_bit(found, process->doorbell_bitmap);
92 
93 	*doorbell_index = amdgpu_mes_get_doorbell_dw_offset_in_bar(adev,
94 				process->doorbell_index, found);
95 
96 	return 0;
97 }
98 
99 static void amdgpu_mes_queue_doorbell_free(struct amdgpu_device *adev,
100 					   struct amdgpu_mes_process *process,
101 					   uint32_t doorbell_index)
102 {
103 	unsigned int old, doorbell_id;
104 
105 	doorbell_id = doorbell_index -
106 		(process->doorbell_index *
107 		 amdgpu_mes_doorbell_process_slice(adev)) / sizeof(u32);
108 	doorbell_id /= 2;
109 
110 	old = test_and_clear_bit(doorbell_id, process->doorbell_bitmap);
111 	WARN_ON(!old);
112 }
113 
114 static int amdgpu_mes_doorbell_init(struct amdgpu_device *adev)
115 {
116 	size_t doorbell_start_offset;
117 	size_t doorbell_aperture_size;
118 	size_t doorbell_process_limit;
119 	size_t aggregated_doorbell_start;
120 	int i;
121 
122 	aggregated_doorbell_start = (adev->doorbell_index.max_assignment + 1) * sizeof(u32);
123 	aggregated_doorbell_start =
124 		roundup(aggregated_doorbell_start, PAGE_SIZE);
125 
126 	doorbell_start_offset = aggregated_doorbell_start + PAGE_SIZE;
127 	doorbell_start_offset =
128 		roundup(doorbell_start_offset,
129 			amdgpu_mes_doorbell_process_slice(adev));
130 
131 	doorbell_aperture_size = adev->doorbell.size;
132 	doorbell_aperture_size =
133 			rounddown(doorbell_aperture_size,
134 				  amdgpu_mes_doorbell_process_slice(adev));
135 
136 	if (doorbell_aperture_size > doorbell_start_offset)
137 		doorbell_process_limit =
138 			(doorbell_aperture_size - doorbell_start_offset) /
139 			amdgpu_mes_doorbell_process_slice(adev);
140 	else
141 		return -ENOSPC;
142 
143 	adev->mes.doorbell_id_offset = doorbell_start_offset / sizeof(u32);
144 	adev->mes.max_doorbell_slices = doorbell_process_limit;
145 
146 	/* allocate Qword range for aggregated doorbell */
147 	for (i = 0; i < AMDGPU_MES_PRIORITY_NUM_LEVELS; i++)
148 		adev->mes.aggregated_doorbells[i] =
149 			aggregated_doorbell_start / sizeof(u32) + i * 2;
150 
151 	DRM_INFO("max_doorbell_slices=%zu\n", doorbell_process_limit);
152 	return 0;
153 }
154 
155 int amdgpu_mes_init(struct amdgpu_device *adev)
156 {
157 	int i, r;
158 
159 	adev->mes.adev = adev;
160 
161 	idr_init(&adev->mes.pasid_idr);
162 	idr_init(&adev->mes.gang_id_idr);
163 	idr_init(&adev->mes.queue_id_idr);
164 	ida_init(&adev->mes.doorbell_ida);
165 	spin_lock_init(&adev->mes.queue_id_lock);
166 	spin_lock_init(&adev->mes.ring_lock);
167 	mutex_init(&adev->mes.mutex_hidden);
168 
169 	adev->mes.total_max_queue = AMDGPU_FENCE_MES_QUEUE_ID_MASK;
170 	adev->mes.vmid_mask_mmhub = 0xffffff00;
171 	adev->mes.vmid_mask_gfxhub = 0xffffff00;
172 
173 	for (i = 0; i < AMDGPU_MES_MAX_COMPUTE_PIPES; i++) {
174 		/* use only 1st MEC pipes */
175 		if (i >= 4)
176 			continue;
177 		adev->mes.compute_hqd_mask[i] = 0xc;
178 	}
179 
180 	for (i = 0; i < AMDGPU_MES_MAX_GFX_PIPES; i++)
181 		adev->mes.gfx_hqd_mask[i] = i ? 0 : 0xfffffffe;
182 
183 	for (i = 0; i < AMDGPU_MES_MAX_SDMA_PIPES; i++) {
184 		if (adev->ip_versions[SDMA0_HWIP][0] < IP_VERSION(6, 0, 0))
185 			adev->mes.sdma_hqd_mask[i] = i ? 0 : 0x3fc;
186 		/* zero sdma_hqd_mask for non-existent engine */
187 		else if (adev->sdma.num_instances == 1)
188 			adev->mes.sdma_hqd_mask[i] = i ? 0 : 0xfc;
189 		else
190 			adev->mes.sdma_hqd_mask[i] = 0xfc;
191 	}
192 
193 	r = amdgpu_device_wb_get(adev, &adev->mes.sch_ctx_offs);
194 	if (r) {
195 		dev_err(adev->dev,
196 			"(%d) ring trail_fence_offs wb alloc failed\n", r);
197 		goto error_ids;
198 	}
199 	adev->mes.sch_ctx_gpu_addr =
200 		adev->wb.gpu_addr + (adev->mes.sch_ctx_offs * 4);
201 	adev->mes.sch_ctx_ptr =
202 		(uint64_t *)&adev->wb.wb[adev->mes.sch_ctx_offs];
203 
204 	r = amdgpu_device_wb_get(adev, &adev->mes.query_status_fence_offs);
205 	if (r) {
206 		amdgpu_device_wb_free(adev, adev->mes.sch_ctx_offs);
207 		dev_err(adev->dev,
208 			"(%d) query_status_fence_offs wb alloc failed\n", r);
209 		goto error_ids;
210 	}
211 	adev->mes.query_status_fence_gpu_addr =
212 		adev->wb.gpu_addr + (adev->mes.query_status_fence_offs * 4);
213 	adev->mes.query_status_fence_ptr =
214 		(uint64_t *)&adev->wb.wb[adev->mes.query_status_fence_offs];
215 
216 	r = amdgpu_device_wb_get(adev, &adev->mes.read_val_offs);
217 	if (r) {
218 		amdgpu_device_wb_free(adev, adev->mes.sch_ctx_offs);
219 		amdgpu_device_wb_free(adev, adev->mes.query_status_fence_offs);
220 		dev_err(adev->dev,
221 			"(%d) read_val_offs alloc failed\n", r);
222 		goto error_ids;
223 	}
224 	adev->mes.read_val_gpu_addr =
225 		adev->wb.gpu_addr + (adev->mes.read_val_offs * 4);
226 	adev->mes.read_val_ptr =
227 		(uint32_t *)&adev->wb.wb[adev->mes.read_val_offs];
228 
229 	r = amdgpu_mes_doorbell_init(adev);
230 	if (r)
231 		goto error;
232 
233 	return 0;
234 
235 error:
236 	amdgpu_device_wb_free(adev, adev->mes.sch_ctx_offs);
237 	amdgpu_device_wb_free(adev, adev->mes.query_status_fence_offs);
238 	amdgpu_device_wb_free(adev, adev->mes.read_val_offs);
239 error_ids:
240 	idr_destroy(&adev->mes.pasid_idr);
241 	idr_destroy(&adev->mes.gang_id_idr);
242 	idr_destroy(&adev->mes.queue_id_idr);
243 	ida_destroy(&adev->mes.doorbell_ida);
244 	mutex_destroy(&adev->mes.mutex_hidden);
245 	return r;
246 }
247 
248 void amdgpu_mes_fini(struct amdgpu_device *adev)
249 {
250 	amdgpu_device_wb_free(adev, adev->mes.sch_ctx_offs);
251 	amdgpu_device_wb_free(adev, adev->mes.query_status_fence_offs);
252 	amdgpu_device_wb_free(adev, adev->mes.read_val_offs);
253 
254 	idr_destroy(&adev->mes.pasid_idr);
255 	idr_destroy(&adev->mes.gang_id_idr);
256 	idr_destroy(&adev->mes.queue_id_idr);
257 	ida_destroy(&adev->mes.doorbell_ida);
258 	mutex_destroy(&adev->mes.mutex_hidden);
259 }
260 
261 static void amdgpu_mes_queue_free_mqd(struct amdgpu_mes_queue *q)
262 {
263 	amdgpu_bo_free_kernel(&q->mqd_obj,
264 			      &q->mqd_gpu_addr,
265 			      &q->mqd_cpu_ptr);
266 }
267 
268 int amdgpu_mes_create_process(struct amdgpu_device *adev, int pasid,
269 			      struct amdgpu_vm *vm)
270 {
271 	struct amdgpu_mes_process *process;
272 	int r;
273 
274 	/* allocate the mes process buffer */
275 	process = kzalloc(sizeof(struct amdgpu_mes_process), GFP_KERNEL);
276 	if (!process) {
277 		DRM_ERROR("no more memory to create mes process\n");
278 		return -ENOMEM;
279 	}
280 
281 	process->doorbell_bitmap =
282 		kzalloc(DIV_ROUND_UP(AMDGPU_MES_MAX_NUM_OF_QUEUES_PER_PROCESS,
283 				     BITS_PER_BYTE), GFP_KERNEL);
284 	if (!process->doorbell_bitmap) {
285 		DRM_ERROR("failed to allocate doorbell bitmap\n");
286 		kfree(process);
287 		return -ENOMEM;
288 	}
289 
290 	/* allocate the process context bo and map it */
291 	r = amdgpu_bo_create_kernel(adev, AMDGPU_MES_PROC_CTX_SIZE, PAGE_SIZE,
292 				    AMDGPU_GEM_DOMAIN_GTT,
293 				    &process->proc_ctx_bo,
294 				    &process->proc_ctx_gpu_addr,
295 				    &process->proc_ctx_cpu_ptr);
296 	if (r) {
297 		DRM_ERROR("failed to allocate process context bo\n");
298 		goto clean_up_memory;
299 	}
300 	memset(process->proc_ctx_cpu_ptr, 0, AMDGPU_MES_PROC_CTX_SIZE);
301 
302 	/*
303 	 * Avoid taking any other locks under MES lock to avoid circular
304 	 * lock dependencies.
305 	 */
306 	amdgpu_mes_lock(&adev->mes);
307 
308 	/* add the mes process to idr list */
309 	r = idr_alloc(&adev->mes.pasid_idr, process, pasid, pasid + 1,
310 		      GFP_KERNEL);
311 	if (r < 0) {
312 		DRM_ERROR("failed to lock pasid=%d\n", pasid);
313 		goto clean_up_ctx;
314 	}
315 
316 	/* allocate the starting doorbell index of the process */
317 	r = amdgpu_mes_alloc_process_doorbells(adev, &process->doorbell_index);
318 	if (r < 0) {
319 		DRM_ERROR("failed to allocate doorbell for process\n");
320 		goto clean_up_pasid;
321 	}
322 
323 	DRM_DEBUG("process doorbell index = %d\n", process->doorbell_index);
324 
325 	INIT_LIST_HEAD(&process->gang_list);
326 	process->vm = vm;
327 	process->pasid = pasid;
328 	process->process_quantum = adev->mes.default_process_quantum;
329 	process->pd_gpu_addr = amdgpu_bo_gpu_offset(vm->root.bo);
330 
331 	amdgpu_mes_unlock(&adev->mes);
332 	return 0;
333 
334 clean_up_pasid:
335 	idr_remove(&adev->mes.pasid_idr, pasid);
336 	amdgpu_mes_unlock(&adev->mes);
337 clean_up_ctx:
338 	amdgpu_bo_free_kernel(&process->proc_ctx_bo,
339 			      &process->proc_ctx_gpu_addr,
340 			      &process->proc_ctx_cpu_ptr);
341 clean_up_memory:
342 	kfree(process->doorbell_bitmap);
343 	kfree(process);
344 	return r;
345 }
346 
347 void amdgpu_mes_destroy_process(struct amdgpu_device *adev, int pasid)
348 {
349 	struct amdgpu_mes_process *process;
350 	struct amdgpu_mes_gang *gang, *tmp1;
351 	struct amdgpu_mes_queue *queue, *tmp2;
352 	struct mes_remove_queue_input queue_input;
353 	unsigned long flags;
354 	int r;
355 
356 	/*
357 	 * Avoid taking any other locks under MES lock to avoid circular
358 	 * lock dependencies.
359 	 */
360 	amdgpu_mes_lock(&adev->mes);
361 
362 	process = idr_find(&adev->mes.pasid_idr, pasid);
363 	if (!process) {
364 		DRM_WARN("pasid %d doesn't exist\n", pasid);
365 		amdgpu_mes_unlock(&adev->mes);
366 		return;
367 	}
368 
369 	/* Remove all queues from hardware */
370 	list_for_each_entry_safe(gang, tmp1, &process->gang_list, list) {
371 		list_for_each_entry_safe(queue, tmp2, &gang->queue_list, list) {
372 			spin_lock_irqsave(&adev->mes.queue_id_lock, flags);
373 			idr_remove(&adev->mes.queue_id_idr, queue->queue_id);
374 			spin_unlock_irqrestore(&adev->mes.queue_id_lock, flags);
375 
376 			queue_input.doorbell_offset = queue->doorbell_off;
377 			queue_input.gang_context_addr = gang->gang_ctx_gpu_addr;
378 
379 			r = adev->mes.funcs->remove_hw_queue(&adev->mes,
380 							     &queue_input);
381 			if (r)
382 				DRM_WARN("failed to remove hardware queue\n");
383 		}
384 
385 		idr_remove(&adev->mes.gang_id_idr, gang->gang_id);
386 	}
387 
388 	amdgpu_mes_free_process_doorbells(adev, process->doorbell_index);
389 	idr_remove(&adev->mes.pasid_idr, pasid);
390 	amdgpu_mes_unlock(&adev->mes);
391 
392 	/* free all memory allocated by the process */
393 	list_for_each_entry_safe(gang, tmp1, &process->gang_list, list) {
394 		/* free all queues in the gang */
395 		list_for_each_entry_safe(queue, tmp2, &gang->queue_list, list) {
396 			amdgpu_mes_queue_free_mqd(queue);
397 			list_del(&queue->list);
398 			kfree(queue);
399 		}
400 		amdgpu_bo_free_kernel(&gang->gang_ctx_bo,
401 				      &gang->gang_ctx_gpu_addr,
402 				      &gang->gang_ctx_cpu_ptr);
403 		list_del(&gang->list);
404 		kfree(gang);
405 
406 	}
407 	amdgpu_bo_free_kernel(&process->proc_ctx_bo,
408 			      &process->proc_ctx_gpu_addr,
409 			      &process->proc_ctx_cpu_ptr);
410 	kfree(process->doorbell_bitmap);
411 	kfree(process);
412 }
413 
414 int amdgpu_mes_add_gang(struct amdgpu_device *adev, int pasid,
415 			struct amdgpu_mes_gang_properties *gprops,
416 			int *gang_id)
417 {
418 	struct amdgpu_mes_process *process;
419 	struct amdgpu_mes_gang *gang;
420 	int r;
421 
422 	/* allocate the mes gang buffer */
423 	gang = kzalloc(sizeof(struct amdgpu_mes_gang), GFP_KERNEL);
424 	if (!gang) {
425 		return -ENOMEM;
426 	}
427 
428 	/* allocate the gang context bo and map it to cpu space */
429 	r = amdgpu_bo_create_kernel(adev, AMDGPU_MES_GANG_CTX_SIZE, PAGE_SIZE,
430 				    AMDGPU_GEM_DOMAIN_GTT,
431 				    &gang->gang_ctx_bo,
432 				    &gang->gang_ctx_gpu_addr,
433 				    &gang->gang_ctx_cpu_ptr);
434 	if (r) {
435 		DRM_ERROR("failed to allocate process context bo\n");
436 		goto clean_up_mem;
437 	}
438 	memset(gang->gang_ctx_cpu_ptr, 0, AMDGPU_MES_GANG_CTX_SIZE);
439 
440 	/*
441 	 * Avoid taking any other locks under MES lock to avoid circular
442 	 * lock dependencies.
443 	 */
444 	amdgpu_mes_lock(&adev->mes);
445 
446 	process = idr_find(&adev->mes.pasid_idr, pasid);
447 	if (!process) {
448 		DRM_ERROR("pasid %d doesn't exist\n", pasid);
449 		r = -EINVAL;
450 		goto clean_up_ctx;
451 	}
452 
453 	/* add the mes gang to idr list */
454 	r = idr_alloc(&adev->mes.gang_id_idr, gang, 1, 0,
455 		      GFP_KERNEL);
456 	if (r < 0) {
457 		DRM_ERROR("failed to allocate idr for gang\n");
458 		goto clean_up_ctx;
459 	}
460 
461 	gang->gang_id = r;
462 	*gang_id = r;
463 
464 	INIT_LIST_HEAD(&gang->queue_list);
465 	gang->process = process;
466 	gang->priority = gprops->priority;
467 	gang->gang_quantum = gprops->gang_quantum ?
468 		gprops->gang_quantum : adev->mes.default_gang_quantum;
469 	gang->global_priority_level = gprops->global_priority_level;
470 	gang->inprocess_gang_priority = gprops->inprocess_gang_priority;
471 	list_add_tail(&gang->list, &process->gang_list);
472 
473 	amdgpu_mes_unlock(&adev->mes);
474 	return 0;
475 
476 clean_up_ctx:
477 	amdgpu_mes_unlock(&adev->mes);
478 	amdgpu_bo_free_kernel(&gang->gang_ctx_bo,
479 			      &gang->gang_ctx_gpu_addr,
480 			      &gang->gang_ctx_cpu_ptr);
481 clean_up_mem:
482 	kfree(gang);
483 	return r;
484 }
485 
486 int amdgpu_mes_remove_gang(struct amdgpu_device *adev, int gang_id)
487 {
488 	struct amdgpu_mes_gang *gang;
489 
490 	/*
491 	 * Avoid taking any other locks under MES lock to avoid circular
492 	 * lock dependencies.
493 	 */
494 	amdgpu_mes_lock(&adev->mes);
495 
496 	gang = idr_find(&adev->mes.gang_id_idr, gang_id);
497 	if (!gang) {
498 		DRM_ERROR("gang id %d doesn't exist\n", gang_id);
499 		amdgpu_mes_unlock(&adev->mes);
500 		return -EINVAL;
501 	}
502 
503 	if (!list_empty(&gang->queue_list)) {
504 		DRM_ERROR("queue list is not empty\n");
505 		amdgpu_mes_unlock(&adev->mes);
506 		return -EBUSY;
507 	}
508 
509 	idr_remove(&adev->mes.gang_id_idr, gang->gang_id);
510 	list_del(&gang->list);
511 	amdgpu_mes_unlock(&adev->mes);
512 
513 	amdgpu_bo_free_kernel(&gang->gang_ctx_bo,
514 			      &gang->gang_ctx_gpu_addr,
515 			      &gang->gang_ctx_cpu_ptr);
516 
517 	kfree(gang);
518 
519 	return 0;
520 }
521 
522 int amdgpu_mes_suspend(struct amdgpu_device *adev)
523 {
524 	struct idr *idp;
525 	struct amdgpu_mes_process *process;
526 	struct amdgpu_mes_gang *gang;
527 	struct mes_suspend_gang_input input;
528 	int r, pasid;
529 
530 	/*
531 	 * Avoid taking any other locks under MES lock to avoid circular
532 	 * lock dependencies.
533 	 */
534 	amdgpu_mes_lock(&adev->mes);
535 
536 	idp = &adev->mes.pasid_idr;
537 
538 	idr_for_each_entry(idp, process, pasid) {
539 		list_for_each_entry(gang, &process->gang_list, list) {
540 			r = adev->mes.funcs->suspend_gang(&adev->mes, &input);
541 			if (r)
542 				DRM_ERROR("failed to suspend pasid %d gangid %d",
543 					 pasid, gang->gang_id);
544 		}
545 	}
546 
547 	amdgpu_mes_unlock(&adev->mes);
548 	return 0;
549 }
550 
551 int amdgpu_mes_resume(struct amdgpu_device *adev)
552 {
553 	struct idr *idp;
554 	struct amdgpu_mes_process *process;
555 	struct amdgpu_mes_gang *gang;
556 	struct mes_resume_gang_input input;
557 	int r, pasid;
558 
559 	/*
560 	 * Avoid taking any other locks under MES lock to avoid circular
561 	 * lock dependencies.
562 	 */
563 	amdgpu_mes_lock(&adev->mes);
564 
565 	idp = &adev->mes.pasid_idr;
566 
567 	idr_for_each_entry(idp, process, pasid) {
568 		list_for_each_entry(gang, &process->gang_list, list) {
569 			r = adev->mes.funcs->resume_gang(&adev->mes, &input);
570 			if (r)
571 				DRM_ERROR("failed to resume pasid %d gangid %d",
572 					 pasid, gang->gang_id);
573 		}
574 	}
575 
576 	amdgpu_mes_unlock(&adev->mes);
577 	return 0;
578 }
579 
580 static int amdgpu_mes_queue_alloc_mqd(struct amdgpu_device *adev,
581 				     struct amdgpu_mes_queue *q,
582 				     struct amdgpu_mes_queue_properties *p)
583 {
584 	struct amdgpu_mqd *mqd_mgr = &adev->mqds[p->queue_type];
585 	u32 mqd_size = mqd_mgr->mqd_size;
586 	int r;
587 
588 	r = amdgpu_bo_create_kernel(adev, mqd_size, PAGE_SIZE,
589 				    AMDGPU_GEM_DOMAIN_GTT,
590 				    &q->mqd_obj,
591 				    &q->mqd_gpu_addr, &q->mqd_cpu_ptr);
592 	if (r) {
593 		dev_warn(adev->dev, "failed to create queue mqd bo (%d)", r);
594 		return r;
595 	}
596 	memset(q->mqd_cpu_ptr, 0, mqd_size);
597 
598 	r = amdgpu_bo_reserve(q->mqd_obj, false);
599 	if (unlikely(r != 0))
600 		goto clean_up;
601 
602 	return 0;
603 
604 clean_up:
605 	amdgpu_bo_free_kernel(&q->mqd_obj,
606 			      &q->mqd_gpu_addr,
607 			      &q->mqd_cpu_ptr);
608 	return r;
609 }
610 
611 static void amdgpu_mes_queue_init_mqd(struct amdgpu_device *adev,
612 				     struct amdgpu_mes_queue *q,
613 				     struct amdgpu_mes_queue_properties *p)
614 {
615 	struct amdgpu_mqd *mqd_mgr = &adev->mqds[p->queue_type];
616 	struct amdgpu_mqd_prop mqd_prop = {0};
617 
618 	mqd_prop.mqd_gpu_addr = q->mqd_gpu_addr;
619 	mqd_prop.hqd_base_gpu_addr = p->hqd_base_gpu_addr;
620 	mqd_prop.rptr_gpu_addr = p->rptr_gpu_addr;
621 	mqd_prop.wptr_gpu_addr = p->wptr_gpu_addr;
622 	mqd_prop.queue_size = p->queue_size;
623 	mqd_prop.use_doorbell = true;
624 	mqd_prop.doorbell_index = p->doorbell_off;
625 	mqd_prop.eop_gpu_addr = p->eop_gpu_addr;
626 	mqd_prop.hqd_pipe_priority = p->hqd_pipe_priority;
627 	mqd_prop.hqd_queue_priority = p->hqd_queue_priority;
628 	mqd_prop.hqd_active = false;
629 
630 	mqd_mgr->init_mqd(adev, q->mqd_cpu_ptr, &mqd_prop);
631 
632 	amdgpu_bo_unreserve(q->mqd_obj);
633 }
634 
635 int amdgpu_mes_add_hw_queue(struct amdgpu_device *adev, int gang_id,
636 			    struct amdgpu_mes_queue_properties *qprops,
637 			    int *queue_id)
638 {
639 	struct amdgpu_mes_queue *queue;
640 	struct amdgpu_mes_gang *gang;
641 	struct mes_add_queue_input queue_input;
642 	unsigned long flags;
643 	int r;
644 
645 	/* allocate the mes queue buffer */
646 	queue = kzalloc(sizeof(struct amdgpu_mes_queue), GFP_KERNEL);
647 	if (!queue) {
648 		DRM_ERROR("Failed to allocate memory for queue\n");
649 		return -ENOMEM;
650 	}
651 
652 	/* Allocate the queue mqd */
653 	r = amdgpu_mes_queue_alloc_mqd(adev, queue, qprops);
654 	if (r)
655 		goto clean_up_memory;
656 
657 	/*
658 	 * Avoid taking any other locks under MES lock to avoid circular
659 	 * lock dependencies.
660 	 */
661 	amdgpu_mes_lock(&adev->mes);
662 
663 	gang = idr_find(&adev->mes.gang_id_idr, gang_id);
664 	if (!gang) {
665 		DRM_ERROR("gang id %d doesn't exist\n", gang_id);
666 		r = -EINVAL;
667 		goto clean_up_mqd;
668 	}
669 
670 	/* add the mes gang to idr list */
671 	spin_lock_irqsave(&adev->mes.queue_id_lock, flags);
672 	r = idr_alloc(&adev->mes.queue_id_idr, queue, 1, 0,
673 		      GFP_ATOMIC);
674 	if (r < 0) {
675 		spin_unlock_irqrestore(&adev->mes.queue_id_lock, flags);
676 		goto clean_up_mqd;
677 	}
678 	spin_unlock_irqrestore(&adev->mes.queue_id_lock, flags);
679 	*queue_id = queue->queue_id = r;
680 
681 	/* allocate a doorbell index for the queue */
682 	r = amdgpu_mes_queue_doorbell_get(adev, gang->process,
683 					  qprops->queue_type,
684 					  &qprops->doorbell_off);
685 	if (r)
686 		goto clean_up_queue_id;
687 
688 	/* initialize the queue mqd */
689 	amdgpu_mes_queue_init_mqd(adev, queue, qprops);
690 
691 	/* add hw queue to mes */
692 	queue_input.process_id = gang->process->pasid;
693 
694 	queue_input.page_table_base_addr =
695 		adev->vm_manager.vram_base_offset + gang->process->pd_gpu_addr -
696 		adev->gmc.vram_start;
697 
698 	queue_input.process_va_start = 0;
699 	queue_input.process_va_end =
700 		(adev->vm_manager.max_pfn - 1) << AMDGPU_GPU_PAGE_SHIFT;
701 	queue_input.process_quantum = gang->process->process_quantum;
702 	queue_input.process_context_addr = gang->process->proc_ctx_gpu_addr;
703 	queue_input.gang_quantum = gang->gang_quantum;
704 	queue_input.gang_context_addr = gang->gang_ctx_gpu_addr;
705 	queue_input.inprocess_gang_priority = gang->inprocess_gang_priority;
706 	queue_input.gang_global_priority_level = gang->global_priority_level;
707 	queue_input.doorbell_offset = qprops->doorbell_off;
708 	queue_input.mqd_addr = queue->mqd_gpu_addr;
709 	queue_input.wptr_addr = qprops->wptr_gpu_addr;
710 	queue_input.wptr_mc_addr = qprops->wptr_mc_addr;
711 	queue_input.queue_type = qprops->queue_type;
712 	queue_input.paging = qprops->paging;
713 	queue_input.is_kfd_process = 0;
714 
715 	r = adev->mes.funcs->add_hw_queue(&adev->mes, &queue_input);
716 	if (r) {
717 		DRM_ERROR("failed to add hardware queue to MES, doorbell=0x%llx\n",
718 			  qprops->doorbell_off);
719 		goto clean_up_doorbell;
720 	}
721 
722 	DRM_DEBUG("MES hw queue was added, pasid=%d, gang id=%d, "
723 		  "queue type=%d, doorbell=0x%llx\n",
724 		  gang->process->pasid, gang_id, qprops->queue_type,
725 		  qprops->doorbell_off);
726 
727 	queue->ring = qprops->ring;
728 	queue->doorbell_off = qprops->doorbell_off;
729 	queue->wptr_gpu_addr = qprops->wptr_gpu_addr;
730 	queue->queue_type = qprops->queue_type;
731 	queue->paging = qprops->paging;
732 	queue->gang = gang;
733 	queue->ring->mqd_ptr = queue->mqd_cpu_ptr;
734 	list_add_tail(&queue->list, &gang->queue_list);
735 
736 	amdgpu_mes_unlock(&adev->mes);
737 	return 0;
738 
739 clean_up_doorbell:
740 	amdgpu_mes_queue_doorbell_free(adev, gang->process,
741 				       qprops->doorbell_off);
742 clean_up_queue_id:
743 	spin_lock_irqsave(&adev->mes.queue_id_lock, flags);
744 	idr_remove(&adev->mes.queue_id_idr, queue->queue_id);
745 	spin_unlock_irqrestore(&adev->mes.queue_id_lock, flags);
746 clean_up_mqd:
747 	amdgpu_mes_unlock(&adev->mes);
748 	amdgpu_mes_queue_free_mqd(queue);
749 clean_up_memory:
750 	kfree(queue);
751 	return r;
752 }
753 
754 int amdgpu_mes_remove_hw_queue(struct amdgpu_device *adev, int queue_id)
755 {
756 	unsigned long flags;
757 	struct amdgpu_mes_queue *queue;
758 	struct amdgpu_mes_gang *gang;
759 	struct mes_remove_queue_input queue_input;
760 	int r;
761 
762 	/*
763 	 * Avoid taking any other locks under MES lock to avoid circular
764 	 * lock dependencies.
765 	 */
766 	amdgpu_mes_lock(&adev->mes);
767 
768 	/* remove the mes gang from idr list */
769 	spin_lock_irqsave(&adev->mes.queue_id_lock, flags);
770 
771 	queue = idr_find(&adev->mes.queue_id_idr, queue_id);
772 	if (!queue) {
773 		spin_unlock_irqrestore(&adev->mes.queue_id_lock, flags);
774 		amdgpu_mes_unlock(&adev->mes);
775 		DRM_ERROR("queue id %d doesn't exist\n", queue_id);
776 		return -EINVAL;
777 	}
778 
779 	idr_remove(&adev->mes.queue_id_idr, queue_id);
780 	spin_unlock_irqrestore(&adev->mes.queue_id_lock, flags);
781 
782 	DRM_DEBUG("try to remove queue, doorbell off = 0x%llx\n",
783 		  queue->doorbell_off);
784 
785 	gang = queue->gang;
786 	queue_input.doorbell_offset = queue->doorbell_off;
787 	queue_input.gang_context_addr = gang->gang_ctx_gpu_addr;
788 
789 	r = adev->mes.funcs->remove_hw_queue(&adev->mes, &queue_input);
790 	if (r)
791 		DRM_ERROR("failed to remove hardware queue, queue id = %d\n",
792 			  queue_id);
793 
794 	list_del(&queue->list);
795 	amdgpu_mes_queue_doorbell_free(adev, gang->process,
796 				       queue->doorbell_off);
797 	amdgpu_mes_unlock(&adev->mes);
798 
799 	amdgpu_mes_queue_free_mqd(queue);
800 	kfree(queue);
801 	return 0;
802 }
803 
804 int amdgpu_mes_unmap_legacy_queue(struct amdgpu_device *adev,
805 				  struct amdgpu_ring *ring,
806 				  enum amdgpu_unmap_queues_action action,
807 				  u64 gpu_addr, u64 seq)
808 {
809 	struct mes_unmap_legacy_queue_input queue_input;
810 	int r;
811 
812 	queue_input.action = action;
813 	queue_input.queue_type = ring->funcs->type;
814 	queue_input.doorbell_offset = ring->doorbell_index;
815 	queue_input.pipe_id = ring->pipe;
816 	queue_input.queue_id = ring->queue;
817 	queue_input.trail_fence_addr = gpu_addr;
818 	queue_input.trail_fence_data = seq;
819 
820 	r = adev->mes.funcs->unmap_legacy_queue(&adev->mes, &queue_input);
821 	if (r)
822 		DRM_ERROR("failed to unmap legacy queue\n");
823 
824 	return r;
825 }
826 
827 uint32_t amdgpu_mes_rreg(struct amdgpu_device *adev, uint32_t reg)
828 {
829 	struct mes_misc_op_input op_input;
830 	int r, val = 0;
831 
832 	op_input.op = MES_MISC_OP_READ_REG;
833 	op_input.read_reg.reg_offset = reg;
834 	op_input.read_reg.buffer_addr = adev->mes.read_val_gpu_addr;
835 
836 	if (!adev->mes.funcs->misc_op) {
837 		DRM_ERROR("mes rreg is not supported!\n");
838 		goto error;
839 	}
840 
841 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
842 	if (r)
843 		DRM_ERROR("failed to read reg (0x%x)\n", reg);
844 	else
845 		val = *(adev->mes.read_val_ptr);
846 
847 error:
848 	return val;
849 }
850 
851 int amdgpu_mes_wreg(struct amdgpu_device *adev,
852 		    uint32_t reg, uint32_t val)
853 {
854 	struct mes_misc_op_input op_input;
855 	int r;
856 
857 	op_input.op = MES_MISC_OP_WRITE_REG;
858 	op_input.write_reg.reg_offset = reg;
859 	op_input.write_reg.reg_value = val;
860 
861 	if (!adev->mes.funcs->misc_op) {
862 		DRM_ERROR("mes wreg is not supported!\n");
863 		r = -EINVAL;
864 		goto error;
865 	}
866 
867 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
868 	if (r)
869 		DRM_ERROR("failed to write reg (0x%x)\n", reg);
870 
871 error:
872 	return r;
873 }
874 
875 int amdgpu_mes_reg_write_reg_wait(struct amdgpu_device *adev,
876 				  uint32_t reg0, uint32_t reg1,
877 				  uint32_t ref, uint32_t mask)
878 {
879 	struct mes_misc_op_input op_input;
880 	int r;
881 
882 	op_input.op = MES_MISC_OP_WRM_REG_WR_WAIT;
883 	op_input.wrm_reg.reg0 = reg0;
884 	op_input.wrm_reg.reg1 = reg1;
885 	op_input.wrm_reg.ref = ref;
886 	op_input.wrm_reg.mask = mask;
887 
888 	if (!adev->mes.funcs->misc_op) {
889 		DRM_ERROR("mes reg_write_reg_wait is not supported!\n");
890 		r = -EINVAL;
891 		goto error;
892 	}
893 
894 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
895 	if (r)
896 		DRM_ERROR("failed to reg_write_reg_wait\n");
897 
898 error:
899 	return r;
900 }
901 
902 int amdgpu_mes_reg_wait(struct amdgpu_device *adev, uint32_t reg,
903 			uint32_t val, uint32_t mask)
904 {
905 	struct mes_misc_op_input op_input;
906 	int r;
907 
908 	op_input.op = MES_MISC_OP_WRM_REG_WAIT;
909 	op_input.wrm_reg.reg0 = reg;
910 	op_input.wrm_reg.ref = val;
911 	op_input.wrm_reg.mask = mask;
912 
913 	if (!adev->mes.funcs->misc_op) {
914 		DRM_ERROR("mes reg wait is not supported!\n");
915 		r = -EINVAL;
916 		goto error;
917 	}
918 
919 	r = adev->mes.funcs->misc_op(&adev->mes, &op_input);
920 	if (r)
921 		DRM_ERROR("failed to reg_write_reg_wait\n");
922 
923 error:
924 	return r;
925 }
926 
927 static void
928 amdgpu_mes_ring_to_queue_props(struct amdgpu_device *adev,
929 			       struct amdgpu_ring *ring,
930 			       struct amdgpu_mes_queue_properties *props)
931 {
932 	props->queue_type = ring->funcs->type;
933 	props->hqd_base_gpu_addr = ring->gpu_addr;
934 	props->rptr_gpu_addr = ring->rptr_gpu_addr;
935 	props->wptr_gpu_addr = ring->wptr_gpu_addr;
936 	props->wptr_mc_addr =
937 		ring->mes_ctx->meta_data_mc_addr + ring->wptr_offs;
938 	props->queue_size = ring->ring_size;
939 	props->eop_gpu_addr = ring->eop_gpu_addr;
940 	props->hqd_pipe_priority = AMDGPU_GFX_PIPE_PRIO_NORMAL;
941 	props->hqd_queue_priority = AMDGPU_GFX_QUEUE_PRIORITY_MINIMUM;
942 	props->paging = false;
943 	props->ring = ring;
944 }
945 
946 #define DEFINE_AMDGPU_MES_CTX_GET_OFFS_ENG(_eng)			\
947 do {									\
948        if (id_offs < AMDGPU_MES_CTX_MAX_OFFS)				\
949 		return offsetof(struct amdgpu_mes_ctx_meta_data,	\
950 				_eng[ring->idx].slots[id_offs]);        \
951        else if (id_offs == AMDGPU_MES_CTX_RING_OFFS)			\
952 		return offsetof(struct amdgpu_mes_ctx_meta_data,        \
953 				_eng[ring->idx].ring);                  \
954        else if (id_offs == AMDGPU_MES_CTX_IB_OFFS)			\
955 		return offsetof(struct amdgpu_mes_ctx_meta_data,        \
956 				_eng[ring->idx].ib);                    \
957        else if (id_offs == AMDGPU_MES_CTX_PADDING_OFFS)			\
958 		return offsetof(struct amdgpu_mes_ctx_meta_data,        \
959 				_eng[ring->idx].padding);               \
960 } while(0)
961 
962 int amdgpu_mes_ctx_get_offs(struct amdgpu_ring *ring, unsigned int id_offs)
963 {
964 	switch (ring->funcs->type) {
965 	case AMDGPU_RING_TYPE_GFX:
966 		DEFINE_AMDGPU_MES_CTX_GET_OFFS_ENG(gfx);
967 		break;
968 	case AMDGPU_RING_TYPE_COMPUTE:
969 		DEFINE_AMDGPU_MES_CTX_GET_OFFS_ENG(compute);
970 		break;
971 	case AMDGPU_RING_TYPE_SDMA:
972 		DEFINE_AMDGPU_MES_CTX_GET_OFFS_ENG(sdma);
973 		break;
974 	default:
975 		break;
976 	}
977 
978 	WARN_ON(1);
979 	return -EINVAL;
980 }
981 
982 int amdgpu_mes_add_ring(struct amdgpu_device *adev, int gang_id,
983 			int queue_type, int idx,
984 			struct amdgpu_mes_ctx_data *ctx_data,
985 			struct amdgpu_ring **out)
986 {
987 	struct amdgpu_ring *ring;
988 	struct amdgpu_mes_gang *gang;
989 	struct amdgpu_mes_queue_properties qprops = {0};
990 	int r, queue_id, pasid;
991 
992 	/*
993 	 * Avoid taking any other locks under MES lock to avoid circular
994 	 * lock dependencies.
995 	 */
996 	amdgpu_mes_lock(&adev->mes);
997 	gang = idr_find(&adev->mes.gang_id_idr, gang_id);
998 	if (!gang) {
999 		DRM_ERROR("gang id %d doesn't exist\n", gang_id);
1000 		amdgpu_mes_unlock(&adev->mes);
1001 		return -EINVAL;
1002 	}
1003 	pasid = gang->process->pasid;
1004 
1005 	ring = kzalloc(sizeof(struct amdgpu_ring), GFP_KERNEL);
1006 	if (!ring) {
1007 		amdgpu_mes_unlock(&adev->mes);
1008 		return -ENOMEM;
1009 	}
1010 
1011 	ring->ring_obj = NULL;
1012 	ring->use_doorbell = true;
1013 	ring->is_mes_queue = true;
1014 	ring->mes_ctx = ctx_data;
1015 	ring->idx = idx;
1016 	ring->no_scheduler = true;
1017 
1018 	if (queue_type == AMDGPU_RING_TYPE_COMPUTE) {
1019 		int offset = offsetof(struct amdgpu_mes_ctx_meta_data,
1020 				      compute[ring->idx].mec_hpd);
1021 		ring->eop_gpu_addr =
1022 			amdgpu_mes_ctx_get_offs_gpu_addr(ring, offset);
1023 	}
1024 
1025 	switch (queue_type) {
1026 	case AMDGPU_RING_TYPE_GFX:
1027 		ring->funcs = adev->gfx.gfx_ring[0].funcs;
1028 		break;
1029 	case AMDGPU_RING_TYPE_COMPUTE:
1030 		ring->funcs = adev->gfx.compute_ring[0].funcs;
1031 		break;
1032 	case AMDGPU_RING_TYPE_SDMA:
1033 		ring->funcs = adev->sdma.instance[0].ring.funcs;
1034 		break;
1035 	default:
1036 		BUG();
1037 	}
1038 
1039 	r = amdgpu_ring_init(adev, ring, 1024, NULL, 0,
1040 			     AMDGPU_RING_PRIO_DEFAULT, NULL);
1041 	if (r)
1042 		goto clean_up_memory;
1043 
1044 	amdgpu_mes_ring_to_queue_props(adev, ring, &qprops);
1045 
1046 	dma_fence_wait(gang->process->vm->last_update, false);
1047 	dma_fence_wait(ctx_data->meta_data_va->last_pt_update, false);
1048 	amdgpu_mes_unlock(&adev->mes);
1049 
1050 	r = amdgpu_mes_add_hw_queue(adev, gang_id, &qprops, &queue_id);
1051 	if (r)
1052 		goto clean_up_ring;
1053 
1054 	ring->hw_queue_id = queue_id;
1055 	ring->doorbell_index = qprops.doorbell_off;
1056 
1057 	if (queue_type == AMDGPU_RING_TYPE_GFX)
1058 		sprintf(ring->name, "gfx_%d.%d.%d", pasid, gang_id, queue_id);
1059 	else if (queue_type == AMDGPU_RING_TYPE_COMPUTE)
1060 		sprintf(ring->name, "compute_%d.%d.%d", pasid, gang_id,
1061 			queue_id);
1062 	else if (queue_type == AMDGPU_RING_TYPE_SDMA)
1063 		sprintf(ring->name, "sdma_%d.%d.%d", pasid, gang_id,
1064 			queue_id);
1065 	else
1066 		BUG();
1067 
1068 	*out = ring;
1069 	return 0;
1070 
1071 clean_up_ring:
1072 	amdgpu_ring_fini(ring);
1073 clean_up_memory:
1074 	kfree(ring);
1075 	amdgpu_mes_unlock(&adev->mes);
1076 	return r;
1077 }
1078 
1079 void amdgpu_mes_remove_ring(struct amdgpu_device *adev,
1080 			    struct amdgpu_ring *ring)
1081 {
1082 	if (!ring)
1083 		return;
1084 
1085 	amdgpu_mes_remove_hw_queue(adev, ring->hw_queue_id);
1086 	amdgpu_ring_fini(ring);
1087 	kfree(ring);
1088 }
1089 
1090 uint32_t amdgpu_mes_get_aggregated_doorbell_index(struct amdgpu_device *adev,
1091 						   enum amdgpu_mes_priority_level prio)
1092 {
1093 	return adev->mes.aggregated_doorbells[prio];
1094 }
1095 
1096 int amdgpu_mes_ctx_alloc_meta_data(struct amdgpu_device *adev,
1097 				   struct amdgpu_mes_ctx_data *ctx_data)
1098 {
1099 	int r;
1100 
1101 	r = amdgpu_bo_create_kernel(adev,
1102 			    sizeof(struct amdgpu_mes_ctx_meta_data),
1103 			    PAGE_SIZE, AMDGPU_GEM_DOMAIN_GTT,
1104 			    &ctx_data->meta_data_obj,
1105 			    &ctx_data->meta_data_mc_addr,
1106 			    &ctx_data->meta_data_ptr);
1107 	if (r) {
1108 		dev_warn(adev->dev, "(%d) create CTX bo failed\n", r);
1109 		return r;
1110 	}
1111 
1112 	if (!ctx_data->meta_data_obj)
1113 		return -ENOMEM;
1114 
1115 	memset(ctx_data->meta_data_ptr, 0,
1116 	       sizeof(struct amdgpu_mes_ctx_meta_data));
1117 
1118 	return 0;
1119 }
1120 
1121 void amdgpu_mes_ctx_free_meta_data(struct amdgpu_mes_ctx_data *ctx_data)
1122 {
1123 	if (ctx_data->meta_data_obj)
1124 		amdgpu_bo_free_kernel(&ctx_data->meta_data_obj,
1125 				      &ctx_data->meta_data_mc_addr,
1126 				      &ctx_data->meta_data_ptr);
1127 }
1128 
1129 int amdgpu_mes_ctx_map_meta_data(struct amdgpu_device *adev,
1130 				 struct amdgpu_vm *vm,
1131 				 struct amdgpu_mes_ctx_data *ctx_data)
1132 {
1133 	struct amdgpu_bo_va *bo_va;
1134 	struct ww_acquire_ctx ticket;
1135 	struct list_head list;
1136 	struct amdgpu_bo_list_entry pd;
1137 	struct ttm_validate_buffer csa_tv;
1138 	struct amdgpu_sync sync;
1139 	int r;
1140 
1141 	amdgpu_sync_create(&sync);
1142 	INIT_LIST_HEAD(&list);
1143 	INIT_LIST_HEAD(&csa_tv.head);
1144 
1145 	csa_tv.bo = &ctx_data->meta_data_obj->tbo;
1146 	csa_tv.num_shared = 1;
1147 
1148 	list_add(&csa_tv.head, &list);
1149 	amdgpu_vm_get_pd_bo(vm, &list, &pd);
1150 
1151 	r = ttm_eu_reserve_buffers(&ticket, &list, true, NULL);
1152 	if (r) {
1153 		DRM_ERROR("failed to reserve meta data BO: err=%d\n", r);
1154 		return r;
1155 	}
1156 
1157 	bo_va = amdgpu_vm_bo_add(adev, vm, ctx_data->meta_data_obj);
1158 	if (!bo_va) {
1159 		ttm_eu_backoff_reservation(&ticket, &list);
1160 		DRM_ERROR("failed to create bo_va for meta data BO\n");
1161 		return -ENOMEM;
1162 	}
1163 
1164 	r = amdgpu_vm_bo_map(adev, bo_va, ctx_data->meta_data_gpu_addr, 0,
1165 			     sizeof(struct amdgpu_mes_ctx_meta_data),
1166 			     AMDGPU_PTE_READABLE | AMDGPU_PTE_WRITEABLE |
1167 			     AMDGPU_PTE_EXECUTABLE);
1168 
1169 	if (r) {
1170 		DRM_ERROR("failed to do bo_map on meta data, err=%d\n", r);
1171 		goto error;
1172 	}
1173 
1174 	r = amdgpu_vm_bo_update(adev, bo_va, false);
1175 	if (r) {
1176 		DRM_ERROR("failed to do vm_bo_update on meta data\n");
1177 		goto error;
1178 	}
1179 	amdgpu_sync_fence(&sync, bo_va->last_pt_update);
1180 
1181 	r = amdgpu_vm_update_pdes(adev, vm, false);
1182 	if (r) {
1183 		DRM_ERROR("failed to update pdes on meta data\n");
1184 		goto error;
1185 	}
1186 	amdgpu_sync_fence(&sync, vm->last_update);
1187 
1188 	amdgpu_sync_wait(&sync, false);
1189 	ttm_eu_backoff_reservation(&ticket, &list);
1190 
1191 	amdgpu_sync_free(&sync);
1192 	ctx_data->meta_data_va = bo_va;
1193 	return 0;
1194 
1195 error:
1196 	amdgpu_vm_bo_del(adev, bo_va);
1197 	ttm_eu_backoff_reservation(&ticket, &list);
1198 	amdgpu_sync_free(&sync);
1199 	return r;
1200 }
1201 
1202 int amdgpu_mes_ctx_unmap_meta_data(struct amdgpu_device *adev,
1203 				   struct amdgpu_mes_ctx_data *ctx_data)
1204 {
1205 	struct amdgpu_bo_va *bo_va = ctx_data->meta_data_va;
1206 	struct amdgpu_bo *bo = ctx_data->meta_data_obj;
1207 	struct amdgpu_vm *vm = bo_va->base.vm;
1208 	struct amdgpu_bo_list_entry vm_pd;
1209 	struct list_head list, duplicates;
1210 	struct dma_fence *fence = NULL;
1211 	struct ttm_validate_buffer tv;
1212 	struct ww_acquire_ctx ticket;
1213 	long r = 0;
1214 
1215 	INIT_LIST_HEAD(&list);
1216 	INIT_LIST_HEAD(&duplicates);
1217 
1218 	tv.bo = &bo->tbo;
1219 	tv.num_shared = 2;
1220 	list_add(&tv.head, &list);
1221 
1222 	amdgpu_vm_get_pd_bo(vm, &list, &vm_pd);
1223 
1224 	r = ttm_eu_reserve_buffers(&ticket, &list, false, &duplicates);
1225 	if (r) {
1226 		dev_err(adev->dev, "leaking bo va because "
1227 			"we fail to reserve bo (%ld)\n", r);
1228 		return r;
1229 	}
1230 
1231 	amdgpu_vm_bo_del(adev, bo_va);
1232 	if (!amdgpu_vm_ready(vm))
1233 		goto out_unlock;
1234 
1235 	r = dma_resv_get_singleton(bo->tbo.base.resv, DMA_RESV_USAGE_BOOKKEEP, &fence);
1236 	if (r)
1237 		goto out_unlock;
1238 	if (fence) {
1239 		amdgpu_bo_fence(bo, fence, true);
1240 		fence = NULL;
1241 	}
1242 
1243 	r = amdgpu_vm_clear_freed(adev, vm, &fence);
1244 	if (r || !fence)
1245 		goto out_unlock;
1246 
1247 	dma_fence_wait(fence, false);
1248 	amdgpu_bo_fence(bo, fence, true);
1249 	dma_fence_put(fence);
1250 
1251 out_unlock:
1252 	if (unlikely(r < 0))
1253 		dev_err(adev->dev, "failed to clear page tables (%ld)\n", r);
1254 	ttm_eu_backoff_reservation(&ticket, &list);
1255 
1256 	return r;
1257 }
1258 
1259 static int amdgpu_mes_test_create_gang_and_queues(struct amdgpu_device *adev,
1260 					  int pasid, int *gang_id,
1261 					  int queue_type, int num_queue,
1262 					  struct amdgpu_ring **added_rings,
1263 					  struct amdgpu_mes_ctx_data *ctx_data)
1264 {
1265 	struct amdgpu_ring *ring;
1266 	struct amdgpu_mes_gang_properties gprops = {0};
1267 	int r, j;
1268 
1269 	/* create a gang for the process */
1270 	gprops.priority = AMDGPU_MES_PRIORITY_LEVEL_NORMAL;
1271 	gprops.gang_quantum = adev->mes.default_gang_quantum;
1272 	gprops.inprocess_gang_priority = AMDGPU_MES_PRIORITY_LEVEL_NORMAL;
1273 	gprops.priority_level = AMDGPU_MES_PRIORITY_LEVEL_NORMAL;
1274 	gprops.global_priority_level = AMDGPU_MES_PRIORITY_LEVEL_NORMAL;
1275 
1276 	r = amdgpu_mes_add_gang(adev, pasid, &gprops, gang_id);
1277 	if (r) {
1278 		DRM_ERROR("failed to add gang\n");
1279 		return r;
1280 	}
1281 
1282 	/* create queues for the gang */
1283 	for (j = 0; j < num_queue; j++) {
1284 		r = amdgpu_mes_add_ring(adev, *gang_id, queue_type, j,
1285 					ctx_data, &ring);
1286 		if (r) {
1287 			DRM_ERROR("failed to add ring\n");
1288 			break;
1289 		}
1290 
1291 		DRM_INFO("ring %s was added\n", ring->name);
1292 		added_rings[j] = ring;
1293 	}
1294 
1295 	return 0;
1296 }
1297 
1298 static int amdgpu_mes_test_queues(struct amdgpu_ring **added_rings)
1299 {
1300 	struct amdgpu_ring *ring;
1301 	int i, r;
1302 
1303 	for (i = 0; i < AMDGPU_MES_CTX_MAX_RINGS; i++) {
1304 		ring = added_rings[i];
1305 		if (!ring)
1306 			continue;
1307 
1308 		r = amdgpu_ring_test_ring(ring);
1309 		if (r) {
1310 			DRM_DEV_ERROR(ring->adev->dev,
1311 				      "ring %s test failed (%d)\n",
1312 				      ring->name, r);
1313 			return r;
1314 		} else
1315 			DRM_INFO("ring %s test pass\n", ring->name);
1316 
1317 		r = amdgpu_ring_test_ib(ring, 1000 * 10);
1318 		if (r) {
1319 			DRM_DEV_ERROR(ring->adev->dev,
1320 				      "ring %s ib test failed (%d)\n",
1321 				      ring->name, r);
1322 			return r;
1323 		} else
1324 			DRM_INFO("ring %s ib test pass\n", ring->name);
1325 	}
1326 
1327 	return 0;
1328 }
1329 
1330 int amdgpu_mes_self_test(struct amdgpu_device *adev)
1331 {
1332 	struct amdgpu_vm *vm = NULL;
1333 	struct amdgpu_mes_ctx_data ctx_data = {0};
1334 	struct amdgpu_ring *added_rings[AMDGPU_MES_CTX_MAX_RINGS] = { NULL };
1335 	int gang_ids[3] = {0};
1336 	int queue_types[][2] = { { AMDGPU_RING_TYPE_GFX, 1 },
1337 				 { AMDGPU_RING_TYPE_COMPUTE, 1 },
1338 				 { AMDGPU_RING_TYPE_SDMA, 1} };
1339 	int i, r, pasid, k = 0;
1340 
1341 	pasid = amdgpu_pasid_alloc(16);
1342 	if (pasid < 0) {
1343 		dev_warn(adev->dev, "No more PASIDs available!");
1344 		pasid = 0;
1345 	}
1346 
1347 	vm = kzalloc(sizeof(*vm), GFP_KERNEL);
1348 	if (!vm) {
1349 		r = -ENOMEM;
1350 		goto error_pasid;
1351 	}
1352 
1353 	r = amdgpu_vm_init(adev, vm);
1354 	if (r) {
1355 		DRM_ERROR("failed to initialize vm\n");
1356 		goto error_pasid;
1357 	}
1358 
1359 	r = amdgpu_mes_ctx_alloc_meta_data(adev, &ctx_data);
1360 	if (r) {
1361 		DRM_ERROR("failed to alloc ctx meta data\n");
1362 		goto error_fini;
1363 	}
1364 
1365 	ctx_data.meta_data_gpu_addr = AMDGPU_VA_RESERVED_SIZE;
1366 	r = amdgpu_mes_ctx_map_meta_data(adev, vm, &ctx_data);
1367 	if (r) {
1368 		DRM_ERROR("failed to map ctx meta data\n");
1369 		goto error_vm;
1370 	}
1371 
1372 	r = amdgpu_mes_create_process(adev, pasid, vm);
1373 	if (r) {
1374 		DRM_ERROR("failed to create MES process\n");
1375 		goto error_vm;
1376 	}
1377 
1378 	for (i = 0; i < ARRAY_SIZE(queue_types); i++) {
1379 		/* On GFX v10.3, fw hasn't supported to map sdma queue. */
1380 		if (adev->ip_versions[GC_HWIP][0] >= IP_VERSION(10, 3, 0) &&
1381 		    adev->ip_versions[GC_HWIP][0] < IP_VERSION(11, 0, 0) &&
1382 		    queue_types[i][0] == AMDGPU_RING_TYPE_SDMA)
1383 			continue;
1384 
1385 		r = amdgpu_mes_test_create_gang_and_queues(adev, pasid,
1386 							   &gang_ids[i],
1387 							   queue_types[i][0],
1388 							   queue_types[i][1],
1389 							   &added_rings[k],
1390 							   &ctx_data);
1391 		if (r)
1392 			goto error_queues;
1393 
1394 		k += queue_types[i][1];
1395 	}
1396 
1397 	/* start ring test and ib test for MES queues */
1398 	amdgpu_mes_test_queues(added_rings);
1399 
1400 error_queues:
1401 	/* remove all queues */
1402 	for (i = 0; i < ARRAY_SIZE(added_rings); i++) {
1403 		if (!added_rings[i])
1404 			continue;
1405 		amdgpu_mes_remove_ring(adev, added_rings[i]);
1406 	}
1407 
1408 	for (i = 0; i < ARRAY_SIZE(gang_ids); i++) {
1409 		if (!gang_ids[i])
1410 			continue;
1411 		amdgpu_mes_remove_gang(adev, gang_ids[i]);
1412 	}
1413 
1414 	amdgpu_mes_destroy_process(adev, pasid);
1415 
1416 error_vm:
1417 	amdgpu_mes_ctx_unmap_meta_data(adev, &ctx_data);
1418 
1419 error_fini:
1420 	amdgpu_vm_fini(adev, vm);
1421 
1422 error_pasid:
1423 	if (pasid)
1424 		amdgpu_pasid_free(pasid);
1425 
1426 	amdgpu_mes_ctx_free_meta_data(&ctx_data);
1427 	kfree(vm);
1428 	return 0;
1429 }
1430 
1431 int amdgpu_mes_init_microcode(struct amdgpu_device *adev, int pipe)
1432 {
1433 	const struct mes_firmware_header_v1_0 *mes_hdr;
1434 	struct amdgpu_firmware_info *info;
1435 	char ucode_prefix[30];
1436 	char fw_name[40];
1437 	bool need_retry = false;
1438 	int r;
1439 
1440 	amdgpu_ucode_ip_version_decode(adev, GC_HWIP, ucode_prefix,
1441 				       sizeof(ucode_prefix));
1442 	if (adev->ip_versions[GC_HWIP][0] >= IP_VERSION(11, 0, 0)) {
1443 		snprintf(fw_name, sizeof(fw_name), "amdgpu/%s_mes%s.bin",
1444 			 ucode_prefix,
1445 			 pipe == AMDGPU_MES_SCHED_PIPE ? "_2" : "1");
1446 		need_retry = true;
1447 	} else {
1448 		snprintf(fw_name, sizeof(fw_name), "amdgpu/%s_mes%s.bin",
1449 			 ucode_prefix,
1450 			 pipe == AMDGPU_MES_SCHED_PIPE ? "" : "1");
1451 	}
1452 
1453 	r = amdgpu_ucode_request(adev, &adev->mes.fw[pipe], fw_name);
1454 	if (r && need_retry && pipe == AMDGPU_MES_SCHED_PIPE) {
1455 		snprintf(fw_name, sizeof(fw_name), "amdgpu/%s_mes.bin",
1456 			 ucode_prefix);
1457 		DRM_INFO("try to fall back to %s\n", fw_name);
1458 		r = amdgpu_ucode_request(adev, &adev->mes.fw[pipe],
1459 					 fw_name);
1460 	}
1461 
1462 	if (r)
1463 		goto out;
1464 
1465 	mes_hdr = (const struct mes_firmware_header_v1_0 *)
1466 		adev->mes.fw[pipe]->data;
1467 	adev->mes.uc_start_addr[pipe] =
1468 		le32_to_cpu(mes_hdr->mes_uc_start_addr_lo) |
1469 		((uint64_t)(le32_to_cpu(mes_hdr->mes_uc_start_addr_hi)) << 32);
1470 	adev->mes.data_start_addr[pipe] =
1471 		le32_to_cpu(mes_hdr->mes_data_start_addr_lo) |
1472 		((uint64_t)(le32_to_cpu(mes_hdr->mes_data_start_addr_hi)) << 32);
1473 
1474 	if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) {
1475 		int ucode, ucode_data;
1476 
1477 		if (pipe == AMDGPU_MES_SCHED_PIPE) {
1478 			ucode = AMDGPU_UCODE_ID_CP_MES;
1479 			ucode_data = AMDGPU_UCODE_ID_CP_MES_DATA;
1480 		} else {
1481 			ucode = AMDGPU_UCODE_ID_CP_MES1;
1482 			ucode_data = AMDGPU_UCODE_ID_CP_MES1_DATA;
1483 		}
1484 
1485 		info = &adev->firmware.ucode[ucode];
1486 		info->ucode_id = ucode;
1487 		info->fw = adev->mes.fw[pipe];
1488 		adev->firmware.fw_size +=
1489 			ALIGN(le32_to_cpu(mes_hdr->mes_ucode_size_bytes),
1490 			      PAGE_SIZE);
1491 
1492 		info = &adev->firmware.ucode[ucode_data];
1493 		info->ucode_id = ucode_data;
1494 		info->fw = adev->mes.fw[pipe];
1495 		adev->firmware.fw_size +=
1496 			ALIGN(le32_to_cpu(mes_hdr->mes_ucode_data_size_bytes),
1497 			      PAGE_SIZE);
1498 	}
1499 
1500 	return 0;
1501 out:
1502 	amdgpu_ucode_release(&adev->mes.fw[pipe]);
1503 	return r;
1504 }
1505