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