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