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