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