xref: /linux/drivers/gpu/drm/amd/amdkfd/kfd_device_queue_manager.c (revision face6a3615a649456eb4549f6d474221d877d604)
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 	if (dqm->dev->kfd->shared_resources.enable_mes) {
1213 		pdd->last_evict_timestamp = get_jiffies_64();
1214 		retval = suspend_all_queues_mes(dqm);
1215 		if (retval) {
1216 			dev_err(dev, "Suspending all queues failed");
1217 			goto out;
1218 		}
1219 	}
1220 
1221 	/* Mark all queues as evicted. Deactivate all active queues on
1222 	 * the qpd.
1223 	 */
1224 	list_for_each_entry(q, &qpd->queues_list, list) {
1225 		q->properties.is_evicted = true;
1226 		if (!q->properties.is_active)
1227 			continue;
1228 
1229 		q->properties.is_active = false;
1230 		decrement_queue_count(dqm, qpd, q);
1231 
1232 		if (dqm->dev->kfd->shared_resources.enable_mes) {
1233 			retval = remove_queue_mes(dqm, q, qpd);
1234 			if (retval) {
1235 				dev_err(dev, "Failed to evict queue %d\n",
1236 					q->properties.queue_id);
1237 				goto out;
1238 			}
1239 		}
1240 	}
1241 
1242 	if (!dqm->dev->kfd->shared_resources.enable_mes) {
1243 		pdd->last_evict_timestamp = get_jiffies_64();
1244 		retval = execute_queues_cpsch(dqm,
1245 					      qpd->is_debug ?
1246 					      KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES :
1247 					      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
1248 					      USE_DEFAULT_GRACE_PERIOD);
1249 	} else {
1250 		retval = resume_all_queues_mes(dqm);
1251 		if (retval)
1252 			dev_err(dev, "Resuming all queues failed");
1253 	}
1254 
1255 out:
1256 	dqm_unlock(dqm);
1257 	return retval;
1258 }
1259 
1260 static int restore_process_queues_nocpsch(struct device_queue_manager *dqm,
1261 					  struct qcm_process_device *qpd)
1262 {
1263 	struct mm_struct *mm = NULL;
1264 	struct queue *q;
1265 	struct mqd_manager *mqd_mgr;
1266 	struct kfd_process_device *pdd;
1267 	uint64_t pd_base;
1268 	uint64_t eviction_duration;
1269 	int retval, ret = 0;
1270 
1271 	pdd = qpd_to_pdd(qpd);
1272 	/* Retrieve PD base */
1273 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1274 
1275 	dqm_lock(dqm);
1276 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
1277 		goto out;
1278 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
1279 		qpd->evicted--;
1280 		goto out;
1281 	}
1282 
1283 	pr_debug_ratelimited("Restoring process pid %d queues\n",
1284 			    pdd->process->lead_thread->pid);
1285 
1286 	/* Update PD Base in QPD */
1287 	qpd->page_table_base = pd_base;
1288 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
1289 
1290 	if (!list_empty(&qpd->queues_list)) {
1291 		dqm->dev->kfd2kgd->set_vm_context_page_table_base(
1292 				dqm->dev->adev,
1293 				qpd->vmid,
1294 				qpd->page_table_base);
1295 		kfd_flush_tlb(pdd, TLB_FLUSH_LEGACY);
1296 	}
1297 
1298 	/* Take a safe reference to the mm_struct, which may otherwise
1299 	 * disappear even while the kfd_process is still referenced.
1300 	 */
1301 	mm = get_task_mm(pdd->process->lead_thread);
1302 	if (!mm) {
1303 		ret = -EFAULT;
1304 		goto out;
1305 	}
1306 
1307 	/* Remove the eviction flags. Activate queues that are not
1308 	 * inactive for other reasons.
1309 	 */
1310 	list_for_each_entry(q, &qpd->queues_list, list) {
1311 		q->properties.is_evicted = false;
1312 		if (!QUEUE_IS_ACTIVE(q->properties))
1313 			continue;
1314 
1315 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1316 				q->properties.type)];
1317 		q->properties.is_active = true;
1318 		increment_queue_count(dqm, qpd, q);
1319 
1320 		if (WARN_ONCE(!dqm->sched_running, "Restore when stopped\n"))
1321 			continue;
1322 
1323 		retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd, q->pipe,
1324 				       q->queue, &q->properties, mm);
1325 		if (retval && !ret)
1326 			/* Return the first error, but keep going to
1327 			 * maintain a consistent eviction state
1328 			 */
1329 			ret = retval;
1330 	}
1331 	qpd->evicted = 0;
1332 	eviction_duration = get_jiffies_64() - pdd->last_evict_timestamp;
1333 	atomic64_add(eviction_duration, &pdd->evict_duration_counter);
1334 out:
1335 	if (mm)
1336 		mmput(mm);
1337 	dqm_unlock(dqm);
1338 	return ret;
1339 }
1340 
1341 static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
1342 					struct qcm_process_device *qpd)
1343 {
1344 	struct queue *q;
1345 	struct device *dev = dqm->dev->adev->dev;
1346 	struct kfd_process_device *pdd;
1347 	uint64_t eviction_duration;
1348 	int retval = 0;
1349 
1350 	pdd = qpd_to_pdd(qpd);
1351 
1352 	dqm_lock(dqm);
1353 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
1354 		goto out;
1355 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
1356 		qpd->evicted--;
1357 		goto out;
1358 	}
1359 
1360 	/* The debugger creates processes that temporarily have not acquired
1361 	 * all VMs for all devices and has no VMs itself.
1362 	 * Skip queue restore on process restore.
1363 	 */
1364 	if (!pdd->drm_priv)
1365 		goto vm_not_acquired;
1366 
1367 	pr_debug_ratelimited("Restoring process pid %d queues\n",
1368 			    pdd->process->lead_thread->pid);
1369 
1370 	/* Update PD Base in QPD */
1371 	qpd->page_table_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1372 	pr_debug("Updated PD address to 0x%llx\n", qpd->page_table_base);
1373 
1374 	/* activate all active queues on the qpd */
1375 	list_for_each_entry(q, &qpd->queues_list, list) {
1376 		q->properties.is_evicted = false;
1377 		if (!QUEUE_IS_ACTIVE(q->properties))
1378 			continue;
1379 
1380 		q->properties.is_active = true;
1381 		increment_queue_count(dqm, &pdd->qpd, q);
1382 
1383 		if (dqm->dev->kfd->shared_resources.enable_mes) {
1384 			retval = add_queue_mes(dqm, q, qpd);
1385 			if (retval) {
1386 				dev_err(dev, "Failed to restore queue %d\n",
1387 					q->properties.queue_id);
1388 				goto out;
1389 			}
1390 		}
1391 	}
1392 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1393 		retval = execute_queues_cpsch(dqm,
1394 					      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD);
1395 	eviction_duration = get_jiffies_64() - pdd->last_evict_timestamp;
1396 	atomic64_add(eviction_duration, &pdd->evict_duration_counter);
1397 vm_not_acquired:
1398 	qpd->evicted = 0;
1399 out:
1400 	dqm_unlock(dqm);
1401 	return retval;
1402 }
1403 
1404 static int register_process(struct device_queue_manager *dqm,
1405 					struct qcm_process_device *qpd)
1406 {
1407 	struct device_process_node *n;
1408 	struct kfd_process_device *pdd;
1409 	uint64_t pd_base;
1410 	int retval;
1411 
1412 	n = kzalloc(sizeof(*n), GFP_KERNEL);
1413 	if (!n)
1414 		return -ENOMEM;
1415 
1416 	n->qpd = qpd;
1417 
1418 	pdd = qpd_to_pdd(qpd);
1419 	/* Retrieve PD base */
1420 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1421 
1422 	dqm_lock(dqm);
1423 	list_add(&n->list, &dqm->queues);
1424 
1425 	/* Update PD Base in QPD */
1426 	qpd->page_table_base = pd_base;
1427 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
1428 
1429 	retval = dqm->asic_ops.update_qpd(dqm, qpd);
1430 
1431 	dqm->processes_count++;
1432 
1433 	dqm_unlock(dqm);
1434 
1435 	/* Outside the DQM lock because under the DQM lock we can't do
1436 	 * reclaim or take other locks that others hold while reclaiming.
1437 	 */
1438 	kfd_inc_compute_active(dqm->dev);
1439 
1440 	return retval;
1441 }
1442 
1443 static int unregister_process(struct device_queue_manager *dqm,
1444 					struct qcm_process_device *qpd)
1445 {
1446 	int retval;
1447 	struct device_process_node *cur, *next;
1448 
1449 	pr_debug("qpd->queues_list is %s\n",
1450 			list_empty(&qpd->queues_list) ? "empty" : "not empty");
1451 
1452 	retval = 0;
1453 	dqm_lock(dqm);
1454 
1455 	list_for_each_entry_safe(cur, next, &dqm->queues, list) {
1456 		if (qpd == cur->qpd) {
1457 			list_del(&cur->list);
1458 			kfree(cur);
1459 			dqm->processes_count--;
1460 			goto out;
1461 		}
1462 	}
1463 	/* qpd not found in dqm list */
1464 	retval = 1;
1465 out:
1466 	dqm_unlock(dqm);
1467 
1468 	/* Outside the DQM lock because under the DQM lock we can't do
1469 	 * reclaim or take other locks that others hold while reclaiming.
1470 	 */
1471 	if (!retval)
1472 		kfd_dec_compute_active(dqm->dev);
1473 
1474 	return retval;
1475 }
1476 
1477 static int
1478 set_pasid_vmid_mapping(struct device_queue_manager *dqm, u32 pasid,
1479 			unsigned int vmid)
1480 {
1481 	uint32_t xcc_mask = dqm->dev->xcc_mask;
1482 	int xcc_id, ret;
1483 
1484 	for_each_inst(xcc_id, xcc_mask) {
1485 		ret = dqm->dev->kfd2kgd->set_pasid_vmid_mapping(
1486 			dqm->dev->adev, pasid, vmid, xcc_id);
1487 		if (ret)
1488 			break;
1489 	}
1490 
1491 	return ret;
1492 }
1493 
1494 static void init_interrupts(struct device_queue_manager *dqm)
1495 {
1496 	uint32_t xcc_mask = dqm->dev->xcc_mask;
1497 	unsigned int i, xcc_id;
1498 
1499 	for_each_inst(xcc_id, xcc_mask) {
1500 		for (i = 0 ; i < get_pipes_per_mec(dqm) ; i++) {
1501 			if (is_pipe_enabled(dqm, 0, i)) {
1502 				dqm->dev->kfd2kgd->init_interrupts(
1503 					dqm->dev->adev, i, xcc_id);
1504 			}
1505 		}
1506 	}
1507 }
1508 
1509 static int initialize_nocpsch(struct device_queue_manager *dqm)
1510 {
1511 	int pipe, queue;
1512 
1513 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
1514 
1515 	dqm->allocated_queues = kcalloc(get_pipes_per_mec(dqm),
1516 					sizeof(unsigned int), GFP_KERNEL);
1517 	if (!dqm->allocated_queues)
1518 		return -ENOMEM;
1519 
1520 	mutex_init(&dqm->lock_hidden);
1521 	INIT_LIST_HEAD(&dqm->queues);
1522 	dqm->active_queue_count = dqm->next_pipe_to_allocate = 0;
1523 	dqm->active_cp_queue_count = 0;
1524 	dqm->gws_queue_count = 0;
1525 
1526 	for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
1527 		int pipe_offset = pipe * get_queues_per_pipe(dqm);
1528 
1529 		for (queue = 0; queue < get_queues_per_pipe(dqm); queue++)
1530 			if (test_bit(pipe_offset + queue,
1531 				     dqm->dev->kfd->shared_resources.cp_queue_bitmap))
1532 				dqm->allocated_queues[pipe] |= 1 << queue;
1533 	}
1534 
1535 	memset(dqm->vmid_pasid, 0, sizeof(dqm->vmid_pasid));
1536 
1537 	init_sdma_bitmaps(dqm);
1538 
1539 	return 0;
1540 }
1541 
1542 static void uninitialize(struct device_queue_manager *dqm)
1543 {
1544 	int i;
1545 
1546 	WARN_ON(dqm->active_queue_count > 0 || dqm->processes_count > 0);
1547 
1548 	kfree(dqm->allocated_queues);
1549 	for (i = 0 ; i < KFD_MQD_TYPE_MAX ; i++)
1550 		kfree(dqm->mqd_mgrs[i]);
1551 	mutex_destroy(&dqm->lock_hidden);
1552 }
1553 
1554 static int start_nocpsch(struct device_queue_manager *dqm)
1555 {
1556 	int r = 0;
1557 
1558 	pr_info("SW scheduler is used");
1559 	init_interrupts(dqm);
1560 
1561 	if (dqm->dev->adev->asic_type == CHIP_HAWAII)
1562 		r = pm_init(&dqm->packet_mgr, dqm);
1563 	if (!r)
1564 		dqm->sched_running = true;
1565 
1566 	return r;
1567 }
1568 
1569 static int stop_nocpsch(struct device_queue_manager *dqm)
1570 {
1571 	dqm_lock(dqm);
1572 	if (!dqm->sched_running) {
1573 		dqm_unlock(dqm);
1574 		return 0;
1575 	}
1576 
1577 	if (dqm->dev->adev->asic_type == CHIP_HAWAII)
1578 		pm_uninit(&dqm->packet_mgr);
1579 	dqm->sched_running = false;
1580 	dqm_unlock(dqm);
1581 
1582 	return 0;
1583 }
1584 
1585 static int allocate_sdma_queue(struct device_queue_manager *dqm,
1586 				struct queue *q, const uint32_t *restore_sdma_id)
1587 {
1588 	struct device *dev = dqm->dev->adev->dev;
1589 	int bit;
1590 
1591 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1592 		if (bitmap_empty(dqm->sdma_bitmap, get_num_sdma_queues(dqm))) {
1593 			dev_warn(dev, "No more SDMA queue to allocate (%d total queues)\n",
1594 				 get_num_sdma_queues(dqm));
1595 			return -ENOMEM;
1596 		}
1597 
1598 		if (restore_sdma_id) {
1599 			/* Re-use existing sdma_id */
1600 			if (!test_bit(*restore_sdma_id, dqm->sdma_bitmap)) {
1601 				dev_err(dev, "SDMA queue already in use\n");
1602 				return -EBUSY;
1603 			}
1604 			clear_bit(*restore_sdma_id, dqm->sdma_bitmap);
1605 			q->sdma_id = *restore_sdma_id;
1606 		} else {
1607 			/* Find first available sdma_id */
1608 			bit = find_first_bit(dqm->sdma_bitmap,
1609 					     get_num_sdma_queues(dqm));
1610 			clear_bit(bit, dqm->sdma_bitmap);
1611 			q->sdma_id = bit;
1612 		}
1613 
1614 		q->properties.sdma_engine_id =
1615 			q->sdma_id % kfd_get_num_sdma_engines(dqm->dev);
1616 		q->properties.sdma_queue_id = q->sdma_id /
1617 				kfd_get_num_sdma_engines(dqm->dev);
1618 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1619 		if (bitmap_empty(dqm->xgmi_sdma_bitmap, get_num_xgmi_sdma_queues(dqm))) {
1620 			dev_warn(dev, "No more XGMI SDMA queue to allocate (%d total queues)\n",
1621 				 get_num_xgmi_sdma_queues(dqm));
1622 			return -ENOMEM;
1623 		}
1624 		if (restore_sdma_id) {
1625 			/* Re-use existing sdma_id */
1626 			if (!test_bit(*restore_sdma_id, dqm->xgmi_sdma_bitmap)) {
1627 				dev_err(dev, "SDMA queue already in use\n");
1628 				return -EBUSY;
1629 			}
1630 			clear_bit(*restore_sdma_id, dqm->xgmi_sdma_bitmap);
1631 			q->sdma_id = *restore_sdma_id;
1632 		} else {
1633 			bit = find_first_bit(dqm->xgmi_sdma_bitmap,
1634 					     get_num_xgmi_sdma_queues(dqm));
1635 			clear_bit(bit, dqm->xgmi_sdma_bitmap);
1636 			q->sdma_id = bit;
1637 		}
1638 		/* sdma_engine_id is sdma id including
1639 		 * both PCIe-optimized SDMAs and XGMI-
1640 		 * optimized SDMAs. The calculation below
1641 		 * assumes the first N engines are always
1642 		 * PCIe-optimized ones
1643 		 */
1644 		q->properties.sdma_engine_id =
1645 			kfd_get_num_sdma_engines(dqm->dev) +
1646 			q->sdma_id % kfd_get_num_xgmi_sdma_engines(dqm->dev);
1647 		q->properties.sdma_queue_id = q->sdma_id /
1648 			kfd_get_num_xgmi_sdma_engines(dqm->dev);
1649 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_BY_ENG_ID) {
1650 		int i, num_queues, num_engines, eng_offset = 0, start_engine;
1651 		bool free_bit_found = false, is_xgmi = false;
1652 
1653 		if (q->properties.sdma_engine_id < kfd_get_num_sdma_engines(dqm->dev)) {
1654 			num_queues = get_num_sdma_queues(dqm);
1655 			num_engines = kfd_get_num_sdma_engines(dqm->dev);
1656 			q->properties.type = KFD_QUEUE_TYPE_SDMA;
1657 		} else {
1658 			num_queues = get_num_xgmi_sdma_queues(dqm);
1659 			num_engines = kfd_get_num_xgmi_sdma_engines(dqm->dev);
1660 			eng_offset = kfd_get_num_sdma_engines(dqm->dev);
1661 			q->properties.type = KFD_QUEUE_TYPE_SDMA_XGMI;
1662 			is_xgmi = true;
1663 		}
1664 
1665 		/* Scan available bit based on target engine ID. */
1666 		start_engine = q->properties.sdma_engine_id - eng_offset;
1667 		for (i = start_engine; i < num_queues; i += num_engines) {
1668 
1669 			if (!test_bit(i, is_xgmi ? dqm->xgmi_sdma_bitmap : dqm->sdma_bitmap))
1670 				continue;
1671 
1672 			clear_bit(i, is_xgmi ? dqm->xgmi_sdma_bitmap : dqm->sdma_bitmap);
1673 			q->sdma_id = i;
1674 			q->properties.sdma_queue_id = q->sdma_id / num_engines;
1675 			free_bit_found = true;
1676 			break;
1677 		}
1678 
1679 		if (!free_bit_found) {
1680 			dev_warn(dev, "No more SDMA queue to allocate for target ID %i (%d total queues)\n",
1681 				 q->properties.sdma_engine_id, num_queues);
1682 			return -ENOMEM;
1683 		}
1684 	}
1685 
1686 	pr_debug("SDMA engine id: %d\n", q->properties.sdma_engine_id);
1687 	pr_debug("SDMA queue id: %d\n", q->properties.sdma_queue_id);
1688 
1689 	return 0;
1690 }
1691 
1692 static void deallocate_sdma_queue(struct device_queue_manager *dqm,
1693 				struct queue *q)
1694 {
1695 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1696 		if (q->sdma_id >= get_num_sdma_queues(dqm))
1697 			return;
1698 		set_bit(q->sdma_id, dqm->sdma_bitmap);
1699 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1700 		if (q->sdma_id >= get_num_xgmi_sdma_queues(dqm))
1701 			return;
1702 		set_bit(q->sdma_id, dqm->xgmi_sdma_bitmap);
1703 	}
1704 }
1705 
1706 /*
1707  * Device Queue Manager implementation for cp scheduler
1708  */
1709 
1710 static int set_sched_resources(struct device_queue_manager *dqm)
1711 {
1712 	int i, mec;
1713 	struct scheduling_resources res;
1714 	struct device *dev = dqm->dev->adev->dev;
1715 
1716 	res.vmid_mask = dqm->dev->compute_vmid_bitmap;
1717 
1718 	res.queue_mask = 0;
1719 	for (i = 0; i < AMDGPU_MAX_QUEUES; ++i) {
1720 		mec = (i / dqm->dev->kfd->shared_resources.num_queue_per_pipe)
1721 			/ dqm->dev->kfd->shared_resources.num_pipe_per_mec;
1722 
1723 		if (!test_bit(i, dqm->dev->kfd->shared_resources.cp_queue_bitmap))
1724 			continue;
1725 
1726 		/* only acquire queues from the first MEC */
1727 		if (mec > 0)
1728 			continue;
1729 
1730 		/* This situation may be hit in the future if a new HW
1731 		 * generation exposes more than 64 queues. If so, the
1732 		 * definition of res.queue_mask needs updating
1733 		 */
1734 		if (WARN_ON(i >= (sizeof(res.queue_mask)*8))) {
1735 			dev_err(dev, "Invalid queue enabled by amdgpu: %d\n", i);
1736 			break;
1737 		}
1738 
1739 		res.queue_mask |= 1ull
1740 			<< amdgpu_queue_mask_bit_to_set_resource_bit(
1741 				dqm->dev->adev, i);
1742 	}
1743 	res.gws_mask = ~0ull;
1744 	res.oac_mask = res.gds_heap_base = res.gds_heap_size = 0;
1745 
1746 	pr_debug("Scheduling resources:\n"
1747 			"vmid mask: 0x%8X\n"
1748 			"queue mask: 0x%8llX\n",
1749 			res.vmid_mask, res.queue_mask);
1750 
1751 	return pm_send_set_resources(&dqm->packet_mgr, &res);
1752 }
1753 
1754 static int initialize_cpsch(struct device_queue_manager *dqm)
1755 {
1756 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
1757 
1758 	mutex_init(&dqm->lock_hidden);
1759 	INIT_LIST_HEAD(&dqm->queues);
1760 	dqm->active_queue_count = dqm->processes_count = 0;
1761 	dqm->active_cp_queue_count = 0;
1762 	dqm->gws_queue_count = 0;
1763 	dqm->active_runlist = false;
1764 	dqm->trap_debug_vmid = 0;
1765 
1766 	init_sdma_bitmaps(dqm);
1767 
1768 	update_dqm_wait_times(dqm);
1769 	return 0;
1770 }
1771 
1772 /* halt_cpsch:
1773  * Unmap queues so the schedule doesn't continue remaining jobs in the queue.
1774  * Then set dqm->sched_halt so queues don't map to runlist until unhalt_cpsch
1775  * is called.
1776  */
1777 static int halt_cpsch(struct device_queue_manager *dqm)
1778 {
1779 	int ret = 0;
1780 
1781 	dqm_lock(dqm);
1782 	if (!dqm->sched_running) {
1783 		dqm_unlock(dqm);
1784 		return 0;
1785 	}
1786 
1787 	WARN_ONCE(dqm->sched_halt, "Scheduling is already on halt\n");
1788 
1789 	if (!dqm->is_hws_hang) {
1790 		if (!dqm->dev->kfd->shared_resources.enable_mes)
1791 			ret = unmap_queues_cpsch(dqm,
1792 						 KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
1793 				USE_DEFAULT_GRACE_PERIOD, false);
1794 		else
1795 			ret = remove_all_kfd_queues_mes(dqm);
1796 	}
1797 	dqm->sched_halt = true;
1798 	dqm_unlock(dqm);
1799 
1800 	return ret;
1801 }
1802 
1803 /* unhalt_cpsch
1804  * Unset dqm->sched_halt and map queues back to runlist
1805  */
1806 static int unhalt_cpsch(struct device_queue_manager *dqm)
1807 {
1808 	int ret = 0;
1809 
1810 	dqm_lock(dqm);
1811 	if (!dqm->sched_running || !dqm->sched_halt) {
1812 		WARN_ONCE(!dqm->sched_halt, "Scheduling is not on halt.\n");
1813 		dqm_unlock(dqm);
1814 		return 0;
1815 	}
1816 	dqm->sched_halt = false;
1817 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1818 		ret = execute_queues_cpsch(dqm,
1819 					   KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES,
1820 			0, USE_DEFAULT_GRACE_PERIOD);
1821 	else
1822 		ret = add_all_kfd_queues_mes(dqm);
1823 
1824 	dqm_unlock(dqm);
1825 
1826 	return ret;
1827 }
1828 
1829 static int start_cpsch(struct device_queue_manager *dqm)
1830 {
1831 	struct device *dev = dqm->dev->adev->dev;
1832 	int retval, num_hw_queue_slots;
1833 
1834 	retval = 0;
1835 
1836 	dqm_lock(dqm);
1837 
1838 	if (!dqm->dev->kfd->shared_resources.enable_mes) {
1839 		retval = pm_init(&dqm->packet_mgr, dqm);
1840 		if (retval)
1841 			goto fail_packet_manager_init;
1842 
1843 		retval = set_sched_resources(dqm);
1844 		if (retval)
1845 			goto fail_set_sched_resources;
1846 	}
1847 	pr_debug("Allocating fence memory\n");
1848 
1849 	/* allocate fence memory on the gart */
1850 	retval = kfd_gtt_sa_allocate(dqm->dev, sizeof(*dqm->fence_addr),
1851 					&dqm->fence_mem);
1852 
1853 	if (retval)
1854 		goto fail_allocate_vidmem;
1855 
1856 	dqm->fence_addr = (uint64_t *)dqm->fence_mem->cpu_ptr;
1857 	dqm->fence_gpu_addr = dqm->fence_mem->gpu_addr;
1858 
1859 	init_interrupts(dqm);
1860 
1861 	/* clear hang status when driver try to start the hw scheduler */
1862 	dqm->sched_running = true;
1863 
1864 	if (!dqm->dev->kfd->shared_resources.enable_mes) {
1865 		if (pm_config_dequeue_wait_counts(&dqm->packet_mgr,
1866 				KFD_DEQUEUE_WAIT_INIT, 0 /* unused */))
1867 			dev_err(dev, "Setting optimized dequeue wait failed. Using default values\n");
1868 		execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD);
1869 	}
1870 
1871 	/* setup per-queue reset detection buffer  */
1872 	num_hw_queue_slots =  dqm->dev->kfd->shared_resources.num_queue_per_pipe *
1873 			      dqm->dev->kfd->shared_resources.num_pipe_per_mec *
1874 			      NUM_XCC(dqm->dev->xcc_mask);
1875 
1876 	dqm->detect_hang_info_size = num_hw_queue_slots * sizeof(struct dqm_detect_hang_info);
1877 	dqm->detect_hang_info = kzalloc(dqm->detect_hang_info_size, GFP_KERNEL);
1878 
1879 	if (!dqm->detect_hang_info) {
1880 		retval = -ENOMEM;
1881 		goto fail_detect_hang_buffer;
1882 	}
1883 
1884 	dqm_unlock(dqm);
1885 
1886 	return 0;
1887 fail_detect_hang_buffer:
1888 	kfd_gtt_sa_free(dqm->dev, dqm->fence_mem);
1889 fail_allocate_vidmem:
1890 fail_set_sched_resources:
1891 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1892 		pm_uninit(&dqm->packet_mgr);
1893 fail_packet_manager_init:
1894 	dqm_unlock(dqm);
1895 	return retval;
1896 }
1897 
1898 static int stop_cpsch(struct device_queue_manager *dqm)
1899 {
1900 	int ret = 0;
1901 
1902 	dqm_lock(dqm);
1903 	if (!dqm->sched_running) {
1904 		dqm_unlock(dqm);
1905 		return 0;
1906 	}
1907 
1908 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1909 		ret = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES,
1910 								0, USE_DEFAULT_GRACE_PERIOD, false);
1911 	else
1912 		ret = remove_all_kfd_queues_mes(dqm);
1913 
1914 	dqm->sched_running = false;
1915 
1916 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1917 		pm_release_ib(&dqm->packet_mgr);
1918 
1919 	kfd_gtt_sa_free(dqm->dev, dqm->fence_mem);
1920 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1921 		pm_uninit(&dqm->packet_mgr);
1922 	kfree(dqm->detect_hang_info);
1923 	dqm->detect_hang_info = NULL;
1924 	dqm_unlock(dqm);
1925 
1926 	return ret;
1927 }
1928 
1929 static int create_kernel_queue_cpsch(struct device_queue_manager *dqm,
1930 					struct kernel_queue *kq,
1931 					struct qcm_process_device *qpd)
1932 {
1933 	dqm_lock(dqm);
1934 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1935 		pr_warn("Can't create new kernel queue because %d queues were already created\n",
1936 				dqm->total_queue_count);
1937 		dqm_unlock(dqm);
1938 		return -EPERM;
1939 	}
1940 
1941 	/*
1942 	 * Unconditionally increment this counter, regardless of the queue's
1943 	 * type or whether the queue is active.
1944 	 */
1945 	dqm->total_queue_count++;
1946 	pr_debug("Total of %d queues are accountable so far\n",
1947 			dqm->total_queue_count);
1948 
1949 	list_add(&kq->list, &qpd->priv_queue_list);
1950 	increment_queue_count(dqm, qpd, kq->queue);
1951 	qpd->is_debug = true;
1952 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
1953 			USE_DEFAULT_GRACE_PERIOD);
1954 	dqm_unlock(dqm);
1955 
1956 	return 0;
1957 }
1958 
1959 static void destroy_kernel_queue_cpsch(struct device_queue_manager *dqm,
1960 					struct kernel_queue *kq,
1961 					struct qcm_process_device *qpd)
1962 {
1963 	dqm_lock(dqm);
1964 	list_del(&kq->list);
1965 	decrement_queue_count(dqm, qpd, kq->queue);
1966 	qpd->is_debug = false;
1967 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
1968 			USE_DEFAULT_GRACE_PERIOD);
1969 	/*
1970 	 * Unconditionally decrement this counter, regardless of the queue's
1971 	 * type.
1972 	 */
1973 	dqm->total_queue_count--;
1974 	pr_debug("Total of %d queues are accountable so far\n",
1975 			dqm->total_queue_count);
1976 	dqm_unlock(dqm);
1977 }
1978 
1979 static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
1980 			struct qcm_process_device *qpd,
1981 			const struct kfd_criu_queue_priv_data *qd,
1982 			const void *restore_mqd, const void *restore_ctl_stack)
1983 {
1984 	int retval;
1985 	struct mqd_manager *mqd_mgr;
1986 
1987 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1988 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
1989 				dqm->total_queue_count);
1990 		retval = -EPERM;
1991 		goto out;
1992 	}
1993 
1994 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1995 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI ||
1996 		q->properties.type == KFD_QUEUE_TYPE_SDMA_BY_ENG_ID) {
1997 		dqm_lock(dqm);
1998 		retval = allocate_sdma_queue(dqm, q, qd ? &qd->sdma_id : NULL);
1999 		dqm_unlock(dqm);
2000 		if (retval)
2001 			goto out;
2002 	}
2003 
2004 	retval = allocate_doorbell(qpd, q, qd ? &qd->doorbell_id : NULL);
2005 	if (retval)
2006 		goto out_deallocate_sdma_queue;
2007 
2008 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2009 			q->properties.type)];
2010 
2011 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
2012 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
2013 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
2014 	q->properties.tba_addr = qpd->tba_addr;
2015 	q->properties.tma_addr = qpd->tma_addr;
2016 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr->dev, &q->properties);
2017 	if (!q->mqd_mem_obj) {
2018 		retval = -ENOMEM;
2019 		goto out_deallocate_doorbell;
2020 	}
2021 
2022 	dqm_lock(dqm);
2023 	/*
2024 	 * Eviction state logic: mark all queues as evicted, even ones
2025 	 * not currently active. Restoring inactive queues later only
2026 	 * updates the is_evicted flag but is a no-op otherwise.
2027 	 */
2028 	q->properties.is_evicted = !!qpd->evicted;
2029 	q->properties.is_dbg_wa = qpd->pqm->process->debug_trap_enabled &&
2030 				  kfd_dbg_has_cwsr_workaround(q->device);
2031 
2032 	if (qd)
2033 		mqd_mgr->restore_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj, &q->gart_mqd_addr,
2034 				     &q->properties, restore_mqd, restore_ctl_stack,
2035 				     qd->ctl_stack_size);
2036 	else
2037 		mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
2038 					&q->gart_mqd_addr, &q->properties);
2039 
2040 	list_add(&q->list, &qpd->queues_list);
2041 	qpd->queue_count++;
2042 
2043 	if (q->properties.is_active) {
2044 		increment_queue_count(dqm, qpd, q);
2045 
2046 		if (!dqm->dev->kfd->shared_resources.enable_mes)
2047 			retval = execute_queues_cpsch(dqm,
2048 					KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD);
2049 		else
2050 			retval = add_queue_mes(dqm, q, qpd);
2051 		if (retval)
2052 			goto cleanup_queue;
2053 	}
2054 
2055 	/*
2056 	 * Unconditionally increment this counter, regardless of the queue's
2057 	 * type or whether the queue is active.
2058 	 */
2059 	dqm->total_queue_count++;
2060 
2061 	pr_debug("Total of %d queues are accountable so far\n",
2062 			dqm->total_queue_count);
2063 
2064 	dqm_unlock(dqm);
2065 	return retval;
2066 
2067 cleanup_queue:
2068 	qpd->queue_count--;
2069 	list_del(&q->list);
2070 	if (q->properties.is_active)
2071 		decrement_queue_count(dqm, qpd, q);
2072 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2073 	dqm_unlock(dqm);
2074 out_deallocate_doorbell:
2075 	deallocate_doorbell(qpd, q);
2076 out_deallocate_sdma_queue:
2077 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
2078 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
2079 		dqm_lock(dqm);
2080 		deallocate_sdma_queue(dqm, q);
2081 		dqm_unlock(dqm);
2082 	}
2083 out:
2084 	return retval;
2085 }
2086 
2087 int amdkfd_fence_wait_timeout(struct device_queue_manager *dqm,
2088 			      uint64_t fence_value,
2089 			      unsigned int timeout_ms)
2090 {
2091 	unsigned long end_jiffies = msecs_to_jiffies(timeout_ms) + jiffies;
2092 	struct device *dev = dqm->dev->adev->dev;
2093 	uint64_t *fence_addr = dqm->fence_addr;
2094 
2095 	while (*fence_addr != fence_value) {
2096 		/* Fatal err detected, this response won't come */
2097 		if (amdgpu_amdkfd_is_fed(dqm->dev->adev))
2098 			return -EIO;
2099 
2100 		if (time_after(jiffies, end_jiffies)) {
2101 			dev_err(dev, "qcm fence wait loop timeout expired\n");
2102 			/* In HWS case, this is used to halt the driver thread
2103 			 * in order not to mess up CP states before doing
2104 			 * scandumps for FW debugging.
2105 			 */
2106 			while (halt_if_hws_hang)
2107 				schedule();
2108 
2109 			return -ETIME;
2110 		}
2111 		schedule();
2112 	}
2113 
2114 	return 0;
2115 }
2116 
2117 /* dqm->lock mutex has to be locked before calling this function */
2118 static int map_queues_cpsch(struct device_queue_manager *dqm)
2119 {
2120 	struct device *dev = dqm->dev->adev->dev;
2121 	int retval;
2122 
2123 	if (!dqm->sched_running || dqm->sched_halt)
2124 		return 0;
2125 	if (dqm->active_queue_count <= 0 || dqm->processes_count <= 0)
2126 		return 0;
2127 	if (dqm->active_runlist)
2128 		return 0;
2129 
2130 	retval = pm_send_runlist(&dqm->packet_mgr, &dqm->queues);
2131 	pr_debug("%s sent runlist\n", __func__);
2132 	if (retval) {
2133 		dev_err(dev, "failed to execute runlist\n");
2134 		return retval;
2135 	}
2136 	dqm->active_runlist = true;
2137 
2138 	return retval;
2139 }
2140 
2141 static void set_queue_as_reset(struct device_queue_manager *dqm, struct queue *q,
2142 			       struct qcm_process_device *qpd)
2143 {
2144 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
2145 
2146 	dev_err(dqm->dev->adev->dev, "queue id 0x%0x at pasid %d is reset\n",
2147 		q->properties.queue_id, pdd->process->lead_thread->pid);
2148 
2149 	pdd->has_reset_queue = true;
2150 	if (q->properties.is_active) {
2151 		q->properties.is_active = false;
2152 		decrement_queue_count(dqm, qpd, q);
2153 	}
2154 }
2155 
2156 static int detect_queue_hang(struct device_queue_manager *dqm)
2157 {
2158 	int i;
2159 
2160 	/* detect should be used only in dqm locked queue reset */
2161 	if (WARN_ON(dqm->detect_hang_count > 0))
2162 		return 0;
2163 
2164 	memset(dqm->detect_hang_info, 0, dqm->detect_hang_info_size);
2165 
2166 	for (i = 0; i < AMDGPU_MAX_QUEUES; ++i) {
2167 		uint32_t mec, pipe, queue;
2168 		int xcc_id;
2169 
2170 		mec = (i / dqm->dev->kfd->shared_resources.num_queue_per_pipe)
2171 			/ dqm->dev->kfd->shared_resources.num_pipe_per_mec;
2172 
2173 		if (mec || !test_bit(i, dqm->dev->kfd->shared_resources.cp_queue_bitmap))
2174 			continue;
2175 
2176 		amdgpu_queue_mask_bit_to_mec_queue(dqm->dev->adev, i, &mec, &pipe, &queue);
2177 
2178 		for_each_inst(xcc_id, dqm->dev->xcc_mask) {
2179 			uint64_t queue_addr = dqm->dev->kfd2kgd->hqd_get_pq_addr(
2180 						dqm->dev->adev, pipe, queue, xcc_id);
2181 			struct dqm_detect_hang_info hang_info;
2182 
2183 			if (!queue_addr)
2184 				continue;
2185 
2186 			hang_info.pipe_id = pipe;
2187 			hang_info.queue_id = queue;
2188 			hang_info.xcc_id = xcc_id;
2189 			hang_info.queue_address = queue_addr;
2190 
2191 			dqm->detect_hang_info[dqm->detect_hang_count] = hang_info;
2192 			dqm->detect_hang_count++;
2193 		}
2194 	}
2195 
2196 	return dqm->detect_hang_count;
2197 }
2198 
2199 static struct queue *find_queue_by_address(struct device_queue_manager *dqm, uint64_t queue_address)
2200 {
2201 	struct device_process_node *cur;
2202 	struct qcm_process_device *qpd;
2203 	struct queue *q;
2204 
2205 	list_for_each_entry(cur, &dqm->queues, list) {
2206 		qpd = cur->qpd;
2207 		list_for_each_entry(q, &qpd->queues_list, list) {
2208 			if (queue_address == q->properties.queue_address)
2209 				return q;
2210 		}
2211 	}
2212 
2213 	return NULL;
2214 }
2215 
2216 static int reset_hung_queues(struct device_queue_manager *dqm)
2217 {
2218 	int r = 0, reset_count = 0, i;
2219 
2220 	if (!dqm->detect_hang_info || dqm->is_hws_hang)
2221 		return -EIO;
2222 
2223 	/* assume dqm locked. */
2224 	if (!detect_queue_hang(dqm))
2225 		return -ENOTRECOVERABLE;
2226 
2227 	for (i = 0; i < dqm->detect_hang_count; i++) {
2228 		struct dqm_detect_hang_info hang_info = dqm->detect_hang_info[i];
2229 		struct queue *q = find_queue_by_address(dqm, hang_info.queue_address);
2230 		struct kfd_process_device *pdd;
2231 		uint64_t queue_addr = 0;
2232 
2233 		if (!q) {
2234 			r = -ENOTRECOVERABLE;
2235 			goto reset_fail;
2236 		}
2237 
2238 		pdd = kfd_get_process_device_data(dqm->dev, q->process);
2239 		if (!pdd) {
2240 			r = -ENOTRECOVERABLE;
2241 			goto reset_fail;
2242 		}
2243 
2244 		queue_addr = dqm->dev->kfd2kgd->hqd_reset(dqm->dev->adev,
2245 				hang_info.pipe_id, hang_info.queue_id, hang_info.xcc_id,
2246 				KFD_UNMAP_LATENCY_MS);
2247 
2248 		/* either reset failed or we reset an unexpected queue. */
2249 		if (queue_addr != q->properties.queue_address) {
2250 			r = -ENOTRECOVERABLE;
2251 			goto reset_fail;
2252 		}
2253 
2254 		set_queue_as_reset(dqm, q, &pdd->qpd);
2255 		reset_count++;
2256 	}
2257 
2258 	if (reset_count == dqm->detect_hang_count)
2259 		kfd_signal_reset_event(dqm->dev);
2260 	else
2261 		r = -ENOTRECOVERABLE;
2262 
2263 reset_fail:
2264 	dqm->detect_hang_count = 0;
2265 
2266 	return r;
2267 }
2268 
2269 static bool sdma_has_hang(struct device_queue_manager *dqm)
2270 {
2271 	int engine_start = dqm->dev->node_id * get_num_all_sdma_engines(dqm);
2272 	int engine_end = engine_start + get_num_all_sdma_engines(dqm);
2273 	int num_queues_per_eng =  dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
2274 	int i, j;
2275 
2276 	for (i = engine_start; i < engine_end; i++) {
2277 		for (j = 0; j < num_queues_per_eng; j++) {
2278 			if (!dqm->dev->kfd2kgd->hqd_sdma_get_doorbell(dqm->dev->adev, i, j))
2279 				continue;
2280 
2281 			return true;
2282 		}
2283 	}
2284 
2285 	return false;
2286 }
2287 
2288 static bool set_sdma_queue_as_reset(struct device_queue_manager *dqm,
2289 				    uint32_t doorbell_off)
2290 {
2291 	struct device_process_node *cur;
2292 	struct qcm_process_device *qpd;
2293 	struct queue *q;
2294 
2295 	list_for_each_entry(cur, &dqm->queues, list) {
2296 		qpd = cur->qpd;
2297 		list_for_each_entry(q, &qpd->queues_list, list) {
2298 			if ((q->properties.type == KFD_QUEUE_TYPE_SDMA ||
2299 			     q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) &&
2300 			     q->properties.doorbell_off == doorbell_off) {
2301 				set_queue_as_reset(dqm, q, qpd);
2302 				return true;
2303 			}
2304 		}
2305 	}
2306 
2307 	return false;
2308 }
2309 
2310 static int reset_hung_queues_sdma(struct device_queue_manager *dqm)
2311 {
2312 	int engine_start = dqm->dev->node_id * get_num_all_sdma_engines(dqm);
2313 	int engine_end = engine_start + get_num_all_sdma_engines(dqm);
2314 	int num_queues_per_eng =  dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
2315 	int r = 0, i, j;
2316 
2317 	if (dqm->is_hws_hang)
2318 		return -EIO;
2319 
2320 	/* Scan for hung HW queues and reset engine. */
2321 	dqm->detect_hang_count = 0;
2322 	for (i = engine_start; i < engine_end; i++) {
2323 		for (j = 0; j < num_queues_per_eng; j++) {
2324 			uint32_t doorbell_off =
2325 				dqm->dev->kfd2kgd->hqd_sdma_get_doorbell(dqm->dev->adev, i, j);
2326 
2327 			if (!doorbell_off)
2328 				continue;
2329 
2330 			/* Reset engine and check. */
2331 			if (amdgpu_sdma_reset_engine(dqm->dev->adev, i, false) ||
2332 			    dqm->dev->kfd2kgd->hqd_sdma_get_doorbell(dqm->dev->adev, i, j) ||
2333 			    !set_sdma_queue_as_reset(dqm, doorbell_off)) {
2334 				r = -ENOTRECOVERABLE;
2335 				goto reset_fail;
2336 			}
2337 
2338 			/* Should only expect one queue active per engine */
2339 			dqm->detect_hang_count++;
2340 			break;
2341 		}
2342 	}
2343 
2344 	/* Signal process reset */
2345 	if (dqm->detect_hang_count)
2346 		kfd_signal_reset_event(dqm->dev);
2347 	else
2348 		r = -ENOTRECOVERABLE;
2349 
2350 reset_fail:
2351 	dqm->detect_hang_count = 0;
2352 
2353 	return r;
2354 }
2355 
2356 static int reset_queues_on_hws_hang(struct device_queue_manager *dqm, bool is_sdma)
2357 {
2358 	struct amdgpu_device *adev = dqm->dev->adev;
2359 
2360 	while (halt_if_hws_hang)
2361 		schedule();
2362 
2363 	if (adev->debug_disable_gpu_ring_reset) {
2364 		dev_info_once(adev->dev,
2365 			      "%s queue hung, but ring reset disabled",
2366 			      is_sdma ? "sdma" : "compute");
2367 
2368 		return -EPERM;
2369 	}
2370 	if (!amdgpu_gpu_recovery)
2371 		return -ENOTRECOVERABLE;
2372 
2373 	return is_sdma ? reset_hung_queues_sdma(dqm) : reset_hung_queues(dqm);
2374 }
2375 
2376 /* dqm->lock mutex has to be locked before calling this function
2377  *
2378  * @grace_period: If USE_DEFAULT_GRACE_PERIOD then default wait time
2379  *   for context switch latency. Lower values are used by debugger
2380  *   since context switching are triggered at high frequency.
2381  *   This is configured by setting CP_IQ_WAIT_TIME2.SCH_WAVE
2382  *
2383  */
2384 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
2385 				enum kfd_unmap_queues_filter filter,
2386 				uint32_t filter_param,
2387 				uint32_t grace_period,
2388 				bool reset)
2389 {
2390 	struct device *dev = dqm->dev->adev->dev;
2391 	struct mqd_manager *mqd_mgr;
2392 	int retval;
2393 
2394 	if (!dqm->sched_running)
2395 		return 0;
2396 	if (!dqm->active_runlist)
2397 		return 0;
2398 	if (!down_read_trylock(&dqm->dev->adev->reset_domain->sem))
2399 		return -EIO;
2400 
2401 	if (grace_period != USE_DEFAULT_GRACE_PERIOD) {
2402 		retval = pm_config_dequeue_wait_counts(&dqm->packet_mgr,
2403 				KFD_DEQUEUE_WAIT_SET_SCH_WAVE, grace_period);
2404 		if (retval)
2405 			goto out;
2406 	}
2407 
2408 	retval = pm_send_unmap_queue(&dqm->packet_mgr, filter, filter_param, reset);
2409 	if (retval)
2410 		goto out;
2411 
2412 	*dqm->fence_addr = KFD_FENCE_INIT;
2413 	mb();
2414 	pm_send_query_status(&dqm->packet_mgr, dqm->fence_gpu_addr,
2415 				KFD_FENCE_COMPLETED);
2416 	/* should be timed out */
2417 	retval = amdkfd_fence_wait_timeout(dqm, KFD_FENCE_COMPLETED,
2418 					   queue_preemption_timeout_ms);
2419 	if (retval) {
2420 		dev_err(dev, "The cp might be in an unrecoverable state due to an unsuccessful queues preemption\n");
2421 		kfd_hws_hang(dqm);
2422 		goto out;
2423 	}
2424 
2425 	/* In the current MEC firmware implementation, if compute queue
2426 	 * doesn't response to the preemption request in time, HIQ will
2427 	 * abandon the unmap request without returning any timeout error
2428 	 * to driver. Instead, MEC firmware will log the doorbell of the
2429 	 * unresponding compute queue to HIQ.MQD.queue_doorbell_id fields.
2430 	 * To make sure the queue unmap was successful, driver need to
2431 	 * check those fields
2432 	 */
2433 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ];
2434 	if (mqd_mgr->check_preemption_failed(mqd_mgr, dqm->packet_mgr.priv_queue->queue->mqd) &&
2435 	    reset_queues_on_hws_hang(dqm, false))
2436 		goto reset_fail;
2437 
2438 	/* Check for SDMA hang and attempt SDMA reset */
2439 	if (sdma_has_hang(dqm) && reset_queues_on_hws_hang(dqm, true))
2440 		goto reset_fail;
2441 
2442 	/* We need to reset the grace period value for this device */
2443 	if (grace_period != USE_DEFAULT_GRACE_PERIOD) {
2444 		if (pm_config_dequeue_wait_counts(&dqm->packet_mgr,
2445 				KFD_DEQUEUE_WAIT_RESET, 0 /* unused */))
2446 			dev_err(dev, "Failed to reset grace period\n");
2447 	}
2448 
2449 	pm_release_ib(&dqm->packet_mgr);
2450 	dqm->active_runlist = false;
2451 out:
2452 	up_read(&dqm->dev->adev->reset_domain->sem);
2453 	return retval;
2454 
2455 reset_fail:
2456 	dqm->is_hws_hang = true;
2457 	kfd_hws_hang(dqm);
2458 	up_read(&dqm->dev->adev->reset_domain->sem);
2459 	return -ETIME;
2460 }
2461 
2462 /* only for compute queue */
2463 static int reset_queues_cpsch(struct device_queue_manager *dqm, uint16_t pasid)
2464 {
2465 	int retval;
2466 
2467 	dqm_lock(dqm);
2468 
2469 	retval = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_BY_PASID,
2470 			pasid, USE_DEFAULT_GRACE_PERIOD, true);
2471 
2472 	dqm_unlock(dqm);
2473 	return retval;
2474 }
2475 
2476 /* dqm->lock mutex has to be locked before calling this function */
2477 static int execute_queues_cpsch(struct device_queue_manager *dqm,
2478 				enum kfd_unmap_queues_filter filter,
2479 				uint32_t filter_param,
2480 				uint32_t grace_period)
2481 {
2482 	int retval;
2483 
2484 	if (!down_read_trylock(&dqm->dev->adev->reset_domain->sem))
2485 		return -EIO;
2486 	retval = unmap_queues_cpsch(dqm, filter, filter_param, grace_period, false);
2487 	if (!retval)
2488 		retval = map_queues_cpsch(dqm);
2489 	up_read(&dqm->dev->adev->reset_domain->sem);
2490 	return retval;
2491 }
2492 
2493 static int wait_on_destroy_queue(struct device_queue_manager *dqm,
2494 				 struct queue *q)
2495 {
2496 	struct kfd_process_device *pdd = kfd_get_process_device_data(q->device,
2497 								q->process);
2498 	int ret = 0;
2499 
2500 	if (WARN_ON(!pdd))
2501 		return ret;
2502 
2503 	if (pdd->qpd.is_debug)
2504 		return ret;
2505 
2506 	q->properties.is_being_destroyed = true;
2507 
2508 	if (pdd->process->debug_trap_enabled && q->properties.is_suspended) {
2509 		dqm_unlock(dqm);
2510 		mutex_unlock(&q->process->mutex);
2511 		ret = wait_event_interruptible(dqm->destroy_wait,
2512 						!q->properties.is_suspended);
2513 
2514 		mutex_lock(&q->process->mutex);
2515 		dqm_lock(dqm);
2516 	}
2517 
2518 	return ret;
2519 }
2520 
2521 static int destroy_queue_cpsch(struct device_queue_manager *dqm,
2522 				struct qcm_process_device *qpd,
2523 				struct queue *q)
2524 {
2525 	int retval;
2526 	struct mqd_manager *mqd_mgr;
2527 	uint64_t sdma_val = 0;
2528 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
2529 	struct device *dev = dqm->dev->adev->dev;
2530 
2531 	/* Get the SDMA queue stats */
2532 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
2533 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
2534 		retval = read_sdma_queue_counter((uint64_t __user *)q->properties.read_ptr,
2535 							&sdma_val);
2536 		if (retval)
2537 			dev_err(dev, "Failed to read SDMA queue counter for queue: %d\n",
2538 				q->properties.queue_id);
2539 	}
2540 
2541 	/* remove queue from list to prevent rescheduling after preemption */
2542 	dqm_lock(dqm);
2543 
2544 	retval = wait_on_destroy_queue(dqm, q);
2545 
2546 	if (retval) {
2547 		dqm_unlock(dqm);
2548 		return retval;
2549 	}
2550 
2551 	if (qpd->is_debug) {
2552 		/*
2553 		 * error, currently we do not allow to destroy a queue
2554 		 * of a currently debugged process
2555 		 */
2556 		retval = -EBUSY;
2557 		goto failed_try_destroy_debugged_queue;
2558 
2559 	}
2560 
2561 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2562 			q->properties.type)];
2563 
2564 	deallocate_doorbell(qpd, q);
2565 
2566 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
2567 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
2568 		deallocate_sdma_queue(dqm, q);
2569 		pdd->sdma_past_activity_counter += sdma_val;
2570 	}
2571 
2572 	if (q->properties.is_active) {
2573 		decrement_queue_count(dqm, qpd, q);
2574 		q->properties.is_active = false;
2575 		if (!dqm->dev->kfd->shared_resources.enable_mes) {
2576 			retval = execute_queues_cpsch(dqm,
2577 						      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
2578 						      USE_DEFAULT_GRACE_PERIOD);
2579 			if (retval == -ETIME)
2580 				qpd->reset_wavefronts = true;
2581 		} else {
2582 			retval = remove_queue_mes(dqm, q, qpd);
2583 		}
2584 	}
2585 	list_del(&q->list);
2586 	qpd->queue_count--;
2587 
2588 	/*
2589 	 * Unconditionally decrement this counter, regardless of the queue's
2590 	 * type
2591 	 */
2592 	dqm->total_queue_count--;
2593 	pr_debug("Total of %d queues are accountable so far\n",
2594 			dqm->total_queue_count);
2595 
2596 	dqm_unlock(dqm);
2597 
2598 	/*
2599 	 * Do free_mqd and raise delete event after dqm_unlock(dqm) to avoid
2600 	 * circular locking
2601 	 */
2602 	kfd_dbg_ev_raise(KFD_EC_MASK(EC_DEVICE_QUEUE_DELETE),
2603 				qpd->pqm->process, q->device,
2604 				-1, false, NULL, 0);
2605 
2606 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2607 
2608 	return retval;
2609 
2610 failed_try_destroy_debugged_queue:
2611 
2612 	dqm_unlock(dqm);
2613 	return retval;
2614 }
2615 
2616 static bool set_cache_memory_policy(struct device_queue_manager *dqm,
2617 				   struct qcm_process_device *qpd,
2618 				   enum cache_policy default_policy,
2619 				   enum cache_policy alternate_policy,
2620 				   void __user *alternate_aperture_base,
2621 				   uint64_t alternate_aperture_size,
2622 				   u32 misc_process_properties)
2623 {
2624 	bool retval = true;
2625 
2626 	if (!dqm->asic_ops.set_cache_memory_policy)
2627 		return retval;
2628 
2629 	dqm_lock(dqm);
2630 
2631 	retval = dqm->asic_ops.set_cache_memory_policy(
2632 			dqm,
2633 			qpd,
2634 			default_policy,
2635 			alternate_policy,
2636 			alternate_aperture_base,
2637 			alternate_aperture_size,
2638 			misc_process_properties);
2639 
2640 	if (retval)
2641 		goto out;
2642 
2643 	if ((dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) && (qpd->vmid != 0))
2644 		program_sh_mem_settings(dqm, qpd);
2645 
2646 	pr_debug("sh_mem_config: 0x%x, ape1_base: 0x%x, ape1_limit: 0x%x\n",
2647 		qpd->sh_mem_config, qpd->sh_mem_ape1_base,
2648 		qpd->sh_mem_ape1_limit);
2649 
2650 out:
2651 	dqm_unlock(dqm);
2652 	return retval;
2653 }
2654 
2655 static int process_termination_nocpsch(struct device_queue_manager *dqm,
2656 		struct qcm_process_device *qpd)
2657 {
2658 	struct queue *q;
2659 	struct device_process_node *cur, *next_dpn;
2660 	int retval = 0;
2661 	bool found = false;
2662 
2663 	dqm_lock(dqm);
2664 
2665 	/* Clear all user mode queues */
2666 	while (!list_empty(&qpd->queues_list)) {
2667 		struct mqd_manager *mqd_mgr;
2668 		int ret;
2669 
2670 		q = list_first_entry(&qpd->queues_list, struct queue, list);
2671 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2672 				q->properties.type)];
2673 		ret = destroy_queue_nocpsch_locked(dqm, qpd, q);
2674 		if (ret)
2675 			retval = ret;
2676 		dqm_unlock(dqm);
2677 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2678 		dqm_lock(dqm);
2679 	}
2680 
2681 	/* Unregister process */
2682 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
2683 		if (qpd == cur->qpd) {
2684 			list_del(&cur->list);
2685 			kfree(cur);
2686 			dqm->processes_count--;
2687 			found = true;
2688 			break;
2689 		}
2690 	}
2691 
2692 	dqm_unlock(dqm);
2693 
2694 	/* Outside the DQM lock because under the DQM lock we can't do
2695 	 * reclaim or take other locks that others hold while reclaiming.
2696 	 */
2697 	if (found)
2698 		kfd_dec_compute_active(dqm->dev);
2699 
2700 	return retval;
2701 }
2702 
2703 static int get_wave_state(struct device_queue_manager *dqm,
2704 			  struct queue *q,
2705 			  void __user *ctl_stack,
2706 			  u32 *ctl_stack_used_size,
2707 			  u32 *save_area_used_size)
2708 {
2709 	struct mqd_manager *mqd_mgr;
2710 
2711 	dqm_lock(dqm);
2712 
2713 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_CP];
2714 
2715 	if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE ||
2716 	    q->properties.is_active || !q->device->kfd->cwsr_enabled ||
2717 	    !mqd_mgr->get_wave_state) {
2718 		dqm_unlock(dqm);
2719 		return -EINVAL;
2720 	}
2721 
2722 	dqm_unlock(dqm);
2723 
2724 	/*
2725 	 * get_wave_state is outside the dqm lock to prevent circular locking
2726 	 * and the queue should be protected against destruction by the process
2727 	 * lock.
2728 	 */
2729 	return mqd_mgr->get_wave_state(mqd_mgr, q->mqd, &q->properties,
2730 			ctl_stack, ctl_stack_used_size, save_area_used_size);
2731 }
2732 
2733 static void get_queue_checkpoint_info(struct device_queue_manager *dqm,
2734 			const struct queue *q,
2735 			u32 *mqd_size,
2736 			u32 *ctl_stack_size)
2737 {
2738 	struct mqd_manager *mqd_mgr;
2739 	enum KFD_MQD_TYPE mqd_type =
2740 			get_mqd_type_from_queue_type(q->properties.type);
2741 
2742 	dqm_lock(dqm);
2743 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
2744 	*mqd_size = mqd_mgr->mqd_size * NUM_XCC(mqd_mgr->dev->xcc_mask);
2745 	*ctl_stack_size = 0;
2746 
2747 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE && mqd_mgr->get_checkpoint_info)
2748 		mqd_mgr->get_checkpoint_info(mqd_mgr, q->mqd, ctl_stack_size);
2749 
2750 	dqm_unlock(dqm);
2751 }
2752 
2753 static int checkpoint_mqd(struct device_queue_manager *dqm,
2754 			  const struct queue *q,
2755 			  void *mqd,
2756 			  void *ctl_stack)
2757 {
2758 	struct mqd_manager *mqd_mgr;
2759 	int r = 0;
2760 	enum KFD_MQD_TYPE mqd_type =
2761 			get_mqd_type_from_queue_type(q->properties.type);
2762 
2763 	dqm_lock(dqm);
2764 
2765 	if (q->properties.is_active || !q->device->kfd->cwsr_enabled) {
2766 		r = -EINVAL;
2767 		goto dqm_unlock;
2768 	}
2769 
2770 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
2771 	if (!mqd_mgr->checkpoint_mqd) {
2772 		r = -EOPNOTSUPP;
2773 		goto dqm_unlock;
2774 	}
2775 
2776 	mqd_mgr->checkpoint_mqd(mqd_mgr, q->mqd, mqd, ctl_stack);
2777 
2778 dqm_unlock:
2779 	dqm_unlock(dqm);
2780 	return r;
2781 }
2782 
2783 static int process_termination_cpsch(struct device_queue_manager *dqm,
2784 		struct qcm_process_device *qpd)
2785 {
2786 	int retval;
2787 	struct queue *q;
2788 	struct device *dev = dqm->dev->adev->dev;
2789 	struct kernel_queue *kq, *kq_next;
2790 	struct mqd_manager *mqd_mgr;
2791 	struct device_process_node *cur, *next_dpn;
2792 	enum kfd_unmap_queues_filter filter =
2793 		KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES;
2794 	bool found = false;
2795 
2796 	retval = 0;
2797 
2798 	dqm_lock(dqm);
2799 
2800 	/* Clean all kernel queues */
2801 	list_for_each_entry_safe(kq, kq_next, &qpd->priv_queue_list, list) {
2802 		list_del(&kq->list);
2803 		decrement_queue_count(dqm, qpd, kq->queue);
2804 		qpd->is_debug = false;
2805 		dqm->total_queue_count--;
2806 		filter = KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES;
2807 	}
2808 
2809 	/* Clear all user mode queues */
2810 	list_for_each_entry(q, &qpd->queues_list, list) {
2811 		if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
2812 			deallocate_sdma_queue(dqm, q);
2813 		else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
2814 			deallocate_sdma_queue(dqm, q);
2815 
2816 		if (q->properties.is_active) {
2817 			decrement_queue_count(dqm, qpd, q);
2818 
2819 			if (dqm->dev->kfd->shared_resources.enable_mes) {
2820 				retval = remove_queue_mes(dqm, q, qpd);
2821 				if (retval)
2822 					dev_err(dev, "Failed to remove queue %d\n",
2823 						q->properties.queue_id);
2824 			}
2825 		}
2826 
2827 		dqm->total_queue_count--;
2828 	}
2829 
2830 	/* Unregister process */
2831 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
2832 		if (qpd == cur->qpd) {
2833 			list_del(&cur->list);
2834 			kfree(cur);
2835 			dqm->processes_count--;
2836 			found = true;
2837 			break;
2838 		}
2839 	}
2840 
2841 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2842 		retval = execute_queues_cpsch(dqm, filter, 0, USE_DEFAULT_GRACE_PERIOD);
2843 
2844 	if ((retval || qpd->reset_wavefronts) &&
2845 	    down_read_trylock(&dqm->dev->adev->reset_domain->sem)) {
2846 		pr_warn("Resetting wave fronts (cpsch) on dev %p\n", dqm->dev);
2847 		dbgdev_wave_reset_wavefronts(dqm->dev, qpd->pqm->process);
2848 		qpd->reset_wavefronts = false;
2849 		up_read(&dqm->dev->adev->reset_domain->sem);
2850 	}
2851 
2852 	/* Lastly, free mqd resources.
2853 	 * Do free_mqd() after dqm_unlock to avoid circular locking.
2854 	 */
2855 	while (!list_empty(&qpd->queues_list)) {
2856 		q = list_first_entry(&qpd->queues_list, struct queue, list);
2857 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2858 				q->properties.type)];
2859 		list_del(&q->list);
2860 		qpd->queue_count--;
2861 		dqm_unlock(dqm);
2862 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2863 		dqm_lock(dqm);
2864 	}
2865 	dqm_unlock(dqm);
2866 
2867 	/* Outside the DQM lock because under the DQM lock we can't do
2868 	 * reclaim or take other locks that others hold while reclaiming.
2869 	 */
2870 	if (found)
2871 		kfd_dec_compute_active(dqm->dev);
2872 
2873 	return retval;
2874 }
2875 
2876 static int init_mqd_managers(struct device_queue_manager *dqm)
2877 {
2878 	int i, j;
2879 	struct device *dev = dqm->dev->adev->dev;
2880 	struct mqd_manager *mqd_mgr;
2881 
2882 	for (i = 0; i < KFD_MQD_TYPE_MAX; i++) {
2883 		mqd_mgr = dqm->asic_ops.mqd_manager_init(i, dqm->dev);
2884 		if (!mqd_mgr) {
2885 			dev_err(dev, "mqd manager [%d] initialization failed\n", i);
2886 			goto out_free;
2887 		}
2888 		dqm->mqd_mgrs[i] = mqd_mgr;
2889 	}
2890 
2891 	return 0;
2892 
2893 out_free:
2894 	for (j = 0; j < i; j++) {
2895 		kfree(dqm->mqd_mgrs[j]);
2896 		dqm->mqd_mgrs[j] = NULL;
2897 	}
2898 
2899 	return -ENOMEM;
2900 }
2901 
2902 /* Allocate one hiq mqd (HWS) and all SDMA mqd in a continuous trunk*/
2903 static int allocate_hiq_sdma_mqd(struct device_queue_manager *dqm)
2904 {
2905 	int retval;
2906 	struct kfd_node *dev = dqm->dev;
2907 	struct kfd_mem_obj *mem_obj = &dqm->hiq_sdma_mqd;
2908 	uint32_t size = dqm->mqd_mgrs[KFD_MQD_TYPE_SDMA]->mqd_size *
2909 		get_num_all_sdma_engines(dqm) *
2910 		dev->kfd->device_info.num_sdma_queues_per_engine +
2911 		(dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ]->mqd_size *
2912 		NUM_XCC(dqm->dev->xcc_mask));
2913 
2914 	retval = amdgpu_amdkfd_alloc_gtt_mem(dev->adev, size,
2915 		&(mem_obj->gtt_mem), &(mem_obj->gpu_addr),
2916 		(void *)&(mem_obj->cpu_ptr), false);
2917 
2918 	return retval;
2919 }
2920 
2921 struct device_queue_manager *device_queue_manager_init(struct kfd_node *dev)
2922 {
2923 	struct device_queue_manager *dqm;
2924 
2925 	pr_debug("Loading device queue manager\n");
2926 
2927 	dqm = kzalloc(sizeof(*dqm), GFP_KERNEL);
2928 	if (!dqm)
2929 		return NULL;
2930 
2931 	switch (dev->adev->asic_type) {
2932 	/* HWS is not available on Hawaii. */
2933 	case CHIP_HAWAII:
2934 	/* HWS depends on CWSR for timely dequeue. CWSR is not
2935 	 * available on Tonga.
2936 	 *
2937 	 * FIXME: This argument also applies to Kaveri.
2938 	 */
2939 	case CHIP_TONGA:
2940 		dqm->sched_policy = KFD_SCHED_POLICY_NO_HWS;
2941 		break;
2942 	default:
2943 		dqm->sched_policy = sched_policy;
2944 		break;
2945 	}
2946 
2947 	dqm->dev = dev;
2948 	switch (dqm->sched_policy) {
2949 	case KFD_SCHED_POLICY_HWS:
2950 	case KFD_SCHED_POLICY_HWS_NO_OVERSUBSCRIPTION:
2951 		/* initialize dqm for cp scheduling */
2952 		dqm->ops.create_queue = create_queue_cpsch;
2953 		dqm->ops.initialize = initialize_cpsch;
2954 		dqm->ops.start = start_cpsch;
2955 		dqm->ops.stop = stop_cpsch;
2956 		dqm->ops.halt = halt_cpsch;
2957 		dqm->ops.unhalt = unhalt_cpsch;
2958 		dqm->ops.destroy_queue = destroy_queue_cpsch;
2959 		dqm->ops.update_queue = update_queue;
2960 		dqm->ops.register_process = register_process;
2961 		dqm->ops.unregister_process = unregister_process;
2962 		dqm->ops.uninitialize = uninitialize;
2963 		dqm->ops.create_kernel_queue = create_kernel_queue_cpsch;
2964 		dqm->ops.destroy_kernel_queue = destroy_kernel_queue_cpsch;
2965 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
2966 		dqm->ops.process_termination = process_termination_cpsch;
2967 		dqm->ops.evict_process_queues = evict_process_queues_cpsch;
2968 		dqm->ops.restore_process_queues = restore_process_queues_cpsch;
2969 		dqm->ops.get_wave_state = get_wave_state;
2970 		dqm->ops.reset_queues = reset_queues_cpsch;
2971 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
2972 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
2973 		break;
2974 	case KFD_SCHED_POLICY_NO_HWS:
2975 		/* initialize dqm for no cp scheduling */
2976 		dqm->ops.start = start_nocpsch;
2977 		dqm->ops.stop = stop_nocpsch;
2978 		dqm->ops.create_queue = create_queue_nocpsch;
2979 		dqm->ops.destroy_queue = destroy_queue_nocpsch;
2980 		dqm->ops.update_queue = update_queue;
2981 		dqm->ops.register_process = register_process;
2982 		dqm->ops.unregister_process = unregister_process;
2983 		dqm->ops.initialize = initialize_nocpsch;
2984 		dqm->ops.uninitialize = uninitialize;
2985 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
2986 		dqm->ops.process_termination = process_termination_nocpsch;
2987 		dqm->ops.evict_process_queues = evict_process_queues_nocpsch;
2988 		dqm->ops.restore_process_queues =
2989 			restore_process_queues_nocpsch;
2990 		dqm->ops.get_wave_state = get_wave_state;
2991 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
2992 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
2993 		break;
2994 	default:
2995 		dev_err(dev->adev->dev, "Invalid scheduling policy %d\n", dqm->sched_policy);
2996 		goto out_free;
2997 	}
2998 
2999 	switch (dev->adev->asic_type) {
3000 	case CHIP_KAVERI:
3001 	case CHIP_HAWAII:
3002 		device_queue_manager_init_cik(&dqm->asic_ops);
3003 		break;
3004 
3005 	case CHIP_CARRIZO:
3006 	case CHIP_TONGA:
3007 	case CHIP_FIJI:
3008 	case CHIP_POLARIS10:
3009 	case CHIP_POLARIS11:
3010 	case CHIP_POLARIS12:
3011 	case CHIP_VEGAM:
3012 		device_queue_manager_init_vi(&dqm->asic_ops);
3013 		break;
3014 
3015 	default:
3016 		if (KFD_GC_VERSION(dev) >= IP_VERSION(12, 0, 0))
3017 			device_queue_manager_init_v12(&dqm->asic_ops);
3018 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(11, 0, 0))
3019 			device_queue_manager_init_v11(&dqm->asic_ops);
3020 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(10, 1, 1))
3021 			device_queue_manager_init_v10(&dqm->asic_ops);
3022 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(9, 0, 1))
3023 			device_queue_manager_init_v9(&dqm->asic_ops);
3024 		else {
3025 			WARN(1, "Unexpected ASIC family %u",
3026 			     dev->adev->asic_type);
3027 			goto out_free;
3028 		}
3029 	}
3030 
3031 	if (init_mqd_managers(dqm))
3032 		goto out_free;
3033 
3034 	if (!dev->kfd->shared_resources.enable_mes && allocate_hiq_sdma_mqd(dqm)) {
3035 		dev_err(dev->adev->dev, "Failed to allocate hiq sdma mqd trunk buffer\n");
3036 		goto out_free;
3037 	}
3038 
3039 	if (!dqm->ops.initialize(dqm)) {
3040 		init_waitqueue_head(&dqm->destroy_wait);
3041 		return dqm;
3042 	}
3043 
3044 out_free:
3045 	kfree(dqm);
3046 	return NULL;
3047 }
3048 
3049 static void deallocate_hiq_sdma_mqd(struct kfd_node *dev,
3050 				    struct kfd_mem_obj *mqd)
3051 {
3052 	WARN(!mqd, "No hiq sdma mqd trunk to free");
3053 
3054 	amdgpu_amdkfd_free_gtt_mem(dev->adev, &mqd->gtt_mem);
3055 }
3056 
3057 void device_queue_manager_uninit(struct device_queue_manager *dqm)
3058 {
3059 	dqm->ops.stop(dqm);
3060 	dqm->ops.uninitialize(dqm);
3061 	if (!dqm->dev->kfd->shared_resources.enable_mes)
3062 		deallocate_hiq_sdma_mqd(dqm->dev, &dqm->hiq_sdma_mqd);
3063 	kfree(dqm);
3064 }
3065 
3066 int kfd_dqm_suspend_bad_queue_mes(struct kfd_node *knode, u32 pasid, u32 doorbell_id)
3067 {
3068 	struct kfd_process_device *pdd = NULL;
3069 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid, &pdd);
3070 	struct device_queue_manager *dqm = knode->dqm;
3071 	struct device *dev = dqm->dev->adev->dev;
3072 	struct qcm_process_device *qpd;
3073 	struct queue *q = NULL;
3074 	int ret = 0;
3075 
3076 	if (!pdd)
3077 		return -EINVAL;
3078 
3079 	dqm_lock(dqm);
3080 
3081 	if (pdd) {
3082 		qpd = &pdd->qpd;
3083 
3084 		list_for_each_entry(q, &qpd->queues_list, list) {
3085 			if (q->doorbell_id == doorbell_id && q->properties.is_active) {
3086 				ret = suspend_all_queues_mes(dqm);
3087 				if (ret) {
3088 					dev_err(dev, "Suspending all queues failed");
3089 					goto out;
3090 				}
3091 
3092 				q->properties.is_evicted = true;
3093 				q->properties.is_active = false;
3094 				decrement_queue_count(dqm, qpd, q);
3095 
3096 				ret = remove_queue_mes(dqm, q, qpd);
3097 				if (ret) {
3098 					dev_err(dev, "Removing bad queue failed");
3099 					goto out;
3100 				}
3101 
3102 				ret = resume_all_queues_mes(dqm);
3103 				if (ret)
3104 					dev_err(dev, "Resuming all queues failed");
3105 
3106 				break;
3107 			}
3108 		}
3109 	}
3110 
3111 out:
3112 	dqm_unlock(dqm);
3113 	kfd_unref_process(p);
3114 	return ret;
3115 }
3116 
3117 int kfd_evict_process_device(struct kfd_process_device *pdd)
3118 {
3119 	struct device_queue_manager *dqm;
3120 	struct kfd_process *p;
3121 
3122 	p = pdd->process;
3123 	dqm = pdd->dev->dqm;
3124 
3125 	WARN(debug_evictions, "Evicting pid %d", p->lead_thread->pid);
3126 
3127 	return dqm->ops.evict_process_queues(dqm, &pdd->qpd);
3128 }
3129 
3130 int reserve_debug_trap_vmid(struct device_queue_manager *dqm,
3131 				struct qcm_process_device *qpd)
3132 {
3133 	int r;
3134 	struct device *dev = dqm->dev->adev->dev;
3135 	int updated_vmid_mask;
3136 
3137 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3138 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3139 		return -EINVAL;
3140 	}
3141 
3142 	dqm_lock(dqm);
3143 
3144 	if (dqm->trap_debug_vmid != 0) {
3145 		dev_err(dev, "Trap debug id already reserved\n");
3146 		r = -EBUSY;
3147 		goto out_unlock;
3148 	}
3149 
3150 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
3151 			USE_DEFAULT_GRACE_PERIOD, false);
3152 	if (r)
3153 		goto out_unlock;
3154 
3155 	updated_vmid_mask = dqm->dev->kfd->shared_resources.compute_vmid_bitmap;
3156 	updated_vmid_mask &= ~(1 << dqm->dev->vm_info.last_vmid_kfd);
3157 
3158 	dqm->dev->kfd->shared_resources.compute_vmid_bitmap = updated_vmid_mask;
3159 	dqm->trap_debug_vmid = dqm->dev->vm_info.last_vmid_kfd;
3160 	r = set_sched_resources(dqm);
3161 	if (r)
3162 		goto out_unlock;
3163 
3164 	r = map_queues_cpsch(dqm);
3165 	if (r)
3166 		goto out_unlock;
3167 
3168 	pr_debug("Reserved VMID for trap debug: %i\n", dqm->trap_debug_vmid);
3169 
3170 out_unlock:
3171 	dqm_unlock(dqm);
3172 	return r;
3173 }
3174 
3175 /*
3176  * Releases vmid for the trap debugger
3177  */
3178 int release_debug_trap_vmid(struct device_queue_manager *dqm,
3179 			struct qcm_process_device *qpd)
3180 {
3181 	struct device *dev = dqm->dev->adev->dev;
3182 	int r;
3183 	int updated_vmid_mask;
3184 	uint32_t trap_debug_vmid;
3185 
3186 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3187 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3188 		return -EINVAL;
3189 	}
3190 
3191 	dqm_lock(dqm);
3192 	trap_debug_vmid = dqm->trap_debug_vmid;
3193 	if (dqm->trap_debug_vmid == 0) {
3194 		dev_err(dev, "Trap debug id is not reserved\n");
3195 		r = -EINVAL;
3196 		goto out_unlock;
3197 	}
3198 
3199 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
3200 			USE_DEFAULT_GRACE_PERIOD, false);
3201 	if (r)
3202 		goto out_unlock;
3203 
3204 	updated_vmid_mask = dqm->dev->kfd->shared_resources.compute_vmid_bitmap;
3205 	updated_vmid_mask |= (1 << dqm->dev->vm_info.last_vmid_kfd);
3206 
3207 	dqm->dev->kfd->shared_resources.compute_vmid_bitmap = updated_vmid_mask;
3208 	dqm->trap_debug_vmid = 0;
3209 	r = set_sched_resources(dqm);
3210 	if (r)
3211 		goto out_unlock;
3212 
3213 	r = map_queues_cpsch(dqm);
3214 	if (r)
3215 		goto out_unlock;
3216 
3217 	pr_debug("Released VMID for trap debug: %i\n", trap_debug_vmid);
3218 
3219 out_unlock:
3220 	dqm_unlock(dqm);
3221 	return r;
3222 }
3223 
3224 #define QUEUE_NOT_FOUND		-1
3225 /* invalidate queue operation in array */
3226 static void q_array_invalidate(uint32_t num_queues, uint32_t *queue_ids)
3227 {
3228 	int i;
3229 
3230 	for (i = 0; i < num_queues; i++)
3231 		queue_ids[i] |= KFD_DBG_QUEUE_INVALID_MASK;
3232 }
3233 
3234 /* find queue index in array */
3235 static int q_array_get_index(unsigned int queue_id,
3236 		uint32_t num_queues,
3237 		uint32_t *queue_ids)
3238 {
3239 	int i;
3240 
3241 	for (i = 0; i < num_queues; i++)
3242 		if (queue_id == (queue_ids[i] & ~KFD_DBG_QUEUE_INVALID_MASK))
3243 			return i;
3244 
3245 	return QUEUE_NOT_FOUND;
3246 }
3247 
3248 struct copy_context_work_handler_workarea {
3249 	struct work_struct copy_context_work;
3250 	struct kfd_process *p;
3251 };
3252 
3253 static void copy_context_work_handler(struct work_struct *work)
3254 {
3255 	struct copy_context_work_handler_workarea *workarea;
3256 	struct mqd_manager *mqd_mgr;
3257 	struct queue *q;
3258 	struct mm_struct *mm;
3259 	struct kfd_process *p;
3260 	uint32_t tmp_ctl_stack_used_size, tmp_save_area_used_size;
3261 	int i;
3262 
3263 	workarea = container_of(work,
3264 			struct copy_context_work_handler_workarea,
3265 			copy_context_work);
3266 
3267 	p = workarea->p;
3268 	mm = get_task_mm(p->lead_thread);
3269 
3270 	if (!mm)
3271 		return;
3272 
3273 	kthread_use_mm(mm);
3274 	for (i = 0; i < p->n_pdds; i++) {
3275 		struct kfd_process_device *pdd = p->pdds[i];
3276 		struct device_queue_manager *dqm = pdd->dev->dqm;
3277 		struct qcm_process_device *qpd = &pdd->qpd;
3278 
3279 		list_for_each_entry(q, &qpd->queues_list, list) {
3280 			if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE)
3281 				continue;
3282 
3283 			mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_CP];
3284 
3285 			/* We ignore the return value from get_wave_state
3286 			 * because
3287 			 * i) right now, it always returns 0, and
3288 			 * ii) if we hit an error, we would continue to the
3289 			 *      next queue anyway.
3290 			 */
3291 			mqd_mgr->get_wave_state(mqd_mgr,
3292 					q->mqd,
3293 					&q->properties,
3294 					(void __user *)	q->properties.ctx_save_restore_area_address,
3295 					&tmp_ctl_stack_used_size,
3296 					&tmp_save_area_used_size);
3297 		}
3298 	}
3299 	kthread_unuse_mm(mm);
3300 	mmput(mm);
3301 }
3302 
3303 static uint32_t *get_queue_ids(uint32_t num_queues, uint32_t *usr_queue_id_array)
3304 {
3305 	size_t array_size = num_queues * sizeof(uint32_t);
3306 
3307 	if (!usr_queue_id_array)
3308 		return NULL;
3309 
3310 	return memdup_user(usr_queue_id_array, array_size);
3311 }
3312 
3313 int resume_queues(struct kfd_process *p,
3314 		uint32_t num_queues,
3315 		uint32_t *usr_queue_id_array)
3316 {
3317 	uint32_t *queue_ids = NULL;
3318 	int total_resumed = 0;
3319 	int i;
3320 
3321 	if (usr_queue_id_array) {
3322 		queue_ids = get_queue_ids(num_queues, usr_queue_id_array);
3323 
3324 		if (IS_ERR(queue_ids))
3325 			return PTR_ERR(queue_ids);
3326 
3327 		/* mask all queues as invalid.  unmask per successful request */
3328 		q_array_invalidate(num_queues, queue_ids);
3329 	}
3330 
3331 	for (i = 0; i < p->n_pdds; i++) {
3332 		struct kfd_process_device *pdd = p->pdds[i];
3333 		struct device_queue_manager *dqm = pdd->dev->dqm;
3334 		struct device *dev = dqm->dev->adev->dev;
3335 		struct qcm_process_device *qpd = &pdd->qpd;
3336 		struct queue *q;
3337 		int r, per_device_resumed = 0;
3338 
3339 		dqm_lock(dqm);
3340 
3341 		/* unmask queues that resume or already resumed as valid */
3342 		list_for_each_entry(q, &qpd->queues_list, list) {
3343 			int q_idx = QUEUE_NOT_FOUND;
3344 
3345 			if (queue_ids)
3346 				q_idx = q_array_get_index(
3347 						q->properties.queue_id,
3348 						num_queues,
3349 						queue_ids);
3350 
3351 			if (!queue_ids || q_idx != QUEUE_NOT_FOUND) {
3352 				int err = resume_single_queue(dqm, &pdd->qpd, q);
3353 
3354 				if (queue_ids) {
3355 					if (!err) {
3356 						queue_ids[q_idx] &=
3357 							~KFD_DBG_QUEUE_INVALID_MASK;
3358 					} else {
3359 						queue_ids[q_idx] |=
3360 							KFD_DBG_QUEUE_ERROR_MASK;
3361 						break;
3362 					}
3363 				}
3364 
3365 				if (dqm->dev->kfd->shared_resources.enable_mes) {
3366 					wake_up_all(&dqm->destroy_wait);
3367 					if (!err)
3368 						total_resumed++;
3369 				} else {
3370 					per_device_resumed++;
3371 				}
3372 			}
3373 		}
3374 
3375 		if (!per_device_resumed) {
3376 			dqm_unlock(dqm);
3377 			continue;
3378 		}
3379 
3380 		r = execute_queues_cpsch(dqm,
3381 					KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES,
3382 					0,
3383 					USE_DEFAULT_GRACE_PERIOD);
3384 		if (r) {
3385 			dev_err(dev, "Failed to resume process queues\n");
3386 			if (queue_ids) {
3387 				list_for_each_entry(q, &qpd->queues_list, list) {
3388 					int q_idx = q_array_get_index(
3389 							q->properties.queue_id,
3390 							num_queues,
3391 							queue_ids);
3392 
3393 					/* mask queue as error on resume fail */
3394 					if (q_idx != QUEUE_NOT_FOUND)
3395 						queue_ids[q_idx] |=
3396 							KFD_DBG_QUEUE_ERROR_MASK;
3397 				}
3398 			}
3399 		} else {
3400 			wake_up_all(&dqm->destroy_wait);
3401 			total_resumed += per_device_resumed;
3402 		}
3403 
3404 		dqm_unlock(dqm);
3405 	}
3406 
3407 	if (queue_ids) {
3408 		if (copy_to_user((void __user *)usr_queue_id_array, queue_ids,
3409 				num_queues * sizeof(uint32_t)))
3410 			pr_err("copy_to_user failed on queue resume\n");
3411 
3412 		kfree(queue_ids);
3413 	}
3414 
3415 	return total_resumed;
3416 }
3417 
3418 int suspend_queues(struct kfd_process *p,
3419 			uint32_t num_queues,
3420 			uint32_t grace_period,
3421 			uint64_t exception_clear_mask,
3422 			uint32_t *usr_queue_id_array)
3423 {
3424 	uint32_t *queue_ids = get_queue_ids(num_queues, usr_queue_id_array);
3425 	int total_suspended = 0;
3426 	int i;
3427 
3428 	if (IS_ERR(queue_ids))
3429 		return PTR_ERR(queue_ids);
3430 
3431 	/* mask all queues as invalid.  umask on successful request */
3432 	q_array_invalidate(num_queues, queue_ids);
3433 
3434 	for (i = 0; i < p->n_pdds; i++) {
3435 		struct kfd_process_device *pdd = p->pdds[i];
3436 		struct device_queue_manager *dqm = pdd->dev->dqm;
3437 		struct device *dev = dqm->dev->adev->dev;
3438 		struct qcm_process_device *qpd = &pdd->qpd;
3439 		struct queue *q;
3440 		int r, per_device_suspended = 0;
3441 
3442 		mutex_lock(&p->event_mutex);
3443 		dqm_lock(dqm);
3444 
3445 		/* unmask queues that suspend or already suspended */
3446 		list_for_each_entry(q, &qpd->queues_list, list) {
3447 			int q_idx = q_array_get_index(q->properties.queue_id,
3448 							num_queues,
3449 							queue_ids);
3450 
3451 			if (q_idx != QUEUE_NOT_FOUND) {
3452 				int err = suspend_single_queue(dqm, pdd, q);
3453 				bool is_mes = dqm->dev->kfd->shared_resources.enable_mes;
3454 
3455 				if (!err) {
3456 					queue_ids[q_idx] &= ~KFD_DBG_QUEUE_INVALID_MASK;
3457 					if (exception_clear_mask && is_mes)
3458 						q->properties.exception_status &=
3459 							~exception_clear_mask;
3460 
3461 					if (is_mes)
3462 						total_suspended++;
3463 					else
3464 						per_device_suspended++;
3465 				} else if (err != -EBUSY) {
3466 					r = err;
3467 					queue_ids[q_idx] |= KFD_DBG_QUEUE_ERROR_MASK;
3468 					break;
3469 				}
3470 			}
3471 		}
3472 
3473 		if (!per_device_suspended) {
3474 			dqm_unlock(dqm);
3475 			mutex_unlock(&p->event_mutex);
3476 			if (total_suspended)
3477 				amdgpu_amdkfd_debug_mem_fence(dqm->dev->adev);
3478 			continue;
3479 		}
3480 
3481 		r = execute_queues_cpsch(dqm,
3482 			KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
3483 			grace_period);
3484 
3485 		if (r)
3486 			dev_err(dev, "Failed to suspend process queues.\n");
3487 		else
3488 			total_suspended += per_device_suspended;
3489 
3490 		list_for_each_entry(q, &qpd->queues_list, list) {
3491 			int q_idx = q_array_get_index(q->properties.queue_id,
3492 						num_queues, queue_ids);
3493 
3494 			if (q_idx == QUEUE_NOT_FOUND)
3495 				continue;
3496 
3497 			/* mask queue as error on suspend fail */
3498 			if (r)
3499 				queue_ids[q_idx] |= KFD_DBG_QUEUE_ERROR_MASK;
3500 			else if (exception_clear_mask)
3501 				q->properties.exception_status &=
3502 							~exception_clear_mask;
3503 		}
3504 
3505 		dqm_unlock(dqm);
3506 		mutex_unlock(&p->event_mutex);
3507 		amdgpu_device_flush_hdp(dqm->dev->adev, NULL);
3508 	}
3509 
3510 	if (total_suspended) {
3511 		struct copy_context_work_handler_workarea copy_context_worker;
3512 
3513 		INIT_WORK_ONSTACK(
3514 				&copy_context_worker.copy_context_work,
3515 				copy_context_work_handler);
3516 
3517 		copy_context_worker.p = p;
3518 
3519 		schedule_work(&copy_context_worker.copy_context_work);
3520 
3521 
3522 		flush_work(&copy_context_worker.copy_context_work);
3523 		destroy_work_on_stack(&copy_context_worker.copy_context_work);
3524 	}
3525 
3526 	if (copy_to_user((void __user *)usr_queue_id_array, queue_ids,
3527 			num_queues * sizeof(uint32_t)))
3528 		pr_err("copy_to_user failed on queue suspend\n");
3529 
3530 	kfree(queue_ids);
3531 
3532 	return total_suspended;
3533 }
3534 
3535 static uint32_t set_queue_type_for_user(struct queue_properties *q_props)
3536 {
3537 	switch (q_props->type) {
3538 	case KFD_QUEUE_TYPE_COMPUTE:
3539 		return q_props->format == KFD_QUEUE_FORMAT_PM4
3540 					? KFD_IOC_QUEUE_TYPE_COMPUTE
3541 					: KFD_IOC_QUEUE_TYPE_COMPUTE_AQL;
3542 	case KFD_QUEUE_TYPE_SDMA:
3543 		return KFD_IOC_QUEUE_TYPE_SDMA;
3544 	case KFD_QUEUE_TYPE_SDMA_XGMI:
3545 		return KFD_IOC_QUEUE_TYPE_SDMA_XGMI;
3546 	default:
3547 		WARN_ONCE(true, "queue type not recognized!");
3548 		return 0xffffffff;
3549 	};
3550 }
3551 
3552 void set_queue_snapshot_entry(struct queue *q,
3553 			      uint64_t exception_clear_mask,
3554 			      struct kfd_queue_snapshot_entry *qss_entry)
3555 {
3556 	qss_entry->ring_base_address = q->properties.queue_address;
3557 	qss_entry->write_pointer_address = (uint64_t)q->properties.write_ptr;
3558 	qss_entry->read_pointer_address = (uint64_t)q->properties.read_ptr;
3559 	qss_entry->ctx_save_restore_address =
3560 				q->properties.ctx_save_restore_area_address;
3561 	qss_entry->ctx_save_restore_area_size =
3562 				q->properties.ctx_save_restore_area_size;
3563 	qss_entry->exception_status = q->properties.exception_status;
3564 	qss_entry->queue_id = q->properties.queue_id;
3565 	qss_entry->gpu_id = q->device->id;
3566 	qss_entry->ring_size = (uint32_t)q->properties.queue_size;
3567 	qss_entry->queue_type = set_queue_type_for_user(&q->properties);
3568 	q->properties.exception_status &= ~exception_clear_mask;
3569 }
3570 
3571 int debug_lock_and_unmap(struct device_queue_manager *dqm)
3572 {
3573 	struct device *dev = dqm->dev->adev->dev;
3574 	int r;
3575 
3576 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3577 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3578 		return -EINVAL;
3579 	}
3580 
3581 	if (!kfd_dbg_is_per_vmid_supported(dqm->dev))
3582 		return 0;
3583 
3584 	dqm_lock(dqm);
3585 
3586 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0, 0, false);
3587 	if (r)
3588 		dqm_unlock(dqm);
3589 
3590 	return r;
3591 }
3592 
3593 int debug_map_and_unlock(struct device_queue_manager *dqm)
3594 {
3595 	struct device *dev = dqm->dev->adev->dev;
3596 	int r;
3597 
3598 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3599 		dev_err(dev, "Unsupported on sched_policy: %i\n", dqm->sched_policy);
3600 		return -EINVAL;
3601 	}
3602 
3603 	if (!kfd_dbg_is_per_vmid_supported(dqm->dev))
3604 		return 0;
3605 
3606 	r = map_queues_cpsch(dqm);
3607 
3608 	dqm_unlock(dqm);
3609 
3610 	return r;
3611 }
3612 
3613 int debug_refresh_runlist(struct device_queue_manager *dqm)
3614 {
3615 	int r = debug_lock_and_unmap(dqm);
3616 
3617 	if (r)
3618 		return r;
3619 
3620 	return debug_map_and_unlock(dqm);
3621 }
3622 
3623 bool kfd_dqm_is_queue_in_process(struct device_queue_manager *dqm,
3624 				 struct qcm_process_device *qpd,
3625 				 int doorbell_off, u32 *queue_format)
3626 {
3627 	struct queue *q;
3628 	bool r = false;
3629 
3630 	if (!queue_format)
3631 		return r;
3632 
3633 	dqm_lock(dqm);
3634 
3635 	list_for_each_entry(q, &qpd->queues_list, list) {
3636 		if (q->properties.doorbell_off == doorbell_off) {
3637 			*queue_format = q->properties.format;
3638 			r = true;
3639 			goto out;
3640 		}
3641 	}
3642 
3643 out:
3644 	dqm_unlock(dqm);
3645 	return r;
3646 }
3647 #if defined(CONFIG_DEBUG_FS)
3648 
3649 static void seq_reg_dump(struct seq_file *m,
3650 			 uint32_t (*dump)[2], uint32_t n_regs)
3651 {
3652 	uint32_t i, count;
3653 
3654 	for (i = 0, count = 0; i < n_regs; i++) {
3655 		if (count == 0 ||
3656 		    dump[i-1][0] + sizeof(uint32_t) != dump[i][0]) {
3657 			seq_printf(m, "%s    %08x: %08x",
3658 				   i ? "\n" : "",
3659 				   dump[i][0], dump[i][1]);
3660 			count = 7;
3661 		} else {
3662 			seq_printf(m, " %08x", dump[i][1]);
3663 			count--;
3664 		}
3665 	}
3666 
3667 	seq_puts(m, "\n");
3668 }
3669 
3670 int dqm_debugfs_hqds(struct seq_file *m, void *data)
3671 {
3672 	struct device_queue_manager *dqm = data;
3673 	uint32_t xcc_mask = dqm->dev->xcc_mask;
3674 	uint32_t (*dump)[2], n_regs;
3675 	int pipe, queue;
3676 	int r = 0, xcc_id;
3677 	uint32_t sdma_engine_start;
3678 
3679 	if (!dqm->sched_running) {
3680 		seq_puts(m, " Device is stopped\n");
3681 		return 0;
3682 	}
3683 
3684 	for_each_inst(xcc_id, xcc_mask) {
3685 		r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->adev,
3686 						KFD_CIK_HIQ_PIPE,
3687 						KFD_CIK_HIQ_QUEUE, &dump,
3688 						&n_regs, xcc_id);
3689 		if (!r) {
3690 			seq_printf(
3691 				m,
3692 				"   Inst %d, HIQ on MEC %d Pipe %d Queue %d\n",
3693 				xcc_id,
3694 				KFD_CIK_HIQ_PIPE / get_pipes_per_mec(dqm) + 1,
3695 				KFD_CIK_HIQ_PIPE % get_pipes_per_mec(dqm),
3696 				KFD_CIK_HIQ_QUEUE);
3697 			seq_reg_dump(m, dump, n_regs);
3698 
3699 			kfree(dump);
3700 		}
3701 
3702 		for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
3703 			int pipe_offset = pipe * get_queues_per_pipe(dqm);
3704 
3705 			for (queue = 0; queue < get_queues_per_pipe(dqm); queue++) {
3706 				if (!test_bit(pipe_offset + queue,
3707 				      dqm->dev->kfd->shared_resources.cp_queue_bitmap))
3708 					continue;
3709 
3710 				r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->adev,
3711 								pipe, queue,
3712 								&dump, &n_regs,
3713 								xcc_id);
3714 				if (r)
3715 					break;
3716 
3717 				seq_printf(m,
3718 					   " Inst %d,  CP Pipe %d, Queue %d\n",
3719 					   xcc_id, pipe, queue);
3720 				seq_reg_dump(m, dump, n_regs);
3721 
3722 				kfree(dump);
3723 			}
3724 		}
3725 	}
3726 
3727 	sdma_engine_start = dqm->dev->node_id * get_num_all_sdma_engines(dqm);
3728 	for (pipe = sdma_engine_start;
3729 	     pipe < (sdma_engine_start + get_num_all_sdma_engines(dqm));
3730 	     pipe++) {
3731 		for (queue = 0;
3732 		     queue < dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
3733 		     queue++) {
3734 			r = dqm->dev->kfd2kgd->hqd_sdma_dump(
3735 				dqm->dev->adev, pipe, queue, &dump, &n_regs);
3736 			if (r)
3737 				break;
3738 
3739 			seq_printf(m, "  SDMA Engine %d, RLC %d\n",
3740 				  pipe, queue);
3741 			seq_reg_dump(m, dump, n_regs);
3742 
3743 			kfree(dump);
3744 		}
3745 	}
3746 
3747 	return r;
3748 }
3749 
3750 int dqm_debugfs_hang_hws(struct device_queue_manager *dqm)
3751 {
3752 	int r = 0;
3753 
3754 	dqm_lock(dqm);
3755 	r = pm_debugfs_hang_hws(&dqm->packet_mgr);
3756 	if (r) {
3757 		dqm_unlock(dqm);
3758 		return r;
3759 	}
3760 	dqm->active_runlist = true;
3761 	r = execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES,
3762 				0, USE_DEFAULT_GRACE_PERIOD);
3763 	dqm_unlock(dqm);
3764 
3765 	return r;
3766 }
3767 
3768 #endif
3769