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