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