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