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