xref: /linux/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c (revision f145d5b3f740de05d85257acdc82f6877180f5c6)
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright 2014-2022 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/ratelimit.h>
26 #include <linux/printk.h>
27 #include <linux/slab.h>
28 #include <linux/list.h>
29 #include <linux/types.h>
30 #include <linux/bitops.h>
31 #include <linux/sched.h>
32 #include "kfd_priv.h"
33 #include "kfd_device_queue_manager.h"
34 #include "kfd_mqd_manager.h"
35 #include "cik_regs.h"
36 #include "kfd_kernel_queue.h"
37 #include "amdgpu_amdkfd.h"
38 #include "amdgpu_reset.h"
39 #include "amdgpu_sdma.h"
40 #include "amdgpu_ring.h"
41 #include "amdgpu_mes.h"
42 #include "kfd_debug.h"
43 
44 /* Size of the per-pipe EOP queue */
45 #define CIK_HPD_EOP_BYTES_LOG2 11
46 #define CIK_HPD_EOP_BYTES (1U << CIK_HPD_EOP_BYTES_LOG2)
47 /* See unmap_queues_cpsch() */
48 #define USE_DEFAULT_GRACE_PERIOD 0xffffffff
49 
50 static int set_pasid_vmid_mapping(struct device_queue_manager *dqm,
51 				  u32 pasid, unsigned int vmid);
52 
53 static int execute_queues_cpsch(struct device_queue_manager *dqm,
54 				enum kfd_unmap_queues_filter filter,
55 				uint32_t filter_param,
56 				uint32_t grace_period);
57 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
58 				enum kfd_unmap_queues_filter filter,
59 				uint32_t filter_param,
60 				uint32_t grace_period,
61 				bool reset);
62 
63 static int map_queues_cpsch(struct device_queue_manager *dqm);
64 
65 static void deallocate_sdma_queue(struct device_queue_manager *dqm,
66 				struct queue *q);
67 
68 static inline void deallocate_hqd(struct device_queue_manager *dqm,
69 				struct queue *q);
70 static int allocate_hqd(struct device_queue_manager *dqm, struct queue *q);
71 static int allocate_sdma_queue(struct device_queue_manager *dqm,
72 				struct queue *q, const uint32_t *restore_sdma_id);
73 
74 static int reset_queues_on_hws_hang(struct device_queue_manager *dqm, bool is_sdma);
75 static struct queue *find_queue_by_doorbell_offset(struct device_queue_manager *dqm,
76 						   u32 doorbell_offset);
77 static void set_queue_as_reset(struct device_queue_manager *dqm, struct queue *q,
78 			       struct qcm_process_device *qpd);
79 static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q);
80 
81 static inline
82 enum KFD_MQD_TYPE get_mqd_type_from_queue_type(enum kfd_queue_type type)
83 {
84 	if (type == KFD_QUEUE_TYPE_SDMA || type == KFD_QUEUE_TYPE_SDMA_XGMI)
85 		return KFD_MQD_TYPE_SDMA;
86 	return KFD_MQD_TYPE_CP;
87 }
88 
89 static bool is_pipe_enabled(struct device_queue_manager *dqm, int mec, int pipe)
90 {
91 	int i;
92 	int pipe_offset = (mec * dqm->dev->kfd->shared_resources.num_pipe_per_mec
93 		+ pipe) * dqm->dev->kfd->shared_resources.num_queue_per_pipe;
94 
95 	/* queue is available for KFD usage if bit is 1 */
96 	for (i = 0; i <  dqm->dev->kfd->shared_resources.num_queue_per_pipe; ++i)
97 		if (test_bit(pipe_offset + i,
98 			      dqm->dev->kfd->shared_resources.cp_queue_bitmap))
99 			return true;
100 	return false;
101 }
102 
103 unsigned int get_cp_queues_num(struct device_queue_manager *dqm)
104 {
105 	return bitmap_weight(dqm->dev->kfd->shared_resources.cp_queue_bitmap,
106 				AMDGPU_MAX_QUEUES);
107 }
108 
109 unsigned int get_queues_per_pipe(struct device_queue_manager *dqm)
110 {
111 	return dqm->dev->kfd->shared_resources.num_queue_per_pipe;
112 }
113 
114 unsigned int get_pipes_per_mec(struct device_queue_manager *dqm)
115 {
116 	return dqm->dev->kfd->shared_resources.num_pipe_per_mec;
117 }
118 
119 static unsigned int get_num_all_sdma_engines(struct device_queue_manager *dqm)
120 {
121 	return kfd_get_num_sdma_engines(dqm->dev) +
122 		kfd_get_num_xgmi_sdma_engines(dqm->dev);
123 }
124 
125 unsigned int get_num_sdma_queues(struct device_queue_manager *dqm)
126 {
127 	return kfd_get_num_sdma_engines(dqm->dev) *
128 		dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
129 }
130 
131 unsigned int get_num_xgmi_sdma_queues(struct device_queue_manager *dqm)
132 {
133 	return kfd_get_num_xgmi_sdma_engines(dqm->dev) *
134 		dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
135 }
136 
137 static void init_sdma_bitmaps(struct device_queue_manager *dqm)
138 {
139 	bitmap_zero(dqm->sdma_bitmap, KFD_MAX_SDMA_QUEUES);
140 	bitmap_set(dqm->sdma_bitmap, 0, get_num_sdma_queues(dqm));
141 
142 	bitmap_zero(dqm->xgmi_sdma_bitmap, KFD_MAX_SDMA_QUEUES);
143 	bitmap_set(dqm->xgmi_sdma_bitmap, 0, get_num_xgmi_sdma_queues(dqm));
144 
145 	/* Mask out the reserved queues */
146 	bitmap_clear(dqm->sdma_bitmap, 0, kfd_get_num_sdma_engines(dqm->dev) *
147 			dqm->dev->kfd->device_info.num_reserved_sdma_queues_per_engine);
148 	bitmap_clear(dqm->xgmi_sdma_bitmap, 0, kfd_get_num_xgmi_sdma_engines(dqm->dev) *
149 			dqm->dev->kfd->device_info.num_reserved_sdma_queues_per_engine);
150 }
151 
152 void program_sh_mem_settings(struct device_queue_manager *dqm,
153 					struct qcm_process_device *qpd)
154 {
155 	uint32_t xcc_mask = dqm->dev->xcc_mask;
156 	int xcc_id;
157 
158 	for_each_inst(xcc_id, xcc_mask)
159 		dqm->dev->kfd2kgd->program_sh_mem_settings(
160 			dqm->dev->adev, qpd->vmid, qpd->sh_mem_config,
161 			qpd->sh_mem_ape1_base, qpd->sh_mem_ape1_limit,
162 			qpd->sh_mem_bases, xcc_id);
163 }
164 
165 static void kfd_hws_hang(struct device_queue_manager *dqm)
166 {
167 	struct device_process_node *cur;
168 	struct qcm_process_device *qpd;
169 	struct queue *q;
170 
171 	/* Mark all device queues as reset. */
172 	list_for_each_entry(cur, &dqm->queues, list) {
173 		qpd = cur->qpd;
174 		list_for_each_entry(q, &qpd->queues_list, list) {
175 			struct kfd_process_device *pdd = qpd_to_pdd(qpd);
176 
177 			pdd->has_reset_queue = true;
178 		}
179 	}
180 
181 	/*
182 	 * Issue a GPU reset if HWS is unresponsive
183 	 */
184 	amdgpu_amdkfd_gpu_reset(dqm->dev->adev);
185 }
186 
187 static int convert_to_amdgpu_ring_type(int queue_type)
188 {
189 	int amdgpu_ring_type;
190 
191 	switch (queue_type) {
192 	case KFD_QUEUE_TYPE_COMPUTE:
193 		amdgpu_ring_type = AMDGPU_RING_TYPE_COMPUTE;
194 		break;
195 	case KFD_QUEUE_TYPE_SDMA:
196 		amdgpu_ring_type = AMDGPU_RING_TYPE_SDMA;
197 		break;
198 	default:
199 		WARN(1, "Invalid queue type %d", queue_type);
200 		amdgpu_ring_type = -EINVAL;
201 		break;
202 	}
203 
204 	return amdgpu_ring_type;
205 }
206 
207 static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
208 			 struct qcm_process_device *qpd)
209 {
210 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
211 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
212 	struct mes_add_queue_input queue_input;
213 	int r, queue_type;
214 	uint64_t wptr_addr_off;
215 
216 	if (!dqm->sched_running || dqm->sched_halt)
217 		return 0;
218 	if (!down_read_trylock(&adev->reset_domain->sem))
219 		return -EIO;
220 
221 	memset(&queue_input, 0x0, sizeof(struct mes_add_queue_input));
222 	queue_input.process_id = pdd->pasid;
223 	queue_input.page_table_base_addr =  qpd->page_table_base;
224 	queue_input.process_va_start = 0;
225 	queue_input.process_va_end = adev->vm_manager.max_pfn - 1;
226 	/* MES unit for quantum is 100ns */
227 	queue_input.process_quantum = KFD_MES_PROCESS_QUANTUM;  /* Equivalent to 10ms. */
228 	queue_input.process_context_addr = pdd->proc_ctx_gpu_addr;
229 	queue_input.process_context_array_index = pdd->proc_ctx_array_index;
230 	queue_input.gang_quantum = KFD_MES_GANG_QUANTUM; /* Equivalent to 1ms */
231 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
232 	queue_input.gang_context_array_index = q->gang_ctx_array_index;
233 	queue_input.inprocess_gang_priority = q->properties.priority;
234 	queue_input.gang_global_priority_level =
235 					AMDGPU_MES_PRIORITY_LEVEL_NORMAL;
236 	queue_input.doorbell_offset = q->properties.doorbell_off;
237 	queue_input.mqd_addr = q->gart_mqd_addr;
238 	queue_input.wptr_addr = (uint64_t)q->properties.write_ptr;
239 
240 	wptr_addr_off = (uint64_t)q->properties.write_ptr & (PAGE_SIZE - 1);
241 	queue_input.wptr_mc_addr = amdgpu_bo_gpu_offset(q->properties.wptr_bo) + wptr_addr_off;
242 
243 	queue_input.is_kfd_process = 1;
244 	queue_input.is_aql_queue = (q->properties.format == KFD_QUEUE_FORMAT_AQL);
245 	queue_input.queue_size = q->properties.queue_size >> 2;
246 
247 	queue_input.paging = false;
248 	queue_input.tba_addr = qpd->tba_addr;
249 	queue_input.tma_addr = qpd->tma_addr;
250 	queue_input.trap_en = !kfd_dbg_has_cwsr_workaround(q->device);
251 	queue_input.skip_process_ctx_clear =
252 		qpd->pqm->process->runtime_info.runtime_state == DEBUG_RUNTIME_STATE_ENABLED &&
253 						(qpd->pqm->process->debug_trap_enabled ||
254 						 kfd_dbg_has_ttmps_always_setup(q->device));
255 
256 	queue_type = convert_to_amdgpu_ring_type(q->properties.type);
257 	if (queue_type < 0) {
258 		dev_err(adev->dev, "Queue type not supported with MES, queue:%d\n",
259 			q->properties.type);
260 		up_read(&adev->reset_domain->sem);
261 		return -EINVAL;
262 	}
263 	queue_input.queue_type = (uint32_t)queue_type;
264 
265 	queue_input.exclusively_scheduled = q->properties.is_gws;
266 	queue_input.sh_mem_config_data = qpd->sh_mem_config;
267 	queue_input.vm_cntx_cntl = qpd->vm_cntx_cntl;
268 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
269 
270 	amdgpu_mes_lock(&adev->mes);
271 	r = adev->mes.funcs->add_hw_queue(&adev->mes, &queue_input);
272 	amdgpu_mes_unlock(&adev->mes);
273 	up_read(&adev->reset_domain->sem);
274 	if (r) {
275 		dev_err(adev->dev, "failed to add hardware queue to MES, doorbell=0x%x\n",
276 			q->properties.doorbell_off);
277 		dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
278 		kfd_hws_hang(dqm);
279 	}
280 
281 	return r;
282 }
283 
284 static int remove_queue_mes_on_reset_option(struct device_queue_manager *dqm, struct queue *q,
285 					    struct qcm_process_device *qpd,
286 					    bool is_for_reset,
287 					    bool flush_mes_queue)
288 {
289 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
290 	int r;
291 	struct mes_remove_queue_input queue_input;
292 
293 	/* queue was already removed during reset */
294 	if (q->properties.is_reset)
295 		return 0;
296 
297 	if (!dqm->sched_running || dqm->sched_halt)
298 		return 0;
299 	if (!down_read_trylock(&adev->reset_domain->sem))
300 		return -EIO;
301 
302 	memset(&queue_input, 0x0, sizeof(struct mes_remove_queue_input));
303 	queue_input.doorbell_offset = q->properties.doorbell_off;
304 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
305 	queue_input.queue_type = convert_to_amdgpu_ring_type(q->properties.type);
306 	queue_input.remove_queue_after_reset = flush_mes_queue;
307 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
308 	queue_input.gang_context_array_index = q->gang_ctx_array_index;
309 
310 	amdgpu_mes_lock(&adev->mes);
311 	r = adev->mes.funcs->remove_hw_queue(&adev->mes, &queue_input);
312 	amdgpu_mes_unlock(&adev->mes);
313 	up_read(&adev->reset_domain->sem);
314 
315 	/* If is_for_reset set, it is a mes internal cleanup */
316 	if (!r || is_for_reset)
317 		return r;
318 
319 	/* remove_hw_queue failure indicates a queue hang. reset the queue */
320 	r = reset_queues_mes(dqm, q);
321 	if (r && amdgpu_gpu_recovery) {
322 		dev_err(adev->dev, "failed to remove queue from MES, doorbell=0x%x\n",
323 			q->properties.doorbell_off);
324 		dev_err(adev->dev, "MES might be in unrecoverable state, issue a GPU reset\n");
325 		kfd_hws_hang(dqm);
326 	}
327 
328 	return r;
329 }
330 
331 static void set_perfcount(struct device_queue_manager *dqm, int enable)
332 {
333 	struct device_process_node *cur;
334 	struct qcm_process_device *qpd;
335 	struct queue *q;
336 	struct mqd_update_info minfo = { 0 };
337 
338 	if (!dqm)
339 		return;
340 
341 	minfo.update_flag = (enable == 1 ? UPDATE_FLAG_PERFCOUNT_ENABLE :
342 						 UPDATE_FLAG_PERFCOUNT_DISABLE);
343 	dqm_lock(dqm);
344 	list_for_each_entry(cur, &dqm->queues, list) {
345 		qpd = cur->qpd;
346 		list_for_each_entry(q, &qpd->queues_list, list) {
347 			pqm_update_mqd(qpd->pqm, q->properties.queue_id,
348 						&minfo);
349 		}
350 	}
351 	dqm_unlock(dqm);
352 }
353 
354 static int remove_queue_mes(struct device_queue_manager *dqm, struct queue *q,
355 			    struct qcm_process_device *qpd)
356 {
357 	return remove_queue_mes_on_reset_option(dqm, q, qpd, false, false);
358 }
359 
360 static int remove_all_kfd_queues_mes(struct device_queue_manager *dqm)
361 {
362 	struct device_process_node *cur;
363 	struct device *dev = dqm->dev->adev->dev;
364 	struct qcm_process_device *qpd;
365 	struct queue *q;
366 	int retval = 0;
367 
368 	list_for_each_entry(cur, &dqm->queues, list) {
369 		qpd = cur->qpd;
370 		list_for_each_entry(q, &qpd->queues_list, list) {
371 			if (q->properties.is_active) {
372 				retval = remove_queue_mes(dqm, q, qpd);
373 				if (retval) {
374 					dev_err(dev, "%s: Failed to remove queue %d for dev %d",
375 						__func__,
376 						q->properties.queue_id,
377 						dqm->dev->id);
378 					return retval;
379 				}
380 			}
381 		}
382 	}
383 
384 	return retval;
385 }
386 
387 static int add_all_kfd_queues_mes(struct device_queue_manager *dqm)
388 {
389 	struct device_process_node *cur;
390 	struct device *dev = dqm->dev->adev->dev;
391 	struct qcm_process_device *qpd;
392 	struct queue *q;
393 	int retval = 0;
394 
395 	list_for_each_entry(cur, &dqm->queues, list) {
396 		qpd = cur->qpd;
397 		list_for_each_entry(q, &qpd->queues_list, list) {
398 			if (!q->properties.is_active)
399 				continue;
400 			retval = add_queue_mes(dqm, q, qpd);
401 			if (retval) {
402 				dev_err(dev, "%s: Failed to add queue %d for dev %d",
403 					__func__,
404 					q->properties.queue_id,
405 					dqm->dev->id);
406 				return retval;
407 			}
408 		}
409 	}
410 
411 	return retval;
412 }
413 
414 static int reset_queue_mes(struct device_queue_manager *dqm, struct queue *q,
415 			   int queue_type, int pipe, int queue, unsigned int db)
416 {
417 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
418 	struct kfd_process_device *pdd;
419 	bool use_mmio = adev->gfx.mec.use_mmio_for_reset;
420 	int r;
421 
422 	pdd = kfd_get_process_device_data(q->device, q->process);
423 	if (!pdd)
424 		return -ENODEV;
425 
426 	if (use_mmio)
427 		r = amdgpu_mes_reset_queue_mmio(adev, queue_type, 0, 1, pipe, queue,
428 						ffs(dqm->dev->xcc_mask) - 1);
429 	else
430 		r = amdgpu_mes_reset_user_queue(adev, queue_type, db,
431 						ffs(dqm->dev->xcc_mask) - 1);
432 	if (r)
433 		return r;
434 	/* Proceed remove_queue with reset=true */
435 	remove_queue_mes_on_reset_option(dqm, q, &pdd->qpd, true, true);
436 	set_queue_as_reset(dqm, q, &pdd->qpd);
437 	return 0;
438 }
439 
440 int kfd_reset_queue_mes(struct device_queue_manager *dqm, int queue_type,
441 			int pipe, int queue, unsigned int db)
442 {
443 	struct queue *q;
444 
445 	q = find_queue_by_doorbell_offset(dqm, db);
446 	if (!q)
447 		return 0;
448 	return reset_queue_mes(dqm, q, queue_type, pipe, queue, db);
449 }
450 
451 static int reset_queues_mes(struct device_queue_manager *dqm, struct queue *q)
452 {
453 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
454 	struct drm_wedge_task_info *info = NULL;
455 	struct amdgpu_task_info *ti = NULL;
456 	struct kfd_process_device *pdd;
457 	unsigned int num_hung = 0;
458 	int r = 0;
459 	struct mes_remove_queue_input queue_input;
460 
461 	if (!amdgpu_mes_queue_reset_by_mes_supported(adev)) {
462 		r = -ENOTRECOVERABLE;
463 		goto fail;
464 	}
465 
466 	/* reset should be used only in dqm locked queue reset */
467 	if (WARN_ON(dqm->detect_hang_count > 0))
468 		return 0;
469 
470 	if (!amdgpu_gpu_recovery) {
471 		r = -ENOTRECOVERABLE;
472 		goto fail;
473 	}
474 
475 	memset(&queue_input, 0x0, sizeof(struct mes_remove_queue_input));
476 	queue_input.doorbell_offset = q->properties.doorbell_off;
477 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
478 	queue_input.queue_type = convert_to_amdgpu_ring_type(q->properties.type);
479 	queue_input.remove_queue_after_reset = false;
480 	queue_input.xcc_id = ffs(dqm->dev->xcc_mask) - 1;
481 	/* pass the known bad queue info to the reset function */
482 	r = amdgpu_gfx_reset_mes_compute(adev, NULL, NULL, NULL, &num_hung, &queue_input);
483 	if (r)
484 		goto fail;
485 	pdd = kfd_get_process_device_data(q->device, q->process);
486 	if (pdd) {
487 		ti = amdgpu_vm_get_task_info_pasid(adev, pdd->pasid);
488 		if (ti) {
489 			amdgpu_vm_print_task_info(adev, ti);
490 			info = &ti->task;
491 		}
492 	}
493 
494 	dqm->detect_hang_count = num_hung;
495 	/* When MES doesn't detect any queue hang, no reset happens. Don't signal reset
496 	 * event.
497 	 */
498 	if (dqm->detect_hang_count) {
499 		kfd_signal_reset_event(dqm->dev);
500 		if (pdd && pdd->has_reset_queue) {
501 			atomic_inc(&adev->gpu_reset_counter);
502 			drm_dev_wedged_event(adev_to_drm(adev), DRM_WEDGE_RECOVERY_NONE, info);
503 		}
504 	}
505 	amdgpu_vm_put_task_info(ti);
506 
507 fail:
508 	dqm->detect_hang_count = 0;
509 	return r;
510 }
511 
512 static void increment_queue_count(struct device_queue_manager *dqm,
513 				  struct qcm_process_device *qpd,
514 				  struct queue *q)
515 {
516 	dqm->active_queue_count++;
517 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE)
518 		dqm->active_cp_queue_count++;
519 
520 	if (q->properties.is_gws) {
521 		dqm->gws_queue_count++;
522 		qpd->mapped_gws_queue = true;
523 	}
524 }
525 
526 static void decrement_queue_count(struct device_queue_manager *dqm,
527 				  struct qcm_process_device *qpd,
528 				  struct queue *q)
529 {
530 	dqm->active_queue_count--;
531 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE)
532 		dqm->active_cp_queue_count--;
533 
534 	if (q->properties.is_gws) {
535 		dqm->gws_queue_count--;
536 		qpd->mapped_gws_queue = false;
537 	}
538 }
539 
540 /*
541  * Allocate a doorbell ID to this queue.
542  * If doorbell_id is passed in, make sure requested ID is valid then allocate it.
543  */
544 static int allocate_doorbell(struct qcm_process_device *qpd,
545 			     struct queue *q,
546 			     uint32_t const *restore_id)
547 {
548 	struct kfd_node *dev = qpd->dqm->dev;
549 
550 	if (!KFD_IS_SOC15(dev)) {
551 		/* On pre-SOC15 chips we need to use the queue ID to
552 		 * preserve the user mode ABI.
553 		 */
554 
555 		if (restore_id && *restore_id != q->properties.queue_id)
556 			return -EINVAL;
557 
558 		q->doorbell_id = q->properties.queue_id;
559 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
560 			q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
561 		/* For SDMA queues on SOC15 with 8-byte doorbell, use static
562 		 * doorbell assignments based on the engine and queue id.
563 		 * The doobell index distance between RLC (2*i) and (2*i+1)
564 		 * for a SDMA engine is 512.
565 		 */
566 
567 		uint32_t *idx_offset = dev->kfd->shared_resources.sdma_doorbell_idx;
568 
569 		/*
570 		 * q->properties.sdma_engine_id corresponds to the virtual
571 		 * sdma engine number. However, for doorbell allocation,
572 		 * we need the physical sdma engine id in order to get the
573 		 * correct doorbell offset.
574 		 */
575 		u32 engine_base = idx_offset[dev->node_id *
576 					     get_num_all_sdma_engines(qpd->dqm) +
577 					     q->properties.sdma_engine_id];
578 		u32 valid_id;
579 
580 		/*
581 		 * With the aqua_vanjaram doorbell layout, a shader doorbell
582 		 * write whose 32-byte block starts in the previous engine's
583 		 * range rings that engine instead. Engine ranges are 10
584 		 * indices apart (sdma_doorbell_range = 20 dwords, halved for
585 		 * 8-byte doorbells, in aqua_vanjaram_doorbell_index_init()),
586 		 * which puts odd engines 2 indices into a shared block.
587 		 * Aligning costs at most 2 indices, and 8 queues per engine use
588 		 * only 4 of the 10, so the aligned base stays in range. The
589 		 * 512-index mirror offset keeps the alignment.
590 		 */
591 		if (KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 3) ||
592 		    KFD_GC_VERSION(dev) == IP_VERSION(9, 4, 4) ||
593 		    KFD_GC_VERSION(dev) == IP_VERSION(9, 5, 0))
594 			engine_base = ALIGN(engine_base,
595 					    KFD_SDMA_SHADER_DOORBELL_GRANULARITY);
596 
597 		valid_id = engine_base +
598 			   (q->properties.sdma_queue_id & 1) *
599 			   KFD_QUEUE_DOORBELL_MIRROR_OFFSET +
600 			   (q->properties.sdma_queue_id >> 1);
601 
602 		if (restore_id && *restore_id != valid_id)
603 			return -EINVAL;
604 		q->doorbell_id = valid_id;
605 	} else {
606 		/* For CP queues on SOC15 */
607 		if (restore_id) {
608 			if (*restore_id >= KFD_MAX_NUM_OF_QUEUES_PER_PROCESS)
609 				return -EINVAL;
610 
611 			/* make sure that ID is free  */
612 			if (__test_and_set_bit(*restore_id, qpd->doorbell_bitmap))
613 				return -EINVAL;
614 
615 			q->doorbell_id = *restore_id;
616 		} else {
617 			/* or reserve a free doorbell ID */
618 			unsigned int found;
619 
620 			found = find_first_zero_bit(qpd->doorbell_bitmap,
621 						    KFD_MAX_NUM_OF_QUEUES_PER_PROCESS);
622 			if (found >= KFD_MAX_NUM_OF_QUEUES_PER_PROCESS) {
623 				pr_debug("No doorbells available");
624 				return -EBUSY;
625 			}
626 			set_bit(found, qpd->doorbell_bitmap);
627 			q->doorbell_id = found;
628 		}
629 	}
630 
631 	q->properties.doorbell_off = amdgpu_doorbell_index_on_bar(dev->adev,
632 								  qpd->proc_doorbells,
633 								  q->doorbell_id,
634 								  dev->kfd->device_info.doorbell_size);
635 	return 0;
636 }
637 
638 static void deallocate_doorbell(struct qcm_process_device *qpd,
639 				struct queue *q)
640 {
641 	unsigned int old;
642 	struct kfd_node *dev = qpd->dqm->dev;
643 
644 	if (!KFD_IS_SOC15(dev) ||
645 	    q->properties.type == KFD_QUEUE_TYPE_SDMA ||
646 	    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
647 		return;
648 
649 	old = test_and_clear_bit(q->doorbell_id, qpd->doorbell_bitmap);
650 	WARN_ON(!old);
651 }
652 
653 static void program_trap_handler_settings(struct device_queue_manager *dqm,
654 				struct qcm_process_device *qpd)
655 {
656 	uint32_t xcc_mask = dqm->dev->xcc_mask;
657 	int xcc_id;
658 
659 	if (dqm->dev->kfd2kgd->program_trap_handler_settings)
660 		for_each_inst(xcc_id, xcc_mask)
661 			dqm->dev->kfd2kgd->program_trap_handler_settings(
662 				dqm->dev->adev, qpd->vmid, qpd->tba_addr,
663 				qpd->tma_addr, xcc_id);
664 }
665 
666 static int allocate_vmid(struct device_queue_manager *dqm,
667 			struct qcm_process_device *qpd,
668 			struct queue *q)
669 {
670 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
671 	struct device *dev = dqm->dev->adev->dev;
672 	int allocated_vmid = -1, i;
673 
674 	for (i = dqm->dev->vm_info.first_vmid_kfd;
675 			i <= dqm->dev->vm_info.last_vmid_kfd; i++) {
676 		if (!dqm->vmid_pasid[i]) {
677 			allocated_vmid = i;
678 			break;
679 		}
680 	}
681 
682 	if (allocated_vmid < 0) {
683 		dev_err(dev, "no more vmid to allocate\n");
684 		return -ENOSPC;
685 	}
686 
687 	pr_debug("vmid allocated: %d\n", allocated_vmid);
688 
689 	dqm->vmid_pasid[allocated_vmid] = pdd->pasid;
690 
691 	set_pasid_vmid_mapping(dqm, pdd->pasid, allocated_vmid);
692 
693 	qpd->vmid = allocated_vmid;
694 	q->properties.vmid = allocated_vmid;
695 
696 	program_sh_mem_settings(dqm, qpd);
697 
698 	if (KFD_IS_SOC15(dqm->dev) && dqm->dev->kfd->cwsr_enabled)
699 		program_trap_handler_settings(dqm, qpd);
700 
701 	/* qpd->page_table_base is set earlier when register_process()
702 	 * is called, i.e. when the first queue is created.
703 	 */
704 	dqm->dev->kfd2kgd->set_vm_context_page_table_base(dqm->dev->adev,
705 			qpd->vmid,
706 			qpd->page_table_base);
707 	/* invalidate the VM context after pasid and vmid mapping is set up */
708 	kfd_flush_tlb(qpd_to_pdd(qpd));
709 
710 	if (dqm->dev->kfd2kgd->set_scratch_backing_va)
711 		dqm->dev->kfd2kgd->set_scratch_backing_va(dqm->dev->adev,
712 				qpd->sh_hidden_private_base, qpd->vmid);
713 
714 	return 0;
715 }
716 
717 static int flush_texture_cache_nocpsch(struct kfd_node *kdev,
718 				struct qcm_process_device *qpd)
719 {
720 	const struct packet_manager_funcs *pmf = qpd->dqm->packet_mgr.pmf;
721 	int ret;
722 
723 	if (!qpd->ib_kaddr)
724 		return -ENOMEM;
725 
726 	ret = pmf->release_mem(qpd->ib_base, (uint32_t *)qpd->ib_kaddr);
727 	if (ret)
728 		return ret;
729 
730 	return amdgpu_amdkfd_submit_ib(kdev->adev, KGD_ENGINE_MEC1, qpd->vmid,
731 				qpd->ib_base, (uint32_t *)qpd->ib_kaddr,
732 				pmf->release_mem_size / sizeof(uint32_t));
733 }
734 
735 static void deallocate_vmid(struct device_queue_manager *dqm,
736 				struct qcm_process_device *qpd,
737 				struct queue *q)
738 {
739 	struct device *dev = dqm->dev->adev->dev;
740 
741 	/* On GFX v7, CP doesn't flush TC at dequeue */
742 	if (q->device->adev->asic_type == CHIP_HAWAII)
743 		if (flush_texture_cache_nocpsch(q->device, qpd))
744 			dev_err(dev, "Failed to flush TC\n");
745 
746 	kfd_flush_tlb(qpd_to_pdd(qpd));
747 
748 	/* Release the vmid mapping */
749 	set_pasid_vmid_mapping(dqm, 0, qpd->vmid);
750 	dqm->vmid_pasid[qpd->vmid] = 0;
751 
752 	qpd->vmid = 0;
753 	q->properties.vmid = 0;
754 }
755 
756 static int create_queue_nocpsch(struct device_queue_manager *dqm,
757 				struct queue *q,
758 				struct qcm_process_device *qpd,
759 				const struct kfd_criu_queue_priv_data *qd,
760 				const void *restore_mqd, const void *restore_ctl_stack)
761 {
762 	struct mqd_manager *mqd_mgr;
763 	int retval;
764 
765 	dqm_lock(dqm);
766 
767 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
768 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
769 				dqm->total_queue_count);
770 		retval = -EPERM;
771 		goto out_unlock;
772 	}
773 
774 	if (list_empty(&qpd->queues_list)) {
775 		retval = allocate_vmid(dqm, qpd, q);
776 		if (retval)
777 			goto out_unlock;
778 	}
779 	q->properties.vmid = qpd->vmid;
780 	/*
781 	 * Eviction state logic: mark all queues as evicted, even ones
782 	 * not currently active. Restoring inactive queues later only
783 	 * updates the is_evicted flag but is a no-op otherwise.
784 	 */
785 	q->properties.is_evicted = !!qpd->evicted;
786 
787 	q->properties.tba_addr = qpd->tba_addr;
788 	q->properties.tma_addr = qpd->tma_addr;
789 
790 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
791 			q->properties.type)];
792 	if (qd && !mqd_mgr->restore_mqd) {
793 		pr_debug("restore_mqd not implemented for queue type %d\n",
794 			 q->properties.type);
795 		retval = -EOPNOTSUPP;
796 		goto deallocate_vmid;
797 	}
798 
799 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE) {
800 		retval = allocate_hqd(dqm, q);
801 		if (retval)
802 			goto deallocate_vmid;
803 		pr_debug("Loading mqd to hqd on pipe %d, queue %d\n",
804 			q->pipe, q->queue);
805 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
806 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
807 		retval = allocate_sdma_queue(dqm, q, qd ? &qd->sdma_id : NULL);
808 		if (retval)
809 			goto deallocate_vmid;
810 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
811 	}
812 
813 	retval = allocate_doorbell(qpd, q, qd ? &qd->doorbell_id : NULL);
814 	if (retval)
815 		goto out_deallocate_hqd;
816 
817 	/* Temporarily release dqm lock to avoid a circular lock dependency */
818 	dqm_unlock(dqm);
819 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr, &q->properties);
820 	dqm_lock(dqm);
821 
822 	if (!q->mqd_mem_obj) {
823 		retval = -ENOMEM;
824 		goto out_deallocate_doorbell;
825 	}
826 
827 	if (qd)
828 		mqd_mgr->restore_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj, &q->gart_mqd_addr,
829 				     &q->properties, restore_mqd, restore_ctl_stack,
830 				     qd->ctl_stack_size);
831 	else
832 		mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
833 					&q->gart_mqd_addr, &q->properties);
834 
835 	if (q->properties.is_active) {
836 		if (!dqm->sched_running) {
837 			WARN_ONCE(1, "Load non-HWS mqd while stopped\n");
838 			goto add_queue_to_list;
839 		}
840 
841 		if (WARN(q->process->mm != current->mm,
842 					"should only run in user thread"))
843 			retval = -EFAULT;
844 		else
845 			retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd, q->pipe,
846 					q->queue, &q->properties, current->mm);
847 		if (retval)
848 			goto out_free_mqd;
849 	}
850 
851 add_queue_to_list:
852 	list_add(&q->list, &qpd->queues_list);
853 	qpd->queue_count++;
854 	if (q->properties.is_active)
855 		increment_queue_count(dqm, qpd, q);
856 
857 	/*
858 	 * Unconditionally increment this counter, regardless of the queue's
859 	 * type or whether the queue is active.
860 	 */
861 	dqm->total_queue_count++;
862 	pr_debug("Total of %d queues are accountable so far\n",
863 			dqm->total_queue_count);
864 	goto out_unlock;
865 
866 out_free_mqd:
867 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
868 out_deallocate_doorbell:
869 	deallocate_doorbell(qpd, q);
870 out_deallocate_hqd:
871 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE)
872 		deallocate_hqd(dqm, q);
873 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
874 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
875 		deallocate_sdma_queue(dqm, q);
876 deallocate_vmid:
877 	if (list_empty(&qpd->queues_list))
878 		deallocate_vmid(dqm, qpd, q);
879 out_unlock:
880 	dqm_unlock(dqm);
881 	return retval;
882 }
883 
884 static int allocate_hqd(struct device_queue_manager *dqm, struct queue *q)
885 {
886 	bool set;
887 	int pipe, bit, i;
888 
889 	set = false;
890 
891 	for (pipe = dqm->next_pipe_to_allocate, i = 0;
892 			i < get_pipes_per_mec(dqm);
893 			pipe = ((pipe + 1) % get_pipes_per_mec(dqm)), ++i) {
894 
895 		if (!is_pipe_enabled(dqm, 0, pipe))
896 			continue;
897 
898 		if (dqm->allocated_queues[pipe] != 0) {
899 			bit = ffs(dqm->allocated_queues[pipe]) - 1;
900 			dqm->allocated_queues[pipe] &= ~(1 << bit);
901 			q->pipe = pipe;
902 			q->queue = bit;
903 			set = true;
904 			break;
905 		}
906 	}
907 
908 	if (!set)
909 		return -EBUSY;
910 
911 	pr_debug("hqd slot - pipe %d, queue %d\n", q->pipe, q->queue);
912 	/* horizontal hqd allocation */
913 	dqm->next_pipe_to_allocate = (pipe + 1) % get_pipes_per_mec(dqm);
914 
915 	return 0;
916 }
917 
918 static inline void deallocate_hqd(struct device_queue_manager *dqm,
919 				struct queue *q)
920 {
921 	dqm->allocated_queues[q->pipe] |= (1 << q->queue);
922 }
923 
924 #define SQ_IND_CMD_CMD_KILL		0x00000003
925 #define SQ_IND_CMD_MODE_BROADCAST	0x00000001
926 
927 static int dbgdev_wave_reset_wavefronts(struct kfd_node *dev, struct kfd_process *p)
928 {
929 	int status = 0;
930 	unsigned int vmid;
931 	uint16_t queried_pasid;
932 	union SQ_CMD_BITS reg_sq_cmd;
933 	union GRBM_GFX_INDEX_BITS reg_gfx_index;
934 	struct kfd_process_device *pdd;
935 	int first_vmid_to_scan = dev->vm_info.first_vmid_kfd;
936 	int last_vmid_to_scan = dev->vm_info.last_vmid_kfd;
937 	uint32_t xcc_mask = dev->xcc_mask;
938 	int xcc_id;
939 
940 	reg_sq_cmd.u32All = 0;
941 	reg_gfx_index.u32All = 0;
942 
943 	pr_debug("Killing all process wavefronts\n");
944 
945 	if (!dev->kfd2kgd->get_atc_vmid_pasid_mapping_info) {
946 		dev_err(dev->adev->dev, "no vmid pasid mapping supported\n");
947 		return -EOPNOTSUPP;
948 	}
949 
950 	/* taking the VMID for that process on the safe way using PDD */
951 	pdd = kfd_get_process_device_data(dev, p);
952 	if (!pdd)
953 		return -EFAULT;
954 
955 	/* Scan all registers in the range ATC_VMID8_PASID_MAPPING ..
956 	 * ATC_VMID15_PASID_MAPPING
957 	 * to check which VMID the current process is mapped to.
958 	 */
959 
960 	for (vmid = first_vmid_to_scan; vmid <= last_vmid_to_scan; vmid++) {
961 		status = dev->kfd2kgd->get_atc_vmid_pasid_mapping_info
962 				(dev->adev, vmid, &queried_pasid);
963 
964 		if (status && queried_pasid == pdd->pasid) {
965 			pr_debug("Killing wave fronts of vmid %d and process pid %d\n",
966 					vmid, p->lead_thread->pid);
967 			break;
968 		}
969 	}
970 
971 	if (vmid > last_vmid_to_scan) {
972 		dev_err(dev->adev->dev, "Didn't find vmid for process pid %d\n",
973 				p->lead_thread->pid);
974 		return -EFAULT;
975 	}
976 
977 	reg_gfx_index.bits.sh_broadcast_writes = 1;
978 	reg_gfx_index.bits.se_broadcast_writes = 1;
979 	reg_gfx_index.bits.instance_broadcast_writes = 1;
980 	reg_sq_cmd.bits.mode = SQ_IND_CMD_MODE_BROADCAST;
981 	reg_sq_cmd.bits.cmd = SQ_IND_CMD_CMD_KILL;
982 	reg_sq_cmd.bits.vm_id = vmid;
983 
984 	for_each_inst(xcc_id, xcc_mask)
985 		dev->kfd2kgd->wave_control_execute(
986 			dev->adev, reg_gfx_index.u32All,
987 			reg_sq_cmd.u32All, xcc_id);
988 
989 	return 0;
990 }
991 
992 /* Access to DQM has to be locked before calling destroy_queue_nocpsch_locked
993  * to avoid asynchronized access
994  */
995 static int destroy_queue_nocpsch_locked(struct device_queue_manager *dqm,
996 				struct qcm_process_device *qpd,
997 				struct queue *q)
998 {
999 	int retval;
1000 	struct mqd_manager *mqd_mgr;
1001 
1002 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(q->properties.type)];
1003 
1004 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE)
1005 		deallocate_hqd(dqm, q);
1006 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
1007 		deallocate_sdma_queue(dqm, q);
1008 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
1009 		deallocate_sdma_queue(dqm, q);
1010 	else {
1011 		pr_debug("q->properties.type %d is invalid\n",
1012 				q->properties.type);
1013 		return -EINVAL;
1014 	}
1015 	dqm->total_queue_count--;
1016 
1017 	deallocate_doorbell(qpd, q);
1018 
1019 	if (!dqm->sched_running) {
1020 		WARN_ONCE(1, "Destroy non-HWS queue while stopped\n");
1021 		return 0;
1022 	}
1023 
1024 	retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
1025 				KFD_PREEMPT_TYPE_WAVEFRONT_RESET,
1026 				KFD_UNMAP_LATENCY_MS,
1027 				q->pipe, q->queue);
1028 	if (retval == -ETIME)
1029 		qpd->reset_wavefronts = true;
1030 
1031 	list_del(&q->list);
1032 	if (list_empty(&qpd->queues_list)) {
1033 		if (qpd->reset_wavefronts) {
1034 			pr_warn("Resetting wave fronts (nocpsch) on dev %p\n",
1035 					dqm->dev);
1036 			/* dbgdev_wave_reset_wavefronts has to be called before
1037 			 * deallocate_vmid(), i.e. when vmid is still in use.
1038 			 */
1039 			dbgdev_wave_reset_wavefronts(dqm->dev,
1040 					qpd->pqm->process);
1041 			qpd->reset_wavefronts = false;
1042 		}
1043 
1044 		deallocate_vmid(dqm, qpd, q);
1045 	}
1046 	qpd->queue_count--;
1047 	if (q->properties.is_active)
1048 		decrement_queue_count(dqm, qpd, q);
1049 
1050 	return retval;
1051 }
1052 
1053 static int destroy_queue_nocpsch(struct device_queue_manager *dqm,
1054 				struct qcm_process_device *qpd,
1055 				struct queue *q)
1056 {
1057 	int retval;
1058 	uint64_t sdma_val = 0;
1059 	struct device *dev = dqm->dev->adev->dev;
1060 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
1061 	struct mqd_manager *mqd_mgr =
1062 		dqm->mqd_mgrs[get_mqd_type_from_queue_type(q->properties.type)];
1063 
1064 	/* Get the SDMA queue stats */
1065 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
1066 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
1067 		if (dqm->dev->kfd2kgd->hqd_sdma_get_counter)
1068 			retval = dqm->dev->kfd2kgd->hqd_sdma_get_counter(
1069 					dqm->dev->adev, q->mqd,
1070 					dqm->dev->kfd->device_info.num_sdma_queues_per_engine,
1071 					&sdma_val);
1072 		else
1073 			retval = read_sdma_queue_counter(
1074 					(uint64_t __user *)q->properties.read_ptr,
1075 					&sdma_val);
1076 		if (retval)
1077 			dev_err(dev, "Failed to read SDMA queue counter for queue: %d\n",
1078 				q->properties.queue_id);
1079 	}
1080 
1081 	dqm_lock(dqm);
1082 	retval = destroy_queue_nocpsch_locked(dqm, qpd, q);
1083 	if (!retval)
1084 		pdd->sdma_past_activity_counter += sdma_val;
1085 	dqm_unlock(dqm);
1086 
1087 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
1088 
1089 	return retval;
1090 }
1091 
1092 static int update_queue(struct device_queue_manager *dqm, struct queue *q,
1093 			struct mqd_update_info *minfo)
1094 {
1095 	int retval = 0;
1096 	struct device *dev = dqm->dev->adev->dev;
1097 	struct mqd_manager *mqd_mgr;
1098 	struct kfd_process_device *pdd;
1099 	bool prev_active = false;
1100 
1101 	dqm_lock(dqm);
1102 	pdd = kfd_get_process_device_data(q->device, q->process);
1103 	if (!pdd) {
1104 		retval = -ENODEV;
1105 		goto out_unlock;
1106 	}
1107 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1108 			q->properties.type)];
1109 
1110 	/* Save previous activity state for counters */
1111 	prev_active = q->properties.is_active;
1112 
1113 	/* Make sure the queue is unmapped before updating the MQD */
1114 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
1115 		if (!dqm->dev->kfd->shared_resources.enable_mes)
1116 			retval = unmap_queues_cpsch(dqm,
1117 						    KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD, false);
1118 		else if (prev_active)
1119 			retval = remove_queue_mes(dqm, q, &pdd->qpd);
1120 
1121 		/* queue is reset so inaccessable  */
1122 		if (pdd->has_reset_queue) {
1123 			retval = -EACCES;
1124 			goto out_unlock;
1125 		}
1126 
1127 		if (retval) {
1128 			dev_err(dev, "unmap queue failed\n");
1129 			goto out_unlock;
1130 		}
1131 	} else if (prev_active &&
1132 		   (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
1133 		    q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1134 		    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
1135 
1136 		if (!dqm->sched_running) {
1137 			WARN_ONCE(1, "Update non-HWS queue while stopped\n");
1138 			goto out_unlock;
1139 		}
1140 
1141 		retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
1142 				(dqm->dev->kfd->cwsr_enabled ?
1143 				 KFD_PREEMPT_TYPE_WAVEFRONT_SAVE :
1144 				 KFD_PREEMPT_TYPE_WAVEFRONT_DRAIN),
1145 				KFD_UNMAP_LATENCY_MS, q->pipe, q->queue);
1146 		if (retval) {
1147 			dev_err(dev, "destroy mqd failed\n");
1148 			goto out_unlock;
1149 		}
1150 	}
1151 
1152 	mqd_mgr->update_mqd(mqd_mgr, q->mqd, &q->properties, minfo);
1153 
1154 	/*
1155 	 * check active state vs. the previous state and modify
1156 	 * counter accordingly. map_queues_cpsch uses the
1157 	 * dqm->active_queue_count to determine whether a new runlist must be
1158 	 * uploaded.
1159 	 */
1160 	if (q->properties.is_active && !prev_active) {
1161 		increment_queue_count(dqm, &pdd->qpd, q);
1162 	} else if (!q->properties.is_active && prev_active) {
1163 		decrement_queue_count(dqm, &pdd->qpd, q);
1164 	} else if (q->gws && !q->properties.is_gws) {
1165 		if (q->properties.is_active) {
1166 			dqm->gws_queue_count++;
1167 			pdd->qpd.mapped_gws_queue = true;
1168 		}
1169 		q->properties.is_gws = true;
1170 	} else if (!q->gws && q->properties.is_gws) {
1171 		if (q->properties.is_active) {
1172 			dqm->gws_queue_count--;
1173 			pdd->qpd.mapped_gws_queue = false;
1174 		}
1175 		q->properties.is_gws = false;
1176 	}
1177 
1178 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
1179 		if (!dqm->dev->kfd->shared_resources.enable_mes)
1180 			retval = map_queues_cpsch(dqm);
1181 		else if (q->properties.is_active)
1182 			retval = add_queue_mes(dqm, q, &pdd->qpd);
1183 	} else if (q->properties.is_active &&
1184 		 (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
1185 		  q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1186 		  q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
1187 		if (WARN(q->process->mm != current->mm,
1188 			 "should only run in user thread"))
1189 			retval = -EFAULT;
1190 		else
1191 			retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd,
1192 						   q->pipe, q->queue,
1193 						   &q->properties, current->mm);
1194 	}
1195 
1196 out_unlock:
1197 	dqm_unlock(dqm);
1198 	return retval;
1199 }
1200 
1201 /* suspend_single_queue does not lock the dqm like the
1202  * evict_process_queues_cpsch or evict_process_queues_nocpsch. You should
1203  * lock the dqm before calling, and unlock after calling.
1204  *
1205  * The reason we don't lock the dqm is because this function may be
1206  * called on multiple queues in a loop, so rather than locking/unlocking
1207  * multiple times, we will just keep the dqm locked for all of the calls.
1208  */
1209 static int suspend_single_queue(struct device_queue_manager *dqm,
1210 				      struct kfd_process_device *pdd,
1211 				      struct queue *q)
1212 {
1213 	bool is_new;
1214 
1215 	if (q->properties.is_suspended)
1216 		return 0;
1217 
1218 	pr_debug("Suspending process pid %d queue [%i]\n",
1219 			pdd->process->lead_thread->pid,
1220 			q->properties.queue_id);
1221 
1222 	is_new = q->properties.exception_status & KFD_EC_MASK(EC_QUEUE_NEW);
1223 
1224 	if (is_new || q->properties.is_being_destroyed) {
1225 		pr_debug("Suspend: skip %s queue id %i\n",
1226 				is_new ? "new" : "destroyed",
1227 				q->properties.queue_id);
1228 		return -EBUSY;
1229 	}
1230 
1231 	q->properties.is_suspended = true;
1232 	if (q->properties.is_active) {
1233 		if (dqm->dev->kfd->shared_resources.enable_mes) {
1234 			int r = remove_queue_mes(dqm, q, &pdd->qpd);
1235 
1236 			if (r)
1237 				return r;
1238 		}
1239 
1240 		decrement_queue_count(dqm, &pdd->qpd, q);
1241 		q->properties.is_active = false;
1242 	}
1243 
1244 	return 0;
1245 }
1246 
1247 /* resume_single_queue does not lock the dqm like the functions
1248  * restore_process_queues_cpsch or restore_process_queues_nocpsch. You should
1249  * lock the dqm before calling, and unlock after calling.
1250  *
1251  * The reason we don't lock the dqm is because this function may be
1252  * called on multiple queues in a loop, so rather than locking/unlocking
1253  * multiple times, we will just keep the dqm locked for all of the calls.
1254  */
1255 static int resume_single_queue(struct device_queue_manager *dqm,
1256 				      struct qcm_process_device *qpd,
1257 				      struct queue *q)
1258 {
1259 	struct kfd_process_device *pdd;
1260 
1261 	if (!q->properties.is_suspended)
1262 		return 0;
1263 
1264 	pdd = qpd_to_pdd(qpd);
1265 
1266 	pr_debug("Restoring from suspend process pid %d queue [%i]\n",
1267 			    pdd->process->lead_thread->pid,
1268 			    q->properties.queue_id);
1269 
1270 	q->properties.is_suspended = false;
1271 
1272 	if (QUEUE_IS_ACTIVE(q->properties)) {
1273 		if (dqm->dev->kfd->shared_resources.enable_mes) {
1274 			int r = add_queue_mes(dqm, q, &pdd->qpd);
1275 
1276 			if (r)
1277 				return r;
1278 		}
1279 
1280 		q->properties.is_active = true;
1281 		increment_queue_count(dqm, qpd, q);
1282 	}
1283 
1284 	return 0;
1285 }
1286 
1287 /* Unpin the MQD BO at S4 suspend so it is evicted into the hibernation image;
1288  * dqm_repin_mqd_bo() pins it back on resume. Gated on adev->in_s4 so runtime
1289  * eviction is untouched.
1290  */
1291 static void dqm_evict_mqd_bo(struct device_queue_manager *dqm, struct queue *q)
1292 {
1293 	struct mqd_manager *mqd_mgr;
1294 	struct amdgpu_bo *bo;
1295 
1296 	if (!dqm->dev->adev->in_s4)
1297 		return;
1298 	if (!mqd_on_vram(dqm->dev->adev))
1299 		return;
1300 	if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE)
1301 		return;
1302 	if (!q->mqd_mem_obj || !q->mqd_mem_obj->mem)
1303 		return;
1304 
1305 	/* Without update_mqd_gpu_addr() the MQD self-address cannot be fixed up
1306 	 * after a repin, so skip eviction (with a warning) instead of faulting.
1307 	 */
1308 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(q->properties.type)];
1309 	if (!mqd_mgr->update_mqd_gpu_addr) {
1310 		dev_warn_once(dqm->dev->adev->dev,
1311 			      "MQD is in VRAM but update_mqd_gpu_addr is not implemented; skipping hibernation eviction\n");
1312 		return;
1313 	}
1314 
1315 	bo = q->mqd_mem_obj->mem;
1316 	if (amdgpu_bo_reserve(bo, false))
1317 		return;
1318 
1319 	amdgpu_bo_unpin(bo);
1320 	amdgpu_bo_unreserve(bo);
1321 	q->mqd = NULL;
1322 	q->needs_mqd_repin = true;
1323 }
1324 
1325 /* Repin the MQD BO to VRAM and refresh the cached mapping and GPU addresses.
1326  * Used both on resume and when a queue is destroyed before resume has repinned
1327  * it. A no-op unless a repin is owed (needs_mqd_repin set).
1328  */
1329 static int dqm_repin_mqd_bo(struct device_queue_manager *dqm, struct queue *q)
1330 {
1331 	struct mqd_manager *mqd_mgr;
1332 	struct amdgpu_bo *bo;
1333 	void *cpu_ptr;
1334 	int r;
1335 
1336 	if (!q->needs_mqd_repin)
1337 		return 0;
1338 	if (!q->mqd_mem_obj || !q->mqd_mem_obj->mem)
1339 		return 0;
1340 
1341 	bo = q->mqd_mem_obj->mem;
1342 	r = amdgpu_bo_reserve(bo, false);
1343 	if (r)
1344 		return r;
1345 	r = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_VRAM);
1346 	if (r) {
1347 		amdgpu_bo_unreserve(bo);
1348 		dev_err(dqm->dev->adev->dev,
1349 			"Failed to repin MQD of queue %d to VRAM: %d\n",
1350 			q->properties.queue_id, r);
1351 		return r;
1352 	}
1353 	/* The BO may have moved; refresh the kernel mapping and gpu address. */
1354 	amdgpu_bo_kunmap(bo);
1355 	r = amdgpu_bo_kmap(bo, &cpu_ptr);
1356 	amdgpu_bo_unreserve(bo);
1357 	if (r) {
1358 		dev_err(dqm->dev->adev->dev,
1359 			"Failed to remap MQD of queue %d: %d\n",
1360 			q->properties.queue_id, r);
1361 		return r;
1362 	}
1363 
1364 	q->mqd_mem_obj->cpu_ptr = cpu_ptr;
1365 	q->mqd_mem_obj->gpu_addr = amdgpu_bo_gpu_offset(bo);
1366 	q->gart_mqd_addr = q->mqd_mem_obj->gpu_addr;
1367 	q->mqd = cpu_ptr;
1368 
1369 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1370 			q->properties.type)];
1371 	if (mqd_mgr->update_mqd_gpu_addr)
1372 		mqd_mgr->update_mqd_gpu_addr(mqd_mgr, q->mqd,
1373 					     q->mqd_mem_obj,
1374 					     &q->properties);
1375 
1376 	q->needs_mqd_repin = false;
1377 	return 0;
1378 }
1379 
1380 static int evict_process_queues_nocpsch(struct device_queue_manager *dqm,
1381 					struct qcm_process_device *qpd)
1382 {
1383 	struct queue *q;
1384 	struct mqd_manager *mqd_mgr;
1385 	struct kfd_process_device *pdd;
1386 	int retval, ret = 0;
1387 
1388 	dqm_lock(dqm);
1389 	if (qpd->evicted++ > 0) /* already evicted, do nothing */
1390 		goto out;
1391 
1392 	pdd = qpd_to_pdd(qpd);
1393 	pr_debug_ratelimited("Evicting process pid %d queues\n",
1394 			    pdd->process->lead_thread->pid);
1395 
1396 	pdd->last_evict_timestamp = get_jiffies_64();
1397 	/* Mark all queues as evicted. Deactivate all active queues on
1398 	 * the qpd.
1399 	 */
1400 	list_for_each_entry(q, &qpd->queues_list, list) {
1401 		q->properties.is_evicted = true;
1402 		if (!q->properties.is_active)
1403 			continue;
1404 
1405 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1406 				q->properties.type)];
1407 		q->properties.is_active = false;
1408 		decrement_queue_count(dqm, qpd, q);
1409 
1410 		if (WARN_ONCE(!dqm->sched_running, "Evict when stopped\n"))
1411 			continue;
1412 
1413 		retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
1414 				(dqm->dev->kfd->cwsr_enabled ?
1415 				 KFD_PREEMPT_TYPE_WAVEFRONT_SAVE :
1416 				 KFD_PREEMPT_TYPE_WAVEFRONT_DRAIN),
1417 				KFD_UNMAP_LATENCY_MS, q->pipe, q->queue);
1418 		if (retval && !ret)
1419 			/* Return the first error, but keep going to
1420 			 * maintain a consistent eviction state
1421 			 */
1422 			ret = retval;
1423 	}
1424 
1425 out:
1426 	dqm_unlock(dqm);
1427 	return ret;
1428 }
1429 
1430 static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
1431 				      struct qcm_process_device *qpd)
1432 {
1433 	struct queue *q;
1434 	struct device *dev = dqm->dev->adev->dev;
1435 	struct kfd_process_device *pdd;
1436 	int retval = 0;
1437 
1438 	dqm_lock(dqm);
1439 	if (qpd->evicted++ > 0) /* already evicted, do nothing */
1440 		goto out;
1441 
1442 	pdd = qpd_to_pdd(qpd);
1443 
1444 	/* The debugger creates processes that temporarily have not acquired
1445 	 * all VMs for all devices and has no VMs itself.
1446 	 * Skip queue eviction on process eviction.
1447 	 */
1448 	if (!pdd->drm_priv)
1449 		goto out;
1450 
1451 	pr_debug_ratelimited("Evicting process pid %d queues\n",
1452 			    pdd->process->lead_thread->pid);
1453 
1454 	if (dqm->dev->kfd->shared_resources.enable_mes)
1455 		pdd->last_evict_timestamp = get_jiffies_64();
1456 
1457 	/* Mark all queues as evicted. Deactivate all active queues on
1458 	 * the qpd.
1459 	 */
1460 	list_for_each_entry(q, &qpd->queues_list, list) {
1461 		q->properties.is_evicted = true;
1462 		if (!q->properties.is_active)
1463 			continue;
1464 
1465 		q->properties.is_active = false;
1466 		decrement_queue_count(dqm, qpd, q);
1467 
1468 		if (dqm->dev->kfd->shared_resources.enable_mes) {
1469 			retval = remove_queue_mes(dqm, q, qpd);
1470 			if (retval) {
1471 				dev_err(dev, "Failed to evict queue %d\n",
1472 					q->properties.queue_id);
1473 				goto out;
1474 			}
1475 		}
1476 
1477 		dqm_evict_mqd_bo(dqm, q);
1478 	}
1479 
1480 	/*
1481 	 * Heavy-weight TLB flush after MES removes queues to ensure
1482 	 * in-flight memory accesses complete before memory is freed/migrated.
1483 	 * HWS does this automatically, MES does not.
1484 	 */
1485 	if (dqm->dev->kfd->shared_resources.enable_mes)
1486 		kfd_flush_tlb(pdd);
1487 
1488 	if (!dqm->dev->kfd->shared_resources.enable_mes) {
1489 		pdd->last_evict_timestamp = get_jiffies_64();
1490 		retval = execute_queues_cpsch(dqm,
1491 					      qpd->is_debug ?
1492 					      KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES :
1493 					      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
1494 					      USE_DEFAULT_GRACE_PERIOD);
1495 	}
1496 
1497 out:
1498 	dqm_unlock(dqm);
1499 	return retval;
1500 }
1501 
1502 static int restore_process_queues_nocpsch(struct device_queue_manager *dqm,
1503 					  struct qcm_process_device *qpd)
1504 {
1505 	struct mm_struct *mm = NULL;
1506 	struct queue *q;
1507 	struct mqd_manager *mqd_mgr;
1508 	struct kfd_process_device *pdd;
1509 	uint64_t pd_base;
1510 	uint64_t eviction_duration;
1511 	int retval, ret = 0;
1512 
1513 	pdd = qpd_to_pdd(qpd);
1514 	/* Retrieve PD base */
1515 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1516 
1517 	dqm_lock(dqm);
1518 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
1519 		goto out;
1520 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
1521 		qpd->evicted--;
1522 		goto out;
1523 	}
1524 
1525 	pr_debug_ratelimited("Restoring process pid %d queues\n",
1526 			    pdd->process->lead_thread->pid);
1527 
1528 	/* Update PD Base in QPD */
1529 	qpd->page_table_base = pd_base;
1530 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
1531 
1532 	if (!list_empty(&qpd->queues_list)) {
1533 		dqm->dev->kfd2kgd->set_vm_context_page_table_base(
1534 				dqm->dev->adev,
1535 				qpd->vmid,
1536 				qpd->page_table_base);
1537 		kfd_flush_tlb(pdd);
1538 	}
1539 
1540 	/* Take a safe reference to the mm_struct, which may otherwise
1541 	 * disappear even while the kfd_process is still referenced.
1542 	 */
1543 	mm = get_task_mm(pdd->process->lead_thread);
1544 	if (!mm) {
1545 		ret = -EFAULT;
1546 		goto out;
1547 	}
1548 
1549 	/* Remove the eviction flags. Activate queues that are not
1550 	 * inactive for other reasons.
1551 	 */
1552 	list_for_each_entry(q, &qpd->queues_list, list) {
1553 		q->properties.is_evicted = false;
1554 		if (!QUEUE_IS_ACTIVE(q->properties))
1555 			continue;
1556 
1557 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1558 				q->properties.type)];
1559 		q->properties.is_active = true;
1560 		increment_queue_count(dqm, qpd, q);
1561 
1562 		if (WARN_ONCE(!dqm->sched_running, "Restore when stopped\n"))
1563 			continue;
1564 
1565 		retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd, q->pipe,
1566 				       q->queue, &q->properties, mm);
1567 		if (retval && !ret)
1568 			/* Return the first error, but keep going to
1569 			 * maintain a consistent eviction state
1570 			 */
1571 			ret = retval;
1572 	}
1573 	qpd->evicted = 0;
1574 	eviction_duration = get_jiffies_64() - pdd->last_evict_timestamp;
1575 	atomic64_add(eviction_duration, &pdd->evict_duration_counter);
1576 out:
1577 	if (mm)
1578 		mmput(mm);
1579 	dqm_unlock(dqm);
1580 	return ret;
1581 }
1582 
1583 static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
1584 					struct qcm_process_device *qpd)
1585 {
1586 	struct queue *q;
1587 	struct device *dev = dqm->dev->adev->dev;
1588 	struct kfd_process_device *pdd;
1589 	uint64_t eviction_duration;
1590 	int retval = 0;
1591 
1592 	pdd = qpd_to_pdd(qpd);
1593 
1594 	dqm_lock(dqm);
1595 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
1596 		goto out;
1597 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
1598 		qpd->evicted--;
1599 		goto out;
1600 	}
1601 
1602 	/* The debugger creates processes that temporarily have not acquired
1603 	 * all VMs for all devices and has no VMs itself.
1604 	 * Skip queue restore on process restore.
1605 	 */
1606 	if (!pdd->drm_priv)
1607 		goto vm_not_acquired;
1608 
1609 	pr_debug_ratelimited("Restoring process pid %d queues\n",
1610 			    pdd->process->lead_thread->pid);
1611 
1612 	/* Update PD Base in QPD */
1613 	qpd->page_table_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1614 	pr_debug("Updated PD address to 0x%llx\n", qpd->page_table_base);
1615 
1616 	/* activate all active queues on the qpd */
1617 	list_for_each_entry(q, &qpd->queues_list, list) {
1618 		q->properties.is_evicted = false;
1619 		if (!QUEUE_IS_ACTIVE(q->properties))
1620 			continue;
1621 
1622 		q->properties.is_active = true;
1623 		increment_queue_count(dqm, &pdd->qpd, q);
1624 
1625 		retval = dqm_repin_mqd_bo(dqm, q);
1626 		if (retval) {
1627 			dev_err(dev, "Failed to repin MQD for queue %d\n",
1628 				q->properties.queue_id);
1629 			goto out;
1630 		}
1631 
1632 		if (dqm->dev->kfd->shared_resources.enable_mes) {
1633 			retval = add_queue_mes(dqm, q, qpd);
1634 			if (retval) {
1635 				dev_err(dev, "Failed to restore queue %d\n",
1636 					q->properties.queue_id);
1637 				goto out;
1638 			}
1639 		}
1640 	}
1641 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1642 		retval = execute_queues_cpsch(dqm,
1643 					      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD);
1644 	eviction_duration = get_jiffies_64() - pdd->last_evict_timestamp;
1645 	atomic64_add(eviction_duration, &pdd->evict_duration_counter);
1646 vm_not_acquired:
1647 	qpd->evicted = 0;
1648 out:
1649 	dqm_unlock(dqm);
1650 	return retval;
1651 }
1652 
1653 static int register_process(struct device_queue_manager *dqm,
1654 					struct qcm_process_device *qpd)
1655 {
1656 	struct device_process_node *n;
1657 	struct kfd_process_device *pdd;
1658 	uint64_t pd_base;
1659 	int retval;
1660 
1661 	n = kzalloc_obj(*n);
1662 	if (!n)
1663 		return -ENOMEM;
1664 
1665 	n->qpd = qpd;
1666 
1667 	pdd = qpd_to_pdd(qpd);
1668 	/* Retrieve PD base */
1669 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1670 
1671 	dqm_lock(dqm);
1672 	list_add(&n->list, &dqm->queues);
1673 
1674 	/* Update PD Base in QPD */
1675 	qpd->page_table_base = pd_base;
1676 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
1677 
1678 	retval = dqm->asic_ops.update_qpd(dqm, qpd);
1679 
1680 	dqm->processes_count++;
1681 
1682 	dqm_unlock(dqm);
1683 
1684 	/* Outside the DQM lock because under the DQM lock we can't do
1685 	 * reclaim or take other locks that others hold while reclaiming.
1686 	 */
1687 	kfd_inc_compute_active(dqm->dev);
1688 
1689 	return retval;
1690 }
1691 
1692 static int unregister_process(struct device_queue_manager *dqm,
1693 					struct qcm_process_device *qpd)
1694 {
1695 	int retval = 0;
1696 	struct device_process_node *cur, *next;
1697 
1698 	pr_debug("qpd->queues_list is %s\n",
1699 			list_empty(&qpd->queues_list) ? "empty" : "not empty");
1700 
1701 	dqm_lock(dqm);
1702 
1703 	list_for_each_entry_safe(cur, next, &dqm->queues, list) {
1704 		if (qpd == cur->qpd) {
1705 			list_del(&cur->list);
1706 			kfree(cur);
1707 			dqm->processes_count--;
1708 			goto out;
1709 		}
1710 	}
1711 	/* qpd not found in dqm list */
1712 	retval = 1;
1713 out:
1714 	dqm_unlock(dqm);
1715 
1716 	/* Outside the DQM lock because under the DQM lock we can't do
1717 	 * reclaim or take other locks that others hold while reclaiming.
1718 	 */
1719 	if (!retval)
1720 		kfd_dec_compute_active(dqm->dev);
1721 
1722 	return retval;
1723 }
1724 
1725 static int
1726 set_pasid_vmid_mapping(struct device_queue_manager *dqm, u32 pasid,
1727 			unsigned int vmid)
1728 {
1729 	uint32_t xcc_mask = dqm->dev->xcc_mask;
1730 	int xcc_id, ret = 0;
1731 
1732 	for_each_inst(xcc_id, xcc_mask) {
1733 		ret = dqm->dev->kfd2kgd->set_pasid_vmid_mapping(
1734 			dqm->dev->adev, pasid, vmid, xcc_id);
1735 		if (ret)
1736 			break;
1737 	}
1738 
1739 	return ret;
1740 }
1741 
1742 static void init_interrupts(struct device_queue_manager *dqm)
1743 {
1744 	uint32_t xcc_mask = dqm->dev->xcc_mask;
1745 	unsigned int i, xcc_id;
1746 
1747 	for_each_inst(xcc_id, xcc_mask) {
1748 		for (i = 0 ; i < get_pipes_per_mec(dqm) ; i++) {
1749 			if (is_pipe_enabled(dqm, 0, i)) {
1750 				dqm->dev->kfd2kgd->init_interrupts(
1751 					dqm->dev->adev, i, xcc_id);
1752 			}
1753 		}
1754 	}
1755 }
1756 
1757 static int initialize_nocpsch(struct device_queue_manager *dqm)
1758 {
1759 	int pipe, queue;
1760 
1761 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
1762 
1763 	dqm->allocated_queues = kcalloc(get_pipes_per_mec(dqm),
1764 					sizeof(unsigned int), GFP_KERNEL);
1765 	if (!dqm->allocated_queues)
1766 		return -ENOMEM;
1767 
1768 	mutex_init(&dqm->lock_hidden);
1769 	INIT_LIST_HEAD(&dqm->queues);
1770 	dqm->active_queue_count = dqm->next_pipe_to_allocate = 0;
1771 	dqm->active_cp_queue_count = 0;
1772 	dqm->gws_queue_count = 0;
1773 
1774 	for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
1775 		int pipe_offset = pipe * get_queues_per_pipe(dqm);
1776 
1777 		for (queue = 0; queue < get_queues_per_pipe(dqm); queue++)
1778 			if (test_bit(pipe_offset + queue,
1779 				     dqm->dev->kfd->shared_resources.cp_queue_bitmap))
1780 				dqm->allocated_queues[pipe] |= 1 << queue;
1781 	}
1782 
1783 	memset(dqm->vmid_pasid, 0, sizeof(dqm->vmid_pasid));
1784 
1785 	init_sdma_bitmaps(dqm);
1786 
1787 	return 0;
1788 }
1789 
1790 static void uninitialize(struct device_queue_manager *dqm)
1791 {
1792 	int i;
1793 
1794 	WARN_ON(dqm->active_queue_count > 0 || dqm->processes_count > 0);
1795 
1796 	kfree(dqm->allocated_queues);
1797 	for (i = 0 ; i < KFD_MQD_TYPE_MAX ; i++)
1798 		kfree(dqm->mqd_mgrs[i]);
1799 	mutex_destroy(&dqm->lock_hidden);
1800 }
1801 
1802 static int start_nocpsch(struct device_queue_manager *dqm)
1803 {
1804 	int r = 0;
1805 
1806 	pr_info("SW scheduler is used");
1807 	init_interrupts(dqm);
1808 
1809 	if (dqm->dev->adev->asic_type == CHIP_HAWAII)
1810 		r = pm_init(&dqm->packet_mgr, dqm);
1811 	if (!r)
1812 		dqm->sched_running = true;
1813 
1814 	return r;
1815 }
1816 
1817 static int stop_nocpsch(struct device_queue_manager *dqm)
1818 {
1819 	dqm_lock(dqm);
1820 	if (!dqm->sched_running) {
1821 		dqm_unlock(dqm);
1822 		return 0;
1823 	}
1824 
1825 	if (dqm->dev->adev->asic_type == CHIP_HAWAII)
1826 		pm_uninit(&dqm->packet_mgr);
1827 	dqm->sched_running = false;
1828 	dqm_unlock(dqm);
1829 
1830 	return 0;
1831 }
1832 
1833 static int allocate_sdma_queue(struct device_queue_manager *dqm,
1834 				struct queue *q, const uint32_t *restore_sdma_id)
1835 {
1836 	struct device *dev = dqm->dev->adev->dev;
1837 	int bit;
1838 
1839 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1840 		if (bitmap_empty(dqm->sdma_bitmap, get_num_sdma_queues(dqm))) {
1841 			dev_warn(dev, "No more SDMA queue to allocate (%d total queues)\n",
1842 				 get_num_sdma_queues(dqm));
1843 			return -ENOMEM;
1844 		}
1845 
1846 		if (restore_sdma_id) {
1847 			if (*restore_sdma_id >= get_num_sdma_queues(dqm))
1848 				return -EINVAL;
1849 
1850 			/* Re-use existing sdma_id */
1851 			if (!test_bit(*restore_sdma_id, dqm->sdma_bitmap)) {
1852 				dev_err(dev, "SDMA queue already in use\n");
1853 				return -EBUSY;
1854 			}
1855 			clear_bit(*restore_sdma_id, dqm->sdma_bitmap);
1856 			q->sdma_id = *restore_sdma_id;
1857 		} else {
1858 			/* Find first available sdma_id */
1859 			bit = find_first_bit(dqm->sdma_bitmap,
1860 					     get_num_sdma_queues(dqm));
1861 			clear_bit(bit, dqm->sdma_bitmap);
1862 			q->sdma_id = bit;
1863 		}
1864 
1865 		q->properties.sdma_engine_id =
1866 			q->sdma_id % kfd_get_num_sdma_engines(dqm->dev);
1867 		q->properties.sdma_queue_id = q->sdma_id /
1868 				kfd_get_num_sdma_engines(dqm->dev);
1869 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1870 		if (bitmap_empty(dqm->xgmi_sdma_bitmap, get_num_xgmi_sdma_queues(dqm))) {
1871 			dev_warn(dev, "No more XGMI SDMA queue to allocate (%d total queues)\n",
1872 				 get_num_xgmi_sdma_queues(dqm));
1873 			return -ENOMEM;
1874 		}
1875 		if (restore_sdma_id) {
1876 			if (*restore_sdma_id >= get_num_xgmi_sdma_queues(dqm))
1877 				return -EINVAL;
1878 
1879 			/* Re-use existing sdma_id */
1880 			if (!test_bit(*restore_sdma_id, dqm->xgmi_sdma_bitmap)) {
1881 				dev_err(dev, "SDMA queue already in use\n");
1882 				return -EBUSY;
1883 			}
1884 			clear_bit(*restore_sdma_id, dqm->xgmi_sdma_bitmap);
1885 			q->sdma_id = *restore_sdma_id;
1886 		} else {
1887 			bit = find_first_bit(dqm->xgmi_sdma_bitmap,
1888 					     get_num_xgmi_sdma_queues(dqm));
1889 			clear_bit(bit, dqm->xgmi_sdma_bitmap);
1890 			q->sdma_id = bit;
1891 		}
1892 		/* sdma_engine_id is sdma id including
1893 		 * both PCIe-optimized SDMAs and XGMI-
1894 		 * optimized SDMAs. The calculation below
1895 		 * assumes the first N engines are always
1896 		 * PCIe-optimized ones
1897 		 */
1898 		q->properties.sdma_engine_id =
1899 			kfd_get_num_sdma_engines(dqm->dev) +
1900 			q->sdma_id % kfd_get_num_xgmi_sdma_engines(dqm->dev);
1901 		q->properties.sdma_queue_id = q->sdma_id /
1902 			kfd_get_num_xgmi_sdma_engines(dqm->dev);
1903 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_BY_ENG_ID) {
1904 		int i, num_queues, num_engines, eng_offset = 0, start_engine;
1905 		bool free_bit_found = false, is_xgmi = false;
1906 
1907 		if (q->properties.sdma_engine_id < kfd_get_num_sdma_engines(dqm->dev)) {
1908 			num_queues = get_num_sdma_queues(dqm);
1909 			num_engines = kfd_get_num_sdma_engines(dqm->dev);
1910 			q->properties.type = KFD_QUEUE_TYPE_SDMA;
1911 		} else {
1912 			num_queues = get_num_xgmi_sdma_queues(dqm);
1913 			num_engines = kfd_get_num_xgmi_sdma_engines(dqm->dev);
1914 			eng_offset = kfd_get_num_sdma_engines(dqm->dev);
1915 			q->properties.type = KFD_QUEUE_TYPE_SDMA_XGMI;
1916 			is_xgmi = true;
1917 		}
1918 
1919 		/* Scan available bit based on target engine ID. */
1920 		start_engine = q->properties.sdma_engine_id - eng_offset;
1921 		for (i = start_engine; i < num_queues; i += num_engines) {
1922 
1923 			if (!test_bit(i, is_xgmi ? dqm->xgmi_sdma_bitmap : dqm->sdma_bitmap))
1924 				continue;
1925 
1926 			clear_bit(i, is_xgmi ? dqm->xgmi_sdma_bitmap : dqm->sdma_bitmap);
1927 			q->sdma_id = i;
1928 			q->properties.sdma_queue_id = q->sdma_id / num_engines;
1929 			free_bit_found = true;
1930 			break;
1931 		}
1932 
1933 		if (!free_bit_found) {
1934 			dev_warn(dev, "No more SDMA queue to allocate for target ID %i (%d total queues)\n",
1935 				 q->properties.sdma_engine_id, num_queues);
1936 			return -ENOMEM;
1937 		}
1938 	}
1939 
1940 	pr_debug("SDMA engine id: %d\n", q->properties.sdma_engine_id);
1941 	pr_debug("SDMA queue id: %d\n", q->properties.sdma_queue_id);
1942 
1943 	return 0;
1944 }
1945 
1946 static void deallocate_sdma_queue(struct device_queue_manager *dqm,
1947 				struct queue *q)
1948 {
1949 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1950 		if (q->sdma_id >= get_num_sdma_queues(dqm))
1951 			return;
1952 		set_bit(q->sdma_id, dqm->sdma_bitmap);
1953 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1954 		if (q->sdma_id >= get_num_xgmi_sdma_queues(dqm))
1955 			return;
1956 		set_bit(q->sdma_id, dqm->xgmi_sdma_bitmap);
1957 	}
1958 }
1959 
1960 /*
1961  * Device Queue Manager implementation for cp scheduler
1962  */
1963 
1964 static int set_sched_resources(struct device_queue_manager *dqm)
1965 {
1966 	int i, mec;
1967 	struct scheduling_resources res;
1968 	struct device *dev = dqm->dev->adev->dev;
1969 
1970 	res.vmid_mask = dqm->dev->compute_vmid_bitmap;
1971 
1972 	res.queue_mask = 0;
1973 	for (i = 0; i < AMDGPU_MAX_QUEUES; ++i) {
1974 		mec = (i / dqm->dev->kfd->shared_resources.num_queue_per_pipe)
1975 			/ dqm->dev->kfd->shared_resources.num_pipe_per_mec;
1976 
1977 		if (!test_bit(i, dqm->dev->kfd->shared_resources.cp_queue_bitmap))
1978 			continue;
1979 
1980 		/* only acquire queues from the first MEC */
1981 		if (mec > 0)
1982 			continue;
1983 
1984 		/* This situation may be hit in the future if a new HW
1985 		 * generation exposes more than 64 queues. If so, the
1986 		 * definition of res.queue_mask needs updating
1987 		 */
1988 		if (WARN_ON(i >= (sizeof(res.queue_mask)*8))) {
1989 			dev_err(dev, "Invalid queue enabled by amdgpu: %d\n", i);
1990 			break;
1991 		}
1992 
1993 		res.queue_mask |= 1ull
1994 			<< amdgpu_queue_mask_bit_to_set_resource_bit(
1995 				dqm->dev->adev, i);
1996 	}
1997 	res.gws_mask = ~0ull;
1998 	res.oac_mask = res.gds_heap_base = res.gds_heap_size = 0;
1999 
2000 	pr_debug("Scheduling resources:\n"
2001 			"vmid mask: 0x%8X\n"
2002 			"queue mask: 0x%8llX\n",
2003 			res.vmid_mask, res.queue_mask);
2004 
2005 	return pm_send_set_resources(&dqm->packet_mgr, &res);
2006 }
2007 
2008 static int initialize_cpsch(struct device_queue_manager *dqm)
2009 {
2010 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
2011 
2012 	mutex_init(&dqm->lock_hidden);
2013 	INIT_LIST_HEAD(&dqm->queues);
2014 	dqm->active_queue_count = dqm->processes_count = 0;
2015 	dqm->active_cp_queue_count = 0;
2016 	dqm->gws_queue_count = 0;
2017 	dqm->active_runlist = false;
2018 	dqm->trap_debug_vmid = 0;
2019 
2020 	init_sdma_bitmaps(dqm);
2021 
2022 	update_dqm_wait_times(dqm);
2023 	return 0;
2024 }
2025 
2026 /* halt_cpsch:
2027  * Unmap queues so the schedule doesn't continue remaining jobs in the queue.
2028  * Then set dqm->sched_halt so queues don't map to runlist until unhalt_cpsch
2029  * is called.
2030  */
2031 static int halt_cpsch(struct device_queue_manager *dqm)
2032 {
2033 	int ret = 0;
2034 
2035 	dqm_lock(dqm);
2036 	if (!dqm->sched_running) {
2037 		dqm_unlock(dqm);
2038 		return 0;
2039 	}
2040 
2041 	WARN_ONCE(dqm->sched_halt, "Scheduling is already on halt\n");
2042 
2043 	if (!dqm->is_hws_hang) {
2044 		if (!dqm->dev->kfd->shared_resources.enable_mes)
2045 			ret = unmap_queues_cpsch(dqm,
2046 						 KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
2047 				USE_DEFAULT_GRACE_PERIOD, false);
2048 		else
2049 			ret = remove_all_kfd_queues_mes(dqm);
2050 	}
2051 	dqm->sched_halt = true;
2052 	dqm_unlock(dqm);
2053 
2054 	return ret;
2055 }
2056 
2057 /* unhalt_cpsch
2058  * Unset dqm->sched_halt and map queues back to runlist
2059  */
2060 static int unhalt_cpsch(struct device_queue_manager *dqm)
2061 {
2062 	int ret = 0;
2063 	struct amdgpu_device *adev = dqm->dev->adev;
2064 
2065 	dqm_lock(dqm);
2066 	if (!dqm->sched_running || !dqm->sched_halt) {
2067 		dev_dbg(adev->dev, "Scheduling is not on halt.\n");
2068 		dqm_unlock(dqm);
2069 		return 0;
2070 	}
2071 	dqm->sched_halt = false;
2072 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2073 		ret = execute_queues_cpsch(dqm,
2074 					   KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES,
2075 			0, USE_DEFAULT_GRACE_PERIOD);
2076 	else
2077 		ret = add_all_kfd_queues_mes(dqm);
2078 
2079 	dqm_unlock(dqm);
2080 
2081 	return ret;
2082 }
2083 
2084 static int start_cpsch(struct device_queue_manager *dqm)
2085 {
2086 	struct device *dev = dqm->dev->adev->dev;
2087 	int retval, num_hw_queue_slots;
2088 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
2089 	int hung_array_size = amdgpu_mes_get_hung_queue_db_array_size(adev);
2090 	int hqd_info_size = adev->mes.hung_queue_hqd_info_offset;
2091 
2092 	dqm_lock(dqm);
2093 
2094 	if (!dqm->dev->kfd->shared_resources.enable_mes) {
2095 		retval = pm_init(&dqm->packet_mgr, dqm);
2096 		if (retval)
2097 			goto fail_packet_manager_init;
2098 
2099 		retval = set_sched_resources(dqm);
2100 		if (retval)
2101 			goto fail_set_sched_resources;
2102 	}
2103 	pr_debug("Allocating fence memory\n");
2104 
2105 	/* allocate fence memory on the gart */
2106 	retval = kfd_gtt_sa_allocate(dqm->dev, sizeof(*dqm->fence_addr),
2107 					&dqm->fence_mem);
2108 
2109 	if (retval)
2110 		goto fail_allocate_vidmem;
2111 
2112 	dqm->fence_addr = (uint64_t *)dqm->fence_mem->cpu_ptr;
2113 	dqm->fence_gpu_addr = dqm->fence_mem->gpu_addr;
2114 
2115 	init_interrupts(dqm);
2116 
2117 	/* clear hang status when driver try to start the hw scheduler */
2118 	dqm->sched_running = true;
2119 
2120 	if (!dqm->dev->kfd->shared_resources.enable_mes) {
2121 		if (pm_config_dequeue_wait_counts(&dqm->packet_mgr,
2122 				KFD_DEQUEUE_WAIT_INIT, 0 /* unused */))
2123 			dev_err(dev, "Setting optimized dequeue wait failed. Using default values\n");
2124 		execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD);
2125 	}
2126 
2127 	/* setup per-queue reset detection buffer  */
2128 	num_hw_queue_slots =  dqm->dev->kfd->shared_resources.num_queue_per_pipe *
2129 			      dqm->dev->kfd->shared_resources.num_pipe_per_mec *
2130 			      NUM_XCC(dqm->dev->xcc_mask);
2131 
2132 	dqm->detect_hang_info_size = num_hw_queue_slots * sizeof(struct dqm_detect_hang_info);
2133 	dqm->detect_hang_info = kzalloc(dqm->detect_hang_info_size, GFP_KERNEL);
2134 
2135 	if (!dqm->detect_hang_info) {
2136 		retval = -ENOMEM;
2137 		goto fail_detect_hang_buffer;
2138 	}
2139 
2140 	dqm->hung_db_array = kzalloc(hung_array_size * sizeof(u32), GFP_KERNEL);
2141 	dqm->hqd_info = kzalloc(
2142 		hqd_info_size * sizeof(struct amdgpu_mes_hung_queue_hqd_info),
2143 		GFP_KERNEL);
2144 
2145 	dqm_unlock(dqm);
2146 
2147 	return 0;
2148 fail_detect_hang_buffer:
2149 	kfd_gtt_sa_free(dqm->dev, dqm->fence_mem);
2150 fail_allocate_vidmem:
2151 fail_set_sched_resources:
2152 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2153 		pm_uninit(&dqm->packet_mgr);
2154 fail_packet_manager_init:
2155 	dqm_unlock(dqm);
2156 	return retval;
2157 }
2158 
2159 static int stop_cpsch(struct device_queue_manager *dqm)
2160 {
2161 	int ret = 0;
2162 
2163 	dqm_lock(dqm);
2164 	if (!dqm->sched_running) {
2165 		dqm_unlock(dqm);
2166 		return 0;
2167 	}
2168 
2169 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2170 		ret = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES,
2171 								0, USE_DEFAULT_GRACE_PERIOD, false);
2172 	else
2173 		ret = remove_all_kfd_queues_mes(dqm);
2174 
2175 	dqm->sched_running = false;
2176 
2177 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2178 		pm_release_ib(&dqm->packet_mgr);
2179 
2180 	kfd_gtt_sa_free(dqm->dev, dqm->fence_mem);
2181 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2182 		pm_uninit(&dqm->packet_mgr);
2183 	kfree(dqm->detect_hang_info);
2184 	dqm->detect_hang_info = NULL;
2185 	kfree(dqm->hung_db_array);
2186 	kfree(dqm->hqd_info);
2187 
2188 	dqm_unlock(dqm);
2189 
2190 	return ret;
2191 }
2192 
2193 static int create_kernel_queue_cpsch(struct device_queue_manager *dqm,
2194 					struct kernel_queue *kq,
2195 					struct qcm_process_device *qpd)
2196 {
2197 	dqm_lock(dqm);
2198 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
2199 		pr_warn("Can't create new kernel queue because %d queues were already created\n",
2200 				dqm->total_queue_count);
2201 		dqm_unlock(dqm);
2202 		return -EPERM;
2203 	}
2204 
2205 	/*
2206 	 * Unconditionally increment this counter, regardless of the queue's
2207 	 * type or whether the queue is active.
2208 	 */
2209 	dqm->total_queue_count++;
2210 	pr_debug("Total of %d queues are accountable so far\n",
2211 			dqm->total_queue_count);
2212 
2213 	list_add(&kq->list, &qpd->priv_queue_list);
2214 	increment_queue_count(dqm, qpd, kq->queue);
2215 	qpd->is_debug = true;
2216 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
2217 			USE_DEFAULT_GRACE_PERIOD);
2218 	dqm_unlock(dqm);
2219 
2220 	return 0;
2221 }
2222 
2223 static void destroy_kernel_queue_cpsch(struct device_queue_manager *dqm,
2224 					struct kernel_queue *kq,
2225 					struct qcm_process_device *qpd)
2226 {
2227 	dqm_lock(dqm);
2228 	list_del(&kq->list);
2229 	decrement_queue_count(dqm, qpd, kq->queue);
2230 	qpd->is_debug = false;
2231 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
2232 			USE_DEFAULT_GRACE_PERIOD);
2233 	/*
2234 	 * Unconditionally decrement this counter, regardless of the queue's
2235 	 * type.
2236 	 */
2237 	dqm->total_queue_count--;
2238 	pr_debug("Total of %d queues are accountable so far\n",
2239 			dqm->total_queue_count);
2240 	dqm_unlock(dqm);
2241 }
2242 
2243 static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
2244 			struct qcm_process_device *qpd,
2245 			const struct kfd_criu_queue_priv_data *qd,
2246 			const void *restore_mqd, const void *restore_ctl_stack)
2247 {
2248 	int retval;
2249 	struct mqd_manager *mqd_mgr;
2250 
2251 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
2252 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
2253 				dqm->total_queue_count);
2254 		retval = -EPERM;
2255 		goto out;
2256 	}
2257 
2258 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
2259 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI ||
2260 		q->properties.type == KFD_QUEUE_TYPE_SDMA_BY_ENG_ID) {
2261 		dqm_lock(dqm);
2262 		retval = allocate_sdma_queue(dqm, q, qd ? &qd->sdma_id : NULL);
2263 		dqm_unlock(dqm);
2264 		if (retval)
2265 			goto out;
2266 	}
2267 
2268 	retval = allocate_doorbell(qpd, q, qd ? &qd->doorbell_id : NULL);
2269 	if (retval)
2270 		goto out_deallocate_sdma_queue;
2271 
2272 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2273 			q->properties.type)];
2274 	if (qd && !mqd_mgr->restore_mqd) {
2275 		pr_debug("restore_mqd not implemented for queue type %d\n",
2276 			 q->properties.type);
2277 		retval = -EOPNOTSUPP;
2278 		goto out_deallocate_doorbell;
2279 	}
2280 
2281 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
2282 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
2283 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
2284 	q->properties.tba_addr = qpd->tba_addr;
2285 	q->properties.tma_addr = qpd->tma_addr;
2286 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr, &q->properties);
2287 	if (!q->mqd_mem_obj) {
2288 		retval = -ENOMEM;
2289 		goto out_deallocate_doorbell;
2290 	}
2291 
2292 	dqm_lock(dqm);
2293 	/*
2294 	 * Eviction state logic: mark all queues as evicted, even ones
2295 	 * not currently active. Restoring inactive queues later only
2296 	 * updates the is_evicted flag but is a no-op otherwise.
2297 	 */
2298 	q->properties.is_evicted = !!qpd->evicted;
2299 	q->properties.is_dbg_wa = qpd->pqm->process->debug_trap_enabled &&
2300 				  kfd_dbg_has_cwsr_workaround(q->device);
2301 
2302 	if (qd)
2303 		mqd_mgr->restore_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj, &q->gart_mqd_addr,
2304 				     &q->properties, restore_mqd, restore_ctl_stack,
2305 				     qd->ctl_stack_size);
2306 	else
2307 		mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
2308 					&q->gart_mqd_addr, &q->properties);
2309 
2310 	list_add(&q->list, &qpd->queues_list);
2311 	qpd->queue_count++;
2312 
2313 	if (q->properties.is_active) {
2314 		increment_queue_count(dqm, qpd, q);
2315 
2316 		if (!dqm->dev->kfd->shared_resources.enable_mes)
2317 			retval = execute_queues_cpsch(dqm,
2318 					KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD);
2319 		else
2320 			retval = add_queue_mes(dqm, q, qpd);
2321 		if (retval)
2322 			goto cleanup_queue;
2323 	}
2324 
2325 	/*
2326 	 * Unconditionally increment this counter, regardless of the queue's
2327 	 * type or whether the queue is active.
2328 	 */
2329 	dqm->total_queue_count++;
2330 
2331 	pr_debug("Total of %d queues are accountable so far\n",
2332 			dqm->total_queue_count);
2333 
2334 	dqm_unlock(dqm);
2335 	return retval;
2336 
2337 cleanup_queue:
2338 	qpd->queue_count--;
2339 	list_del(&q->list);
2340 	if (q->properties.is_active)
2341 		decrement_queue_count(dqm, qpd, q);
2342 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2343 	dqm_unlock(dqm);
2344 out_deallocate_doorbell:
2345 	deallocate_doorbell(qpd, q);
2346 out_deallocate_sdma_queue:
2347 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
2348 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
2349 		dqm_lock(dqm);
2350 		deallocate_sdma_queue(dqm, q);
2351 		dqm_unlock(dqm);
2352 	}
2353 out:
2354 	return retval;
2355 }
2356 
2357 int amdkfd_fence_wait_timeout(struct device_queue_manager *dqm,
2358 			      uint64_t fence_value,
2359 			      unsigned int timeout_ms)
2360 {
2361 	unsigned long end_jiffies = msecs_to_jiffies(timeout_ms) + jiffies;
2362 	struct device *dev = dqm->dev->adev->dev;
2363 	uint64_t *fence_addr = dqm->fence_addr;
2364 
2365 	while (*fence_addr != fence_value) {
2366 		/* Fatal err detected, this response won't come */
2367 		if (amdgpu_amdkfd_is_fed(dqm->dev->adev) ||
2368 		    amdgpu_in_reset(dqm->dev->adev))
2369 			return -EIO;
2370 
2371 		if (time_after(jiffies, end_jiffies)) {
2372 			dev_err(dev, "qcm fence wait loop timeout expired\n");
2373 			/* In HWS case, this is used to halt the driver thread
2374 			 * in order not to mess up CP states before doing
2375 			 * scandumps for FW debugging.
2376 			 */
2377 			while (halt_if_hws_hang)
2378 				schedule();
2379 
2380 			return -ETIME;
2381 		}
2382 		schedule();
2383 	}
2384 
2385 	return 0;
2386 }
2387 
2388 /* dqm->lock mutex has to be locked before calling this function */
2389 static int map_queues_cpsch(struct device_queue_manager *dqm)
2390 {
2391 	struct device *dev = dqm->dev->adev->dev;
2392 	int retval;
2393 
2394 	if (!dqm->sched_running || dqm->sched_halt)
2395 		return 0;
2396 	if (dqm->active_queue_count <= 0 || dqm->processes_count <= 0)
2397 		return 0;
2398 	if (dqm->active_runlist)
2399 		return 0;
2400 
2401 	retval = pm_send_runlist(&dqm->packet_mgr, &dqm->queues);
2402 	pr_debug("%s sent runlist\n", __func__);
2403 	if (retval) {
2404 		dev_err(dev, "failed to execute runlist\n");
2405 		return retval;
2406 	}
2407 	dqm->active_runlist = true;
2408 
2409 	return retval;
2410 }
2411 
2412 static void set_queue_as_reset(struct device_queue_manager *dqm, struct queue *q,
2413 			       struct qcm_process_device *qpd)
2414 {
2415 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
2416 
2417 	dev_err(dqm->dev->adev->dev, "queue id 0x%0x at pasid %d is reset\n",
2418 		q->properties.queue_id, pdd->process->lead_thread->pid);
2419 
2420 	pdd->has_reset_queue = true;
2421 	q->properties.is_reset = true;
2422 	if (q->properties.is_active) {
2423 		q->properties.is_active = false;
2424 		decrement_queue_count(dqm, qpd, q);
2425 	}
2426 }
2427 
2428 static int detect_queue_hang(struct device_queue_manager *dqm)
2429 {
2430 	int i;
2431 
2432 	/* detect should be used only in dqm locked queue reset */
2433 	if (WARN_ON(dqm->detect_hang_count > 0))
2434 		return 0;
2435 
2436 	memset(dqm->detect_hang_info, 0, dqm->detect_hang_info_size);
2437 
2438 	for (i = 0; i < AMDGPU_MAX_QUEUES; ++i) {
2439 		uint32_t mec, pipe, queue;
2440 		int xcc_id;
2441 
2442 		mec = (i / dqm->dev->kfd->shared_resources.num_queue_per_pipe)
2443 			/ dqm->dev->kfd->shared_resources.num_pipe_per_mec;
2444 
2445 		if (mec || !test_bit(i, dqm->dev->kfd->shared_resources.cp_queue_bitmap))
2446 			continue;
2447 
2448 		amdgpu_queue_mask_bit_to_mec_queue(dqm->dev->adev, i, &mec, &pipe, &queue);
2449 
2450 		for_each_inst(xcc_id, dqm->dev->xcc_mask) {
2451 			uint64_t queue_addr = dqm->dev->kfd2kgd->hqd_get_pq_addr(
2452 						dqm->dev->adev, pipe, queue, xcc_id);
2453 			struct dqm_detect_hang_info hang_info;
2454 
2455 			if (!queue_addr)
2456 				continue;
2457 
2458 			hang_info.pipe_id = pipe;
2459 			hang_info.queue_id = queue;
2460 			hang_info.xcc_id = xcc_id;
2461 			hang_info.queue_address = queue_addr;
2462 
2463 			dqm->detect_hang_info[dqm->detect_hang_count] = hang_info;
2464 			dqm->detect_hang_count++;
2465 		}
2466 	}
2467 
2468 	return dqm->detect_hang_count;
2469 }
2470 
2471 static struct queue *find_queue_by_address(struct device_queue_manager *dqm, uint64_t queue_address)
2472 {
2473 	struct device_process_node *cur;
2474 	struct qcm_process_device *qpd;
2475 	struct queue *q;
2476 
2477 	list_for_each_entry(cur, &dqm->queues, list) {
2478 		qpd = cur->qpd;
2479 		list_for_each_entry(q, &qpd->queues_list, list) {
2480 			if (queue_address == q->properties.queue_address)
2481 				return q;
2482 		}
2483 	}
2484 
2485 	return NULL;
2486 }
2487 
2488 static struct queue *find_queue_by_doorbell_offset(struct device_queue_manager *dqm, u32 doorbell_offset)
2489 {
2490 	struct device_process_node *cur;
2491 	struct qcm_process_device *qpd;
2492 	struct queue *q;
2493 
2494 	list_for_each_entry(cur, &dqm->queues, list) {
2495 		qpd = cur->qpd;
2496 		list_for_each_entry(q, &qpd->queues_list, list) {
2497 			if (doorbell_offset == q->properties.doorbell_off)
2498 				return q;
2499 		}
2500 	}
2501 
2502 	return NULL;
2503 }
2504 
2505 static int reset_hung_queues(struct device_queue_manager *dqm)
2506 {
2507 	int r = 0, reset_count = 0, i;
2508 
2509 	if (!dqm->detect_hang_info || dqm->is_hws_hang)
2510 		return -EIO;
2511 
2512 	/* assume dqm locked. */
2513 	if (!detect_queue_hang(dqm))
2514 		return -ENOTRECOVERABLE;
2515 
2516 	for (i = 0; i < dqm->detect_hang_count; i++) {
2517 		struct dqm_detect_hang_info hang_info = dqm->detect_hang_info[i];
2518 		struct queue *q = find_queue_by_address(dqm, hang_info.queue_address);
2519 		struct kfd_process_device *pdd;
2520 		uint64_t queue_addr = 0;
2521 
2522 		if (!q) {
2523 			r = -ENOTRECOVERABLE;
2524 			goto reset_fail;
2525 		}
2526 
2527 		pdd = kfd_get_process_device_data(dqm->dev, q->process);
2528 		if (!pdd) {
2529 			r = -ENOTRECOVERABLE;
2530 			goto reset_fail;
2531 		}
2532 
2533 		queue_addr = dqm->dev->kfd2kgd->hqd_reset(dqm->dev->adev,
2534 				hang_info.pipe_id, hang_info.queue_id, hang_info.xcc_id,
2535 				KFD_UNMAP_LATENCY_MS);
2536 
2537 		/* either reset failed or we reset an unexpected queue. */
2538 		if (queue_addr != q->properties.queue_address) {
2539 			r = -ENOTRECOVERABLE;
2540 			goto reset_fail;
2541 		}
2542 
2543 		set_queue_as_reset(dqm, q, &pdd->qpd);
2544 		reset_count++;
2545 	}
2546 
2547 	if (reset_count == dqm->detect_hang_count)
2548 		kfd_signal_reset_event(dqm->dev);
2549 	else
2550 		r = -ENOTRECOVERABLE;
2551 
2552 reset_fail:
2553 	dqm->detect_hang_count = 0;
2554 
2555 	return r;
2556 }
2557 
2558 static bool sdma_has_hang(struct device_queue_manager *dqm)
2559 {
2560 	int engine_start = dqm->dev->node_id * get_num_all_sdma_engines(dqm);
2561 	int engine_end = engine_start + get_num_all_sdma_engines(dqm);
2562 	int num_queues_per_eng =  dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
2563 	int i, j;
2564 
2565 	for (i = engine_start; i < engine_end; i++) {
2566 		for (j = 0; j < num_queues_per_eng; j++) {
2567 			if (!dqm->dev->kfd2kgd->hqd_sdma_get_doorbell(dqm->dev->adev, i, j))
2568 				continue;
2569 
2570 			return true;
2571 		}
2572 	}
2573 
2574 	return false;
2575 }
2576 
2577 static bool set_sdma_queue_as_reset(struct device_queue_manager *dqm,
2578 				    uint32_t doorbell_off)
2579 {
2580 	struct device_process_node *cur;
2581 	struct qcm_process_device *qpd;
2582 	struct queue *q;
2583 
2584 	list_for_each_entry(cur, &dqm->queues, list) {
2585 		qpd = cur->qpd;
2586 		list_for_each_entry(q, &qpd->queues_list, list) {
2587 			if ((q->properties.type == KFD_QUEUE_TYPE_SDMA ||
2588 			     q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) &&
2589 			     q->properties.doorbell_off == doorbell_off) {
2590 				set_queue_as_reset(dqm, q, qpd);
2591 				return true;
2592 			}
2593 		}
2594 	}
2595 
2596 	return false;
2597 }
2598 
2599 static int reset_hung_queues_sdma(struct device_queue_manager *dqm)
2600 {
2601 	int engine_start = dqm->dev->node_id * get_num_all_sdma_engines(dqm);
2602 	int engine_end = engine_start + get_num_all_sdma_engines(dqm);
2603 	int num_queues_per_eng =  dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
2604 	int r = 0, i, j;
2605 
2606 	if (dqm->is_hws_hang)
2607 		return -EIO;
2608 
2609 	/* Scan for hung HW queues and reset engine. */
2610 	dqm->detect_hang_count = 0;
2611 	for (i = engine_start; i < engine_end; i++) {
2612 		for (j = 0; j < num_queues_per_eng; j++) {
2613 			uint32_t doorbell_off =
2614 				dqm->dev->kfd2kgd->hqd_sdma_get_doorbell(dqm->dev->adev, i, j);
2615 
2616 			if (!doorbell_off)
2617 				continue;
2618 
2619 			/* Reset engine and check. */
2620 			if (amdgpu_sdma_reset_engine(dqm->dev->adev, i, false) ||
2621 			    dqm->dev->kfd2kgd->hqd_sdma_get_doorbell(dqm->dev->adev, i, j) ||
2622 			    !set_sdma_queue_as_reset(dqm, doorbell_off)) {
2623 				r = -ENOTRECOVERABLE;
2624 				goto reset_fail;
2625 			}
2626 
2627 			/* Should only expect one queue active per engine */
2628 			dqm->detect_hang_count++;
2629 			break;
2630 		}
2631 	}
2632 
2633 	/* Signal process reset */
2634 	if (dqm->detect_hang_count)
2635 		kfd_signal_reset_event(dqm->dev);
2636 	else
2637 		r = -ENOTRECOVERABLE;
2638 
2639 reset_fail:
2640 	dqm->detect_hang_count = 0;
2641 
2642 	return r;
2643 }
2644 
2645 static int reset_queues_on_hws_hang(struct device_queue_manager *dqm, bool is_sdma)
2646 {
2647 	struct amdgpu_device *adev = dqm->dev->adev;
2648 
2649 	while (halt_if_hws_hang)
2650 		schedule();
2651 
2652 	if (adev->debug_disable_gpu_ring_reset) {
2653 		dev_info_once(adev->dev,
2654 			      "%s queue hung, but ring reset disabled",
2655 			      is_sdma ? "sdma" : "compute");
2656 
2657 		return -EPERM;
2658 	}
2659 	if (!amdgpu_gpu_recovery)
2660 		return -ENOTRECOVERABLE;
2661 
2662 	return is_sdma ? reset_hung_queues_sdma(dqm) : reset_hung_queues(dqm);
2663 }
2664 
2665 /* dqm->lock mutex has to be locked before calling this function
2666  *
2667  * @grace_period: If USE_DEFAULT_GRACE_PERIOD then default wait time
2668  *   for context switch latency. Lower values are used by debugger
2669  *   since context switching are triggered at high frequency.
2670  *   This is configured by setting CP_IQ_WAIT_TIME2.SCH_WAVE
2671  *
2672  */
2673 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
2674 				enum kfd_unmap_queues_filter filter,
2675 				uint32_t filter_param,
2676 				uint32_t grace_period,
2677 				bool reset)
2678 {
2679 	struct device *dev = dqm->dev->adev->dev;
2680 	struct mqd_manager *mqd_mgr;
2681 	int retval;
2682 
2683 	if (!dqm->sched_running)
2684 		return 0;
2685 	if (!dqm->active_runlist)
2686 		return 0;
2687 	if (!down_read_trylock(&dqm->dev->adev->reset_domain->sem))
2688 		return -EIO;
2689 
2690 	if (grace_period != USE_DEFAULT_GRACE_PERIOD) {
2691 		retval = pm_config_dequeue_wait_counts(&dqm->packet_mgr,
2692 				KFD_DEQUEUE_WAIT_SET_SCH_WAVE, grace_period);
2693 		if (retval)
2694 			goto out;
2695 	}
2696 
2697 	retval = pm_send_unmap_queue(&dqm->packet_mgr, filter, filter_param, reset);
2698 	if (retval)
2699 		goto out;
2700 
2701 	*dqm->fence_addr = KFD_FENCE_INIT;
2702 	mb();
2703 	pm_send_query_status(&dqm->packet_mgr, dqm->fence_gpu_addr,
2704 				KFD_FENCE_COMPLETED);
2705 	/* should be timed out */
2706 	retval = amdkfd_fence_wait_timeout(dqm, KFD_FENCE_COMPLETED,
2707 					   queue_preemption_timeout_ms);
2708 	if (retval) {
2709 		dev_err(dev, "The cp might be in an unrecoverable state due to an unsuccessful queues preemption\n");
2710 		kfd_hws_hang(dqm);
2711 		goto out;
2712 	}
2713 
2714 	/* In the current MEC firmware implementation, if compute queue
2715 	 * doesn't response to the preemption request in time, HIQ will
2716 	 * abandon the unmap request without returning any timeout error
2717 	 * to driver. Instead, MEC firmware will log the doorbell of the
2718 	 * unresponding compute queue to HIQ.MQD.queue_doorbell_id fields.
2719 	 * To make sure the queue unmap was successful, driver need to
2720 	 * check those fields
2721 	 */
2722 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ];
2723 	if (mqd_mgr->check_preemption_failed(mqd_mgr, dqm->packet_mgr.priv_queue->queue->mqd) &&
2724 	    reset_queues_on_hws_hang(dqm, false))
2725 		goto reset_fail;
2726 
2727 	/* Check for SDMA hang and attempt SDMA reset */
2728 	if (sdma_has_hang(dqm) && reset_queues_on_hws_hang(dqm, true))
2729 		goto reset_fail;
2730 
2731 	/* We need to reset the grace period value for this device */
2732 	if (grace_period != USE_DEFAULT_GRACE_PERIOD) {
2733 		if (pm_config_dequeue_wait_counts(&dqm->packet_mgr,
2734 				KFD_DEQUEUE_WAIT_RESET, 0 /* unused */))
2735 			dev_err(dev, "Failed to reset grace period\n");
2736 	}
2737 
2738 	pm_release_ib(&dqm->packet_mgr);
2739 	dqm->active_runlist = false;
2740 out:
2741 	up_read(&dqm->dev->adev->reset_domain->sem);
2742 	return retval;
2743 
2744 reset_fail:
2745 	dqm->is_hws_hang = true;
2746 	kfd_hws_hang(dqm);
2747 	up_read(&dqm->dev->adev->reset_domain->sem);
2748 	return -ETIME;
2749 }
2750 
2751 /* only for compute queue */
2752 static int reset_queues_cpsch(struct device_queue_manager *dqm, uint16_t pasid)
2753 {
2754 	int retval;
2755 
2756 	dqm_lock(dqm);
2757 
2758 	retval = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_BY_PASID,
2759 			pasid, USE_DEFAULT_GRACE_PERIOD, true);
2760 
2761 	dqm_unlock(dqm);
2762 	return retval;
2763 }
2764 
2765 /* dqm->lock mutex has to be locked before calling this function */
2766 static int execute_queues_cpsch(struct device_queue_manager *dqm,
2767 				enum kfd_unmap_queues_filter filter,
2768 				uint32_t filter_param,
2769 				uint32_t grace_period)
2770 {
2771 	int retval;
2772 
2773 	if (!down_read_trylock(&dqm->dev->adev->reset_domain->sem))
2774 		return -EIO;
2775 	retval = unmap_queues_cpsch(dqm, filter, filter_param, grace_period, false);
2776 	if (!retval)
2777 		retval = map_queues_cpsch(dqm);
2778 	up_read(&dqm->dev->adev->reset_domain->sem);
2779 	return retval;
2780 }
2781 
2782 static int wait_on_destroy_queue(struct device_queue_manager *dqm,
2783 				 struct queue *q)
2784 {
2785 	struct kfd_process_device *pdd = kfd_get_process_device_data(q->device,
2786 								q->process);
2787 	int ret = 0;
2788 
2789 	if (WARN_ON(!pdd))
2790 		return ret;
2791 
2792 	if (pdd->qpd.is_debug)
2793 		return ret;
2794 
2795 	if (q->properties.is_being_destroyed)
2796 		return -EBUSY;
2797 
2798 	q->properties.is_being_destroyed = true;
2799 
2800 	if (pdd->process->debug_trap_enabled && q->properties.is_suspended) {
2801 		dqm_unlock(dqm);
2802 		mutex_unlock(&q->process->mutex);
2803 		ret = wait_event_interruptible(dqm->destroy_wait,
2804 						!q->properties.is_suspended);
2805 
2806 		mutex_lock(&q->process->mutex);
2807 		dqm_lock(dqm);
2808 	}
2809 
2810 	if (ret)
2811 		q->properties.is_being_destroyed = false;
2812 
2813 	return ret;
2814 }
2815 
2816 static int destroy_queue_cpsch(struct device_queue_manager *dqm,
2817 				struct qcm_process_device *qpd,
2818 				struct queue *q)
2819 {
2820 	int retval;
2821 	struct mqd_manager *mqd_mgr;
2822 	uint64_t sdma_val = 0;
2823 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
2824 	struct device *dev = dqm->dev->adev->dev;
2825 
2826 	/* Get the SDMA queue stats */
2827 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
2828 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
2829 		if (dqm->dev->kfd2kgd->hqd_sdma_get_counter)
2830 			retval = dqm->dev->kfd2kgd->hqd_sdma_get_counter(
2831 					dqm->dev->adev, q->mqd,
2832 					dqm->dev->kfd->device_info.num_sdma_queues_per_engine,
2833 					&sdma_val);
2834 		else
2835 			retval = read_sdma_queue_counter(
2836 					(uint64_t __user *)q->properties.read_ptr,
2837 					&sdma_val);
2838 
2839 		if (retval)
2840 			dev_err(dev, "Failed to read SDMA queue counter for queue: %d\n",
2841 				q->properties.queue_id);
2842 	}
2843 
2844 	/* remove queue from list to prevent rescheduling after preemption */
2845 	dqm_lock(dqm);
2846 
2847 	retval = wait_on_destroy_queue(dqm, q);
2848 
2849 	if (retval) {
2850 		dqm_unlock(dqm);
2851 		return retval;
2852 	}
2853 
2854 	if (qpd->is_debug) {
2855 		/*
2856 		 * error, currently we do not allow to destroy a queue
2857 		 * of a currently debugged process
2858 		 */
2859 		retval = -EBUSY;
2860 		goto failed_try_destroy_debugged_queue;
2861 
2862 	}
2863 
2864 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2865 			q->properties.type)];
2866 
2867 	deallocate_doorbell(qpd, q);
2868 
2869 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
2870 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
2871 		deallocate_sdma_queue(dqm, q);
2872 		pdd->sdma_past_activity_counter += sdma_val;
2873 	}
2874 
2875 	if (q->properties.is_active) {
2876 		decrement_queue_count(dqm, qpd, q);
2877 		q->properties.is_active = false;
2878 		if (!dqm->dev->kfd->shared_resources.enable_mes) {
2879 			retval = execute_queues_cpsch(dqm,
2880 						      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
2881 						      USE_DEFAULT_GRACE_PERIOD);
2882 			if (retval == -ETIME)
2883 				qpd->reset_wavefronts = true;
2884 		} else {
2885 			retval = remove_queue_mes(dqm, q, qpd);
2886 		}
2887 	}
2888 	list_del(&q->list);
2889 	qpd->queue_count--;
2890 
2891 	/*
2892 	 * Unconditionally decrement this counter, regardless of the queue's
2893 	 * type
2894 	 */
2895 	dqm->total_queue_count--;
2896 	pr_debug("Total of %d queues are accountable so far\n",
2897 			dqm->total_queue_count);
2898 
2899 	dqm_unlock(dqm);
2900 
2901 	/*
2902 	 * Do free_mqd and raise delete event after dqm_unlock(dqm) to avoid
2903 	 * circular locking
2904 	 */
2905 	kfd_dbg_ev_raise(KFD_EC_MASK(EC_DEVICE_QUEUE_DELETE),
2906 				qpd->pqm->process, q->device,
2907 				-1, false, NULL, 0);
2908 
2909 	/* Repin the MQD BO if still evicted for hibernation, before it is freed. */
2910 	dqm_repin_mqd_bo(dqm, q);
2911 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2912 
2913 	return retval;
2914 
2915 failed_try_destroy_debugged_queue:
2916 	q->properties.is_being_destroyed = false;
2917 	dqm_unlock(dqm);
2918 	return retval;
2919 }
2920 
2921 static bool set_cache_memory_policy(struct device_queue_manager *dqm,
2922 				   struct qcm_process_device *qpd,
2923 				   enum cache_policy default_policy,
2924 				   enum cache_policy alternate_policy,
2925 				   void __user *alternate_aperture_base,
2926 				   uint64_t alternate_aperture_size,
2927 				   u32 misc_process_properties)
2928 {
2929 	bool retval = true;
2930 
2931 	if (!dqm->asic_ops.set_cache_memory_policy)
2932 		return retval;
2933 
2934 	dqm_lock(dqm);
2935 
2936 	retval = dqm->asic_ops.set_cache_memory_policy(
2937 			dqm,
2938 			qpd,
2939 			default_policy,
2940 			alternate_policy,
2941 			alternate_aperture_base,
2942 			alternate_aperture_size,
2943 			misc_process_properties);
2944 
2945 	if (retval)
2946 		goto out;
2947 
2948 	if ((dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) && (qpd->vmid != 0))
2949 		program_sh_mem_settings(dqm, qpd);
2950 
2951 	pr_debug("sh_mem_config: 0x%x, ape1_base: 0x%x, ape1_limit: 0x%x\n",
2952 		qpd->sh_mem_config, qpd->sh_mem_ape1_base,
2953 		qpd->sh_mem_ape1_limit);
2954 
2955 out:
2956 	dqm_unlock(dqm);
2957 	return retval;
2958 }
2959 
2960 static int process_termination_nocpsch(struct device_queue_manager *dqm,
2961 		struct qcm_process_device *qpd)
2962 {
2963 	struct queue *q;
2964 	struct device_process_node *cur, *next_dpn;
2965 	int retval = 0;
2966 	bool found = false;
2967 
2968 	dqm_lock(dqm);
2969 
2970 	/* Clear all user mode queues */
2971 	while (!list_empty(&qpd->queues_list)) {
2972 		struct mqd_manager *mqd_mgr;
2973 		int ret;
2974 
2975 		q = list_first_entry(&qpd->queues_list, struct queue, list);
2976 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2977 				q->properties.type)];
2978 		ret = destroy_queue_nocpsch_locked(dqm, qpd, q);
2979 		if (ret)
2980 			retval = ret;
2981 		dqm_unlock(dqm);
2982 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2983 		dqm_lock(dqm);
2984 	}
2985 
2986 	/* Unregister process */
2987 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
2988 		if (qpd == cur->qpd) {
2989 			list_del(&cur->list);
2990 			kfree(cur);
2991 			dqm->processes_count--;
2992 			found = true;
2993 			break;
2994 		}
2995 	}
2996 
2997 	dqm_unlock(dqm);
2998 
2999 	/* Outside the DQM lock because under the DQM lock we can't do
3000 	 * reclaim or take other locks that others hold while reclaiming.
3001 	 */
3002 	if (found)
3003 		kfd_dec_compute_active(dqm->dev);
3004 
3005 	return retval;
3006 }
3007 
3008 static int get_wave_state(struct device_queue_manager *dqm,
3009 			  struct queue *q,
3010 			  void __user *ctl_stack,
3011 			  u32 *ctl_stack_used_size,
3012 			  u32 *save_area_used_size)
3013 {
3014 	struct mqd_manager *mqd_mgr;
3015 
3016 	dqm_lock(dqm);
3017 
3018 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_CP];
3019 
3020 	if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE ||
3021 	    q->properties.is_active || !q->device->kfd->cwsr_enabled ||
3022 	    !mqd_mgr->get_wave_state) {
3023 		dqm_unlock(dqm);
3024 		return -EINVAL;
3025 	}
3026 
3027 	dqm_unlock(dqm);
3028 
3029 	/*
3030 	 * get_wave_state is outside the dqm lock to prevent circular locking
3031 	 * and the queue should be protected against destruction by the process
3032 	 * lock.
3033 	 */
3034 	return mqd_mgr->get_wave_state(mqd_mgr, q->mqd, &q->properties,
3035 			ctl_stack, ctl_stack_used_size, save_area_used_size);
3036 }
3037 
3038 static int get_queue_checkpoint_info(struct device_queue_manager *dqm,
3039 			const struct queue *q,
3040 			u32 *mqd_size,
3041 			u32 *ctl_stack_size)
3042 {
3043 	struct mqd_manager *mqd_mgr;
3044 	enum KFD_MQD_TYPE mqd_type =
3045 			get_mqd_type_from_queue_type(q->properties.type);
3046 	int ret = 0;
3047 
3048 	dqm_lock(dqm);
3049 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
3050 	*mqd_size = mqd_mgr->mqd_size * NUM_XCC(mqd_mgr->dev->xcc_mask);
3051 	*ctl_stack_size = 0;
3052 
3053 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE && mqd_mgr->get_checkpoint_info)
3054 		ret = mqd_mgr->get_checkpoint_info(mqd_mgr, q->mqd, ctl_stack_size);
3055 
3056 	dqm_unlock(dqm);
3057 
3058 	return ret;
3059 }
3060 
3061 static int checkpoint_mqd(struct device_queue_manager *dqm,
3062 			  const struct queue *q,
3063 			  void *mqd,
3064 			  void *ctl_stack)
3065 {
3066 	struct mqd_manager *mqd_mgr;
3067 	int r = 0;
3068 	enum KFD_MQD_TYPE mqd_type =
3069 			get_mqd_type_from_queue_type(q->properties.type);
3070 
3071 	dqm_lock(dqm);
3072 
3073 	if (q->properties.is_active || !q->device->kfd->cwsr_enabled) {
3074 		r = -EINVAL;
3075 		goto dqm_unlock;
3076 	}
3077 
3078 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
3079 	if (!mqd_mgr->checkpoint_mqd) {
3080 		r = -EOPNOTSUPP;
3081 		goto dqm_unlock;
3082 	}
3083 
3084 	mqd_mgr->checkpoint_mqd(mqd_mgr, q->mqd, mqd, ctl_stack);
3085 
3086 dqm_unlock:
3087 	dqm_unlock(dqm);
3088 	return r;
3089 }
3090 
3091 static int process_termination_cpsch(struct device_queue_manager *dqm,
3092 		struct qcm_process_device *qpd)
3093 {
3094 	int retval = 0;
3095 	struct queue *q;
3096 	struct device *dev = dqm->dev->adev->dev;
3097 	struct kernel_queue *kq, *kq_next;
3098 	struct mqd_manager *mqd_mgr;
3099 	struct device_process_node *cur, *next_dpn;
3100 	enum kfd_unmap_queues_filter filter =
3101 		KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES;
3102 	bool found = false;
3103 
3104 	dqm_lock(dqm);
3105 
3106 	/* Clean all kernel queues */
3107 	list_for_each_entry_safe(kq, kq_next, &qpd->priv_queue_list, list) {
3108 		list_del(&kq->list);
3109 		decrement_queue_count(dqm, qpd, kq->queue);
3110 		qpd->is_debug = false;
3111 		dqm->total_queue_count--;
3112 		filter = KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES;
3113 	}
3114 
3115 	/* Clear all user mode queues */
3116 	list_for_each_entry(q, &qpd->queues_list, list) {
3117 		if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
3118 			deallocate_sdma_queue(dqm, q);
3119 		else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
3120 			deallocate_sdma_queue(dqm, q);
3121 
3122 		if (q->properties.is_active) {
3123 			decrement_queue_count(dqm, qpd, q);
3124 
3125 			if (dqm->dev->kfd->shared_resources.enable_mes) {
3126 				retval = remove_queue_mes(dqm, q, qpd);
3127 				if (retval)
3128 					dev_err(dev, "Failed to remove queue %d\n",
3129 						q->properties.queue_id);
3130 			}
3131 		}
3132 
3133 		dqm->total_queue_count--;
3134 	}
3135 
3136 	/* Unregister process */
3137 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
3138 		if (qpd == cur->qpd) {
3139 			list_del(&cur->list);
3140 			kfree(cur);
3141 			dqm->processes_count--;
3142 			found = true;
3143 			break;
3144 		}
3145 	}
3146 
3147 	if (!dqm->dev->kfd->shared_resources.enable_mes)
3148 		retval = execute_queues_cpsch(dqm, filter, 0, USE_DEFAULT_GRACE_PERIOD);
3149 
3150 	if ((retval || qpd->reset_wavefronts) &&
3151 	    down_read_trylock(&dqm->dev->adev->reset_domain->sem)) {
3152 		pr_warn("Resetting wave fronts (cpsch) on dev %p\n", dqm->dev);
3153 		dbgdev_wave_reset_wavefronts(dqm->dev, qpd->pqm->process);
3154 		qpd->reset_wavefronts = false;
3155 		up_read(&dqm->dev->adev->reset_domain->sem);
3156 	}
3157 
3158 	/* Lastly, free mqd resources.
3159 	 * Do free_mqd() after dqm_unlock to avoid circular locking.
3160 	 */
3161 	while (!list_empty(&qpd->queues_list)) {
3162 		q = list_first_entry(&qpd->queues_list, struct queue, list);
3163 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
3164 				q->properties.type)];
3165 		list_del(&q->list);
3166 		qpd->queue_count--;
3167 		dqm_unlock(dqm);
3168 		/* Repin the MQD BO if still evicted for hibernation, before free. */
3169 		dqm_repin_mqd_bo(dqm, q);
3170 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
3171 		dqm_lock(dqm);
3172 	}
3173 	dqm_unlock(dqm);
3174 
3175 	/* Outside the DQM lock because under the DQM lock we can't do
3176 	 * reclaim or take other locks that others hold while reclaiming.
3177 	 */
3178 	if (found)
3179 		kfd_dec_compute_active(dqm->dev);
3180 
3181 	return retval;
3182 }
3183 
3184 static int init_mqd_managers(struct device_queue_manager *dqm)
3185 {
3186 	int i, j;
3187 	struct device *dev = dqm->dev->adev->dev;
3188 	struct mqd_manager *mqd_mgr;
3189 
3190 	for (i = 0; i < KFD_MQD_TYPE_MAX; i++) {
3191 		mqd_mgr = dqm->asic_ops.mqd_manager_init(i, dqm->dev);
3192 		if (!mqd_mgr) {
3193 			dev_err(dev, "mqd manager [%d] initialization failed\n", i);
3194 			goto out_free;
3195 		}
3196 		dqm->mqd_mgrs[i] = mqd_mgr;
3197 	}
3198 
3199 	return 0;
3200 
3201 out_free:
3202 	for (j = 0; j < i; j++) {
3203 		kfree(dqm->mqd_mgrs[j]);
3204 		dqm->mqd_mgrs[j] = NULL;
3205 	}
3206 
3207 	return -ENOMEM;
3208 }
3209 
3210 /* Allocate one hiq mqd (HWS) and all SDMA mqd in a continuous trunk*/
3211 static int allocate_hiq_sdma_mqd(struct device_queue_manager *dqm)
3212 {
3213 	int retval;
3214 	struct kfd_node *dev = dqm->dev;
3215 	struct kfd_mem_obj *mem_obj = &dqm->hiq_sdma_mqd;
3216 	uint32_t size = dqm->mqd_mgrs[KFD_MQD_TYPE_SDMA]->mqd_size *
3217 		get_num_all_sdma_engines(dqm) *
3218 		dev->kfd->device_info.num_sdma_queues_per_engine +
3219 		(dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ]->mqd_size *
3220 		NUM_XCC(dqm->dev->xcc_mask));
3221 
3222 	retval = amdgpu_amdkfd_alloc_kernel_mem(dev->adev, size,
3223 		AMDGPU_GEM_DOMAIN_GTT,
3224 		&(mem_obj->mem), &(mem_obj->gpu_addr),
3225 		(void *)&(mem_obj->cpu_ptr), false);
3226 
3227 	return retval;
3228 }
3229 
3230 static void deallocate_hiq_sdma_mqd(struct kfd_node *dev,
3231 				    struct kfd_mem_obj *mqd)
3232 {
3233 	WARN(!mqd, "No hiq sdma mqd trunk to free");
3234 
3235 	amdgpu_amdkfd_free_kernel_mem(dev->adev, &mqd->mem);
3236 }
3237 
3238 struct device_queue_manager *device_queue_manager_init(struct kfd_node *dev)
3239 {
3240 	struct device_queue_manager *dqm;
3241 	int i;
3242 
3243 	pr_debug("Loading device queue manager\n");
3244 
3245 	dqm = kzalloc_obj(*dqm);
3246 	if (!dqm)
3247 		return NULL;
3248 
3249 	switch (dev->adev->asic_type) {
3250 	/* HWS is not available on Hawaii. */
3251 	case CHIP_HAWAII:
3252 	/* HWS depends on CWSR for timely dequeue. CWSR is not
3253 	 * available on Tonga.
3254 	 *
3255 	 * FIXME: This argument also applies to Kaveri.
3256 	 */
3257 	case CHIP_TONGA:
3258 		dqm->sched_policy = KFD_SCHED_POLICY_NO_HWS;
3259 		break;
3260 	default:
3261 		dqm->sched_policy = sched_policy;
3262 		break;
3263 	}
3264 
3265 	dqm->dev = dev;
3266 	switch (dqm->sched_policy) {
3267 	case KFD_SCHED_POLICY_HWS:
3268 	case KFD_SCHED_POLICY_HWS_NO_OVERSUBSCRIPTION:
3269 		/* initialize dqm for cp scheduling */
3270 		dqm->ops.create_queue = create_queue_cpsch;
3271 		dqm->ops.initialize = initialize_cpsch;
3272 		dqm->ops.start = start_cpsch;
3273 		dqm->ops.stop = stop_cpsch;
3274 		dqm->ops.halt = halt_cpsch;
3275 		dqm->ops.unhalt = unhalt_cpsch;
3276 		dqm->ops.destroy_queue = destroy_queue_cpsch;
3277 		dqm->ops.update_queue = update_queue;
3278 		dqm->ops.register_process = register_process;
3279 		dqm->ops.unregister_process = unregister_process;
3280 		dqm->ops.uninitialize = uninitialize;
3281 		dqm->ops.create_kernel_queue = create_kernel_queue_cpsch;
3282 		dqm->ops.destroy_kernel_queue = destroy_kernel_queue_cpsch;
3283 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
3284 		dqm->ops.process_termination = process_termination_cpsch;
3285 		dqm->ops.evict_process_queues = evict_process_queues_cpsch;
3286 		dqm->ops.restore_process_queues = restore_process_queues_cpsch;
3287 		dqm->ops.get_wave_state = get_wave_state;
3288 		dqm->ops.reset_queues = reset_queues_cpsch;
3289 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
3290 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
3291 		dqm->ops.set_perfcount = set_perfcount;
3292 		break;
3293 	case KFD_SCHED_POLICY_NO_HWS:
3294 		/* initialize dqm for no cp scheduling */
3295 		dqm->ops.start = start_nocpsch;
3296 		dqm->ops.stop = stop_nocpsch;
3297 		dqm->ops.create_queue = create_queue_nocpsch;
3298 		dqm->ops.destroy_queue = destroy_queue_nocpsch;
3299 		dqm->ops.update_queue = update_queue;
3300 		dqm->ops.register_process = register_process;
3301 		dqm->ops.unregister_process = unregister_process;
3302 		dqm->ops.initialize = initialize_nocpsch;
3303 		dqm->ops.uninitialize = uninitialize;
3304 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
3305 		dqm->ops.process_termination = process_termination_nocpsch;
3306 		dqm->ops.evict_process_queues = evict_process_queues_nocpsch;
3307 		dqm->ops.restore_process_queues =
3308 			restore_process_queues_nocpsch;
3309 		dqm->ops.get_wave_state = get_wave_state;
3310 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
3311 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
3312 		dqm->ops.set_perfcount = set_perfcount;
3313 		break;
3314 	default:
3315 		dev_err(dev->adev->dev, "Invalid scheduling policy %d\n", dqm->sched_policy);
3316 		goto out_free;
3317 	}
3318 
3319 	switch (dev->adev->asic_type) {
3320 	case CHIP_KAVERI:
3321 	case CHIP_HAWAII:
3322 		device_queue_manager_init_cik(&dqm->asic_ops);
3323 		break;
3324 
3325 	case CHIP_CARRIZO:
3326 	case CHIP_TONGA:
3327 	case CHIP_FIJI:
3328 	case CHIP_POLARIS10:
3329 	case CHIP_POLARIS11:
3330 	case CHIP_POLARIS12:
3331 	case CHIP_VEGAM:
3332 		device_queue_manager_init_vi(&dqm->asic_ops);
3333 		break;
3334 
3335 	default:
3336 		if (KFD_GC_VERSION(dev) >= IP_VERSION(12, 1, 0))
3337 			device_queue_manager_init_v12_1(&dqm->asic_ops);
3338 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(12, 0, 0))
3339 			device_queue_manager_init_v12(&dqm->asic_ops);
3340 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(11, 0, 0))
3341 			device_queue_manager_init_v11(&dqm->asic_ops);
3342 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(10, 1, 1))
3343 			device_queue_manager_init_v10(&dqm->asic_ops);
3344 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(9, 0, 1))
3345 			device_queue_manager_init_v9(&dqm->asic_ops);
3346 		else {
3347 			WARN(1, "Unexpected ASIC family %u",
3348 			     dev->adev->asic_type);
3349 			goto out_free;
3350 		}
3351 	}
3352 
3353 	if (init_mqd_managers(dqm))
3354 		goto out_free;
3355 
3356 	if (!dev->kfd->shared_resources.enable_mes && allocate_hiq_sdma_mqd(dqm)) {
3357 		dev_err(dev->adev->dev, "Failed to allocate hiq sdma mqd trunk buffer\n");
3358 		goto out_free;
3359 	}
3360 
3361 	if (!dqm->ops.initialize(dqm)) {
3362 		init_waitqueue_head(&dqm->destroy_wait);
3363 		return dqm;
3364 	}
3365 
3366 	if (!dev->kfd->shared_resources.enable_mes)
3367 		deallocate_hiq_sdma_mqd(dev, &dqm->hiq_sdma_mqd);
3368 
3369 out_free:
3370 	for (i = 0; i < KFD_MQD_TYPE_MAX; i++)
3371 		kfree(dqm->mqd_mgrs[i]);
3372 
3373 	kfree(dqm);
3374 	return NULL;
3375 }
3376 
3377 void device_queue_manager_uninit(struct device_queue_manager *dqm)
3378 {
3379 	dqm->ops.stop(dqm);
3380 	dqm->ops.uninitialize(dqm);
3381 	if (!dqm->dev->kfd->shared_resources.enable_mes)
3382 		deallocate_hiq_sdma_mqd(dqm->dev, &dqm->hiq_sdma_mqd);
3383 	kfree(dqm);
3384 }
3385 
3386 /* bad queue notified by interrupt from CP */
3387 int kfd_dqm_suspend_bad_queue_mes(struct kfd_node *knode, u32 pasid, u32 doorbell_id)
3388 {
3389 	struct kfd_process_device *pdd = NULL;
3390 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid, &pdd);
3391 	struct device_queue_manager *dqm = knode->dqm;
3392 	struct qcm_process_device *qpd;
3393 	struct queue *q = NULL;
3394 	int ret = 0;
3395 
3396 	if (!pdd)
3397 		return -EINVAL;
3398 
3399 	dqm_lock(dqm);
3400 
3401 	if (pdd) {
3402 		qpd = &pdd->qpd;
3403 
3404 		list_for_each_entry(q, &qpd->queues_list, list) {
3405 			if (q->doorbell_id == doorbell_id && q->properties.is_active) {
3406 				reset_queues_mes(dqm, q);
3407 				q->properties.is_evicted = true;
3408 				q->properties.is_active = false;
3409 				decrement_queue_count(dqm, qpd, q);
3410 				break;
3411 			}
3412 		}
3413 	}
3414 
3415 	dqm_unlock(dqm);
3416 	kfd_unref_process(p);
3417 	return ret;
3418 }
3419 
3420 int kfd_evict_process_device(struct kfd_process_device *pdd)
3421 {
3422 	struct device_queue_manager *dqm;
3423 	struct kfd_process *p;
3424 
3425 	p = pdd->process;
3426 	dqm = pdd->dev->dqm;
3427 
3428 	WARN(debug_evictions, "Evicting pid %d", p->lead_thread->pid);
3429 
3430 	return dqm->ops.evict_process_queues(dqm, &pdd->qpd);
3431 }
3432 
3433 int reserve_debug_trap_vmid(struct device_queue_manager *dqm,
3434 				struct qcm_process_device *qpd)
3435 {
3436 	int r;
3437 	struct device *dev = dqm->dev->adev->dev;
3438 	int updated_vmid_mask;
3439 
3440 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3441 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3442 		return -EINVAL;
3443 	}
3444 
3445 	dqm_lock(dqm);
3446 
3447 	if (dqm->trap_debug_vmid != 0) {
3448 		dev_err(dev, "Trap debug id already reserved\n");
3449 		r = -EBUSY;
3450 		goto out_unlock;
3451 	}
3452 
3453 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
3454 			USE_DEFAULT_GRACE_PERIOD, false);
3455 	if (r)
3456 		goto out_unlock;
3457 
3458 	updated_vmid_mask = dqm->dev->kfd->shared_resources.compute_vmid_bitmap;
3459 	updated_vmid_mask &= ~(1 << dqm->dev->vm_info.last_vmid_kfd);
3460 
3461 	dqm->dev->kfd->shared_resources.compute_vmid_bitmap = updated_vmid_mask;
3462 	dqm->trap_debug_vmid = dqm->dev->vm_info.last_vmid_kfd;
3463 	r = set_sched_resources(dqm);
3464 	if (r)
3465 		goto out_unlock;
3466 
3467 	r = map_queues_cpsch(dqm);
3468 	if (r)
3469 		goto out_unlock;
3470 
3471 	pr_debug("Reserved VMID for trap debug: %i\n", dqm->trap_debug_vmid);
3472 
3473 out_unlock:
3474 	dqm_unlock(dqm);
3475 	return r;
3476 }
3477 
3478 /*
3479  * Releases vmid for the trap debugger
3480  */
3481 int release_debug_trap_vmid(struct device_queue_manager *dqm,
3482 			struct qcm_process_device *qpd)
3483 {
3484 	struct device *dev = dqm->dev->adev->dev;
3485 	int r;
3486 	int updated_vmid_mask;
3487 	uint32_t trap_debug_vmid;
3488 
3489 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3490 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3491 		return -EINVAL;
3492 	}
3493 
3494 	dqm_lock(dqm);
3495 	trap_debug_vmid = dqm->trap_debug_vmid;
3496 	if (dqm->trap_debug_vmid == 0) {
3497 		dev_err(dev, "Trap debug id is not reserved\n");
3498 		r = -EINVAL;
3499 		goto out_unlock;
3500 	}
3501 
3502 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
3503 			USE_DEFAULT_GRACE_PERIOD, false);
3504 	if (r)
3505 		goto out_unlock;
3506 
3507 	updated_vmid_mask = dqm->dev->kfd->shared_resources.compute_vmid_bitmap;
3508 	updated_vmid_mask |= (1 << dqm->dev->vm_info.last_vmid_kfd);
3509 
3510 	dqm->dev->kfd->shared_resources.compute_vmid_bitmap = updated_vmid_mask;
3511 	dqm->trap_debug_vmid = 0;
3512 	r = set_sched_resources(dqm);
3513 	if (r)
3514 		goto out_unlock;
3515 
3516 	r = map_queues_cpsch(dqm);
3517 	if (r)
3518 		goto out_unlock;
3519 
3520 	pr_debug("Released VMID for trap debug: %i\n", trap_debug_vmid);
3521 
3522 out_unlock:
3523 	dqm_unlock(dqm);
3524 	return r;
3525 }
3526 
3527 #define QUEUE_NOT_FOUND		-1
3528 /* invalidate queue operation in array */
3529 static void q_array_invalidate(uint32_t num_queues, uint32_t *queue_ids)
3530 {
3531 	int i;
3532 
3533 	for (i = 0; i < num_queues; i++)
3534 		queue_ids[i] |= KFD_DBG_QUEUE_INVALID_MASK;
3535 }
3536 
3537 /* find queue index in array */
3538 static int q_array_get_index(unsigned int queue_id,
3539 		uint32_t num_queues,
3540 		uint32_t *queue_ids)
3541 {
3542 	int i;
3543 
3544 	for (i = 0; i < num_queues; i++)
3545 		if (queue_id == (queue_ids[i] & ~KFD_DBG_QUEUE_INVALID_MASK))
3546 			return i;
3547 
3548 	return QUEUE_NOT_FOUND;
3549 }
3550 
3551 struct copy_context_work_handler_workarea {
3552 	struct work_struct copy_context_work;
3553 	struct kfd_process *p;
3554 };
3555 
3556 static void copy_context_work_handler(struct work_struct *work)
3557 {
3558 	struct copy_context_work_handler_workarea *workarea;
3559 	struct mqd_manager *mqd_mgr;
3560 	struct queue *q;
3561 	struct mm_struct *mm;
3562 	struct kfd_process *p;
3563 	uint32_t tmp_ctl_stack_used_size, tmp_save_area_used_size;
3564 	int i;
3565 
3566 	workarea = container_of(work,
3567 			struct copy_context_work_handler_workarea,
3568 			copy_context_work);
3569 
3570 	p = workarea->p;
3571 	mm = get_task_mm(p->lead_thread);
3572 
3573 	if (!mm)
3574 		return;
3575 
3576 	kthread_use_mm(mm);
3577 	for (i = 0; i < p->n_pdds; i++) {
3578 		struct kfd_process_device *pdd = p->pdds[i];
3579 		struct device_queue_manager *dqm = pdd->dev->dqm;
3580 		struct qcm_process_device *qpd = &pdd->qpd;
3581 
3582 		list_for_each_entry(q, &qpd->queues_list, list) {
3583 			if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE)
3584 				continue;
3585 
3586 			mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_CP];
3587 
3588 			/* We ignore the return value from get_wave_state
3589 			 * because
3590 			 * i) right now, it always returns 0, and
3591 			 * ii) if we hit an error, we would continue to the
3592 			 *      next queue anyway.
3593 			 */
3594 			mqd_mgr->get_wave_state(mqd_mgr,
3595 					q->mqd,
3596 					&q->properties,
3597 					(void __user *)	q->properties.ctx_save_restore_area_address,
3598 					&tmp_ctl_stack_used_size,
3599 					&tmp_save_area_used_size);
3600 		}
3601 	}
3602 	kthread_unuse_mm(mm);
3603 	mmput(mm);
3604 }
3605 
3606 static uint32_t *get_queue_ids(uint32_t num_queues, uint32_t *usr_queue_id_array)
3607 {
3608 	if (!usr_queue_id_array)
3609 		return num_queues ? ERR_PTR(-EINVAL) : NULL;
3610 
3611 	if (num_queues > KFD_MAX_NUM_OF_QUEUES_PER_PROCESS)
3612 		return ERR_PTR(-EINVAL);
3613 
3614 	return memdup_user(usr_queue_id_array,
3615 			   array_size(num_queues, sizeof(uint32_t)));
3616 }
3617 
3618 int resume_queues(struct kfd_process *p,
3619 		uint32_t num_queues,
3620 		uint32_t *usr_queue_id_array)
3621 {
3622 	uint32_t *queue_ids = NULL;
3623 	int total_resumed = 0;
3624 	int i;
3625 
3626 	if (usr_queue_id_array) {
3627 		queue_ids = get_queue_ids(num_queues, usr_queue_id_array);
3628 
3629 		if (IS_ERR(queue_ids))
3630 			return PTR_ERR(queue_ids);
3631 
3632 		/* mask all queues as invalid.  unmask per successful request */
3633 		q_array_invalidate(num_queues, queue_ids);
3634 	}
3635 
3636 	for (i = 0; i < p->n_pdds; i++) {
3637 		struct kfd_process_device *pdd = p->pdds[i];
3638 		struct device_queue_manager *dqm = pdd->dev->dqm;
3639 		struct device *dev = dqm->dev->adev->dev;
3640 		struct qcm_process_device *qpd = &pdd->qpd;
3641 		struct queue *q;
3642 		int r, per_device_resumed = 0;
3643 
3644 		dqm_lock(dqm);
3645 
3646 		/* unmask queues that resume or already resumed as valid */
3647 		list_for_each_entry(q, &qpd->queues_list, list) {
3648 			int q_idx = QUEUE_NOT_FOUND;
3649 
3650 			if (queue_ids)
3651 				q_idx = q_array_get_index(
3652 						q->properties.queue_id,
3653 						num_queues,
3654 						queue_ids);
3655 
3656 			if (!queue_ids || q_idx != QUEUE_NOT_FOUND) {
3657 				int err = resume_single_queue(dqm, &pdd->qpd, q);
3658 
3659 				if (queue_ids) {
3660 					if (!err) {
3661 						queue_ids[q_idx] &=
3662 							~KFD_DBG_QUEUE_INVALID_MASK;
3663 					} else {
3664 						queue_ids[q_idx] |=
3665 							KFD_DBG_QUEUE_ERROR_MASK;
3666 						break;
3667 					}
3668 				}
3669 
3670 				if (dqm->dev->kfd->shared_resources.enable_mes) {
3671 					wake_up_all(&dqm->destroy_wait);
3672 					if (!err)
3673 						total_resumed++;
3674 				} else {
3675 					per_device_resumed++;
3676 				}
3677 			}
3678 		}
3679 
3680 		if (!per_device_resumed) {
3681 			dqm_unlock(dqm);
3682 			continue;
3683 		}
3684 
3685 		r = execute_queues_cpsch(dqm,
3686 					KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES,
3687 					0,
3688 					USE_DEFAULT_GRACE_PERIOD);
3689 		if (r) {
3690 			dev_err(dev, "Failed to resume process queues\n");
3691 			if (queue_ids) {
3692 				list_for_each_entry(q, &qpd->queues_list, list) {
3693 					int q_idx = q_array_get_index(
3694 							q->properties.queue_id,
3695 							num_queues,
3696 							queue_ids);
3697 
3698 					/* mask queue as error on resume fail */
3699 					if (q_idx != QUEUE_NOT_FOUND)
3700 						queue_ids[q_idx] |=
3701 							KFD_DBG_QUEUE_ERROR_MASK;
3702 				}
3703 			}
3704 		} else {
3705 			wake_up_all(&dqm->destroy_wait);
3706 			total_resumed += per_device_resumed;
3707 		}
3708 
3709 		dqm_unlock(dqm);
3710 	}
3711 
3712 	if (queue_ids) {
3713 		if (copy_to_user((void __user *)usr_queue_id_array, queue_ids,
3714 				num_queues * sizeof(uint32_t)))
3715 			pr_err("copy_to_user failed on queue resume\n");
3716 
3717 		kfree(queue_ids);
3718 	}
3719 
3720 	return total_resumed;
3721 }
3722 
3723 int suspend_queues(struct kfd_process *p,
3724 			uint32_t num_queues,
3725 			uint32_t grace_period,
3726 			uint64_t exception_clear_mask,
3727 			uint32_t *usr_queue_id_array)
3728 {
3729 	uint32_t *queue_ids = get_queue_ids(num_queues, usr_queue_id_array);
3730 	int total_suspended = 0;
3731 	int i;
3732 
3733 	if (IS_ERR(queue_ids))
3734 		return PTR_ERR(queue_ids);
3735 
3736 	/* mask all queues as invalid.  umask on successful request */
3737 	q_array_invalidate(num_queues, queue_ids);
3738 
3739 	for (i = 0; i < p->n_pdds; i++) {
3740 		struct kfd_process_device *pdd = p->pdds[i];
3741 		struct device_queue_manager *dqm = pdd->dev->dqm;
3742 		struct device *dev = dqm->dev->adev->dev;
3743 		struct qcm_process_device *qpd = &pdd->qpd;
3744 		struct queue *q;
3745 		int r, per_device_suspended = 0;
3746 
3747 		mutex_lock(&p->event_mutex);
3748 		dqm_lock(dqm);
3749 
3750 		/* unmask queues that suspend or already suspended */
3751 		list_for_each_entry(q, &qpd->queues_list, list) {
3752 			int q_idx = q_array_get_index(q->properties.queue_id,
3753 							num_queues,
3754 							queue_ids);
3755 
3756 			if (q_idx != QUEUE_NOT_FOUND) {
3757 				int err = suspend_single_queue(dqm, pdd, q);
3758 				bool is_mes = dqm->dev->kfd->shared_resources.enable_mes;
3759 
3760 				if (!err) {
3761 					queue_ids[q_idx] &= ~KFD_DBG_QUEUE_INVALID_MASK;
3762 					if (exception_clear_mask && is_mes)
3763 						q->properties.exception_status &=
3764 							~exception_clear_mask;
3765 
3766 					if (is_mes)
3767 						total_suspended++;
3768 					else
3769 						per_device_suspended++;
3770 				} else if (err != -EBUSY) {
3771 					queue_ids[q_idx] |= KFD_DBG_QUEUE_ERROR_MASK;
3772 					break;
3773 				}
3774 			}
3775 		}
3776 
3777 		if (!per_device_suspended) {
3778 			dqm_unlock(dqm);
3779 			mutex_unlock(&p->event_mutex);
3780 			if (total_suspended) {
3781 				amdgpu_amdkfd_debug_mem_fence(dqm->dev->adev);
3782 				/* Heavy-weight TLB flush after MES suspends queues */
3783 				kfd_flush_tlb(pdd);
3784 			}
3785 			continue;
3786 		}
3787 
3788 		r = execute_queues_cpsch(dqm,
3789 			KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
3790 			grace_period);
3791 
3792 		if (r)
3793 			dev_err(dev, "Failed to suspend process queues.\n");
3794 		else
3795 			total_suspended += per_device_suspended;
3796 
3797 		list_for_each_entry(q, &qpd->queues_list, list) {
3798 			int q_idx = q_array_get_index(q->properties.queue_id,
3799 						num_queues, queue_ids);
3800 
3801 			if (q_idx == QUEUE_NOT_FOUND)
3802 				continue;
3803 
3804 			/* mask queue as error on suspend fail */
3805 			if (r)
3806 				queue_ids[q_idx] |= KFD_DBG_QUEUE_ERROR_MASK;
3807 			else if (exception_clear_mask)
3808 				q->properties.exception_status &=
3809 							~exception_clear_mask;
3810 		}
3811 
3812 		dqm_unlock(dqm);
3813 		mutex_unlock(&p->event_mutex);
3814 		amdgpu_device_flush_hdp(dqm->dev->adev, NULL);
3815 	}
3816 
3817 	if (total_suspended) {
3818 		struct copy_context_work_handler_workarea copy_context_worker;
3819 
3820 		INIT_WORK_ONSTACK(
3821 				&copy_context_worker.copy_context_work,
3822 				copy_context_work_handler);
3823 
3824 		copy_context_worker.p = p;
3825 
3826 		schedule_work(&copy_context_worker.copy_context_work);
3827 
3828 
3829 		flush_work(&copy_context_worker.copy_context_work);
3830 		destroy_work_on_stack(&copy_context_worker.copy_context_work);
3831 	}
3832 
3833 	if (copy_to_user((void __user *)usr_queue_id_array, queue_ids,
3834 			num_queues * sizeof(uint32_t)))
3835 		pr_err("copy_to_user failed on queue suspend\n");
3836 
3837 	kfree(queue_ids);
3838 
3839 	return total_suspended;
3840 }
3841 
3842 static uint32_t set_queue_type_for_user(struct queue_properties *q_props)
3843 {
3844 	switch (q_props->type) {
3845 	case KFD_QUEUE_TYPE_COMPUTE:
3846 		return q_props->format == KFD_QUEUE_FORMAT_PM4
3847 					? KFD_IOC_QUEUE_TYPE_COMPUTE
3848 					: KFD_IOC_QUEUE_TYPE_COMPUTE_AQL;
3849 	case KFD_QUEUE_TYPE_SDMA:
3850 		return KFD_IOC_QUEUE_TYPE_SDMA;
3851 	case KFD_QUEUE_TYPE_SDMA_XGMI:
3852 		return KFD_IOC_QUEUE_TYPE_SDMA_XGMI;
3853 	default:
3854 		WARN_ONCE(true, "queue type not recognized!");
3855 		return 0xffffffff;
3856 	};
3857 }
3858 
3859 void set_queue_snapshot_entry(struct queue *q,
3860 			      uint64_t exception_clear_mask,
3861 			      struct kfd_queue_snapshot_entry *qss_entry)
3862 {
3863 	qss_entry->ring_base_address = q->properties.queue_address;
3864 	qss_entry->write_pointer_address = (uint64_t)q->properties.write_ptr;
3865 	qss_entry->read_pointer_address = (uint64_t)q->properties.read_ptr;
3866 	qss_entry->ctx_save_restore_address =
3867 				q->properties.ctx_save_restore_area_address;
3868 	qss_entry->ctx_save_restore_area_size =
3869 				q->properties.ctx_save_restore_area_size;
3870 	qss_entry->exception_status = q->properties.exception_status;
3871 	qss_entry->queue_id = q->properties.queue_id;
3872 	qss_entry->gpu_id = q->device->id;
3873 	qss_entry->ring_size = (uint32_t)q->properties.queue_size;
3874 	qss_entry->queue_type = set_queue_type_for_user(&q->properties);
3875 	q->properties.exception_status &= ~exception_clear_mask;
3876 }
3877 
3878 int debug_lock_and_unmap(struct device_queue_manager *dqm)
3879 {
3880 	struct device *dev = dqm->dev->adev->dev;
3881 	int r;
3882 
3883 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3884 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3885 		return -EINVAL;
3886 	}
3887 
3888 	if (!kfd_dbg_is_per_vmid_supported(dqm->dev))
3889 		return 0;
3890 
3891 	dqm_lock(dqm);
3892 
3893 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0, 0, false);
3894 	if (r)
3895 		dqm_unlock(dqm);
3896 
3897 	return r;
3898 }
3899 
3900 int debug_map_and_unlock(struct device_queue_manager *dqm)
3901 {
3902 	struct device *dev = dqm->dev->adev->dev;
3903 	int r;
3904 
3905 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3906 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3907 		return -EINVAL;
3908 	}
3909 
3910 	if (!kfd_dbg_is_per_vmid_supported(dqm->dev))
3911 		return 0;
3912 
3913 	r = map_queues_cpsch(dqm);
3914 
3915 	dqm_unlock(dqm);
3916 
3917 	return r;
3918 }
3919 
3920 int debug_refresh_runlist(struct device_queue_manager *dqm)
3921 {
3922 	int r = debug_lock_and_unmap(dqm);
3923 
3924 	if (r)
3925 		return r;
3926 
3927 	return debug_map_and_unlock(dqm);
3928 }
3929 
3930 bool kfd_dqm_is_queue_in_process(struct device_queue_manager *dqm,
3931 				 struct qcm_process_device *qpd,
3932 				 int doorbell_off, u32 *queue_format)
3933 {
3934 	struct queue *q;
3935 	bool r = false;
3936 
3937 	if (!queue_format)
3938 		return r;
3939 
3940 	dqm_lock(dqm);
3941 
3942 	list_for_each_entry(q, &qpd->queues_list, list) {
3943 		if (q->properties.doorbell_off == doorbell_off) {
3944 			*queue_format = q->properties.format;
3945 			r = true;
3946 			goto out;
3947 		}
3948 	}
3949 
3950 out:
3951 	dqm_unlock(dqm);
3952 	return r;
3953 }
3954 
3955 size_t mqd_size_from_queue_type(struct device_queue_manager *dqm, enum kfd_queue_type type)
3956 {
3957 	return dqm->mqd_mgrs[get_mqd_type_from_queue_type(type)]->mqd_size;
3958 }
3959 
3960 #if defined(CONFIG_DEBUG_FS)
3961 
3962 static void seq_reg_dump(struct seq_file *m,
3963 			 uint32_t (*dump)[2], uint32_t n_regs)
3964 {
3965 	uint32_t i, count;
3966 
3967 	for (i = 0, count = 0; i < n_regs; i++) {
3968 		if (count == 0 ||
3969 		    dump[i-1][0] + sizeof(uint32_t) != dump[i][0]) {
3970 			seq_printf(m, "%s    %08x: %08x",
3971 				   i ? "\n" : "",
3972 				   dump[i][0], dump[i][1]);
3973 			count = 7;
3974 		} else {
3975 			seq_printf(m, " %08x", dump[i][1]);
3976 			count--;
3977 		}
3978 	}
3979 
3980 	seq_puts(m, "\n");
3981 }
3982 
3983 int dqm_debugfs_hqds(struct seq_file *m, void *data)
3984 {
3985 	struct device_queue_manager *dqm = data;
3986 	uint32_t xcc_mask = dqm->dev->xcc_mask;
3987 	uint32_t (*dump)[2], n_regs;
3988 	int pipe, queue;
3989 	int r = 0, xcc_id;
3990 	uint32_t sdma_engine_start;
3991 
3992 	if (!dqm->sched_running) {
3993 		seq_puts(m, " Device is stopped\n");
3994 		return 0;
3995 	}
3996 
3997 	for_each_inst(xcc_id, xcc_mask) {
3998 		r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->adev,
3999 						KFD_CIK_HIQ_PIPE,
4000 						KFD_CIK_HIQ_QUEUE, &dump,
4001 						&n_regs, xcc_id);
4002 		if (!r) {
4003 			seq_printf(
4004 				m,
4005 				"   Inst %d, HIQ on MEC %d Pipe %d Queue %d\n",
4006 				xcc_id,
4007 				KFD_CIK_HIQ_PIPE / get_pipes_per_mec(dqm) + 1,
4008 				KFD_CIK_HIQ_PIPE % get_pipes_per_mec(dqm),
4009 				KFD_CIK_HIQ_QUEUE);
4010 			seq_reg_dump(m, dump, n_regs);
4011 
4012 			kfree(dump);
4013 		}
4014 
4015 		for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
4016 			int pipe_offset = pipe * get_queues_per_pipe(dqm);
4017 
4018 			for (queue = 0; queue < get_queues_per_pipe(dqm); queue++) {
4019 				if (!test_bit(pipe_offset + queue,
4020 				      dqm->dev->kfd->shared_resources.cp_queue_bitmap))
4021 					continue;
4022 
4023 				r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->adev,
4024 								pipe, queue,
4025 								&dump, &n_regs,
4026 								xcc_id);
4027 				if (r)
4028 					break;
4029 
4030 				seq_printf(m,
4031 					   " Inst %d,  CP Pipe %d, Queue %d\n",
4032 					   xcc_id, pipe, queue);
4033 				seq_reg_dump(m, dump, n_regs);
4034 
4035 				kfree(dump);
4036 			}
4037 		}
4038 	}
4039 
4040 	sdma_engine_start = dqm->dev->node_id * get_num_all_sdma_engines(dqm);
4041 	for (pipe = sdma_engine_start;
4042 	     pipe < (sdma_engine_start + get_num_all_sdma_engines(dqm));
4043 	     pipe++) {
4044 		for (queue = 0;
4045 		     queue < dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
4046 		     queue++) {
4047 			r = dqm->dev->kfd2kgd->hqd_sdma_dump(
4048 				dqm->dev->adev, pipe, queue, &dump, &n_regs);
4049 			if (r)
4050 				break;
4051 
4052 			seq_printf(m, "  SDMA Engine %d, RLC %d\n",
4053 				  pipe, queue);
4054 			seq_reg_dump(m, dump, n_regs);
4055 
4056 			kfree(dump);
4057 		}
4058 	}
4059 
4060 	return r;
4061 }
4062 
4063 int dqm_debugfs_hang_hws(struct device_queue_manager *dqm)
4064 {
4065 	int r = 0;
4066 
4067 	dqm_lock(dqm);
4068 	r = pm_debugfs_hang_hws(&dqm->packet_mgr);
4069 	if (r) {
4070 		dqm_unlock(dqm);
4071 		return r;
4072 	}
4073 	dqm->active_runlist = true;
4074 	r = execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES,
4075 				0, USE_DEFAULT_GRACE_PERIOD);
4076 	dqm_unlock(dqm);
4077 
4078 	return r;
4079 }
4080 
4081 #endif
4082