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