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 = amdgpu_bo_gpu_offset(q->wptr_bo) + 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 					     kfd_dbg_has_ttmps_always_setup(q->device);
232 
233 	queue_type = convert_to_mes_queue_type(q->properties.type);
234 	if (queue_type < 0) {
235 		pr_err("Queue type not supported with MES, queue:%d\n",
236 				q->properties.type);
237 		return -EINVAL;
238 	}
239 	queue_input.queue_type = (uint32_t)queue_type;
240 
241 	queue_input.exclusively_scheduled = q->properties.is_gws;
242 
243 	amdgpu_mes_lock(&adev->mes);
244 	r = adev->mes.funcs->add_hw_queue(&adev->mes, &queue_input);
245 	amdgpu_mes_unlock(&adev->mes);
246 	if (r) {
247 		pr_err("failed to add hardware queue to MES, doorbell=0x%x\n",
248 			q->properties.doorbell_off);
249 		pr_err("MES might be in unrecoverable state, issue a GPU reset\n");
250 		kfd_hws_hang(dqm);
251 	}
252 
253 	return r;
254 }
255 
256 static int remove_queue_mes(struct device_queue_manager *dqm, struct queue *q,
257 			struct qcm_process_device *qpd)
258 {
259 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
260 	int r;
261 	struct mes_remove_queue_input queue_input;
262 
263 	if (dqm->is_hws_hang)
264 		return -EIO;
265 
266 	memset(&queue_input, 0x0, sizeof(struct mes_remove_queue_input));
267 	queue_input.doorbell_offset = q->properties.doorbell_off;
268 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
269 
270 	amdgpu_mes_lock(&adev->mes);
271 	r = adev->mes.funcs->remove_hw_queue(&adev->mes, &queue_input);
272 	amdgpu_mes_unlock(&adev->mes);
273 
274 	if (r) {
275 		pr_err("failed to remove hardware queue from MES, doorbell=0x%x\n",
276 			q->properties.doorbell_off);
277 		pr_err("MES might be in unrecoverable state, issue a GPU reset\n");
278 		kfd_hws_hang(dqm);
279 	}
280 
281 	return r;
282 }
283 
284 static int remove_all_queues_mes(struct device_queue_manager *dqm)
285 {
286 	struct device_process_node *cur;
287 	struct qcm_process_device *qpd;
288 	struct queue *q;
289 	int retval = 0;
290 
291 	list_for_each_entry(cur, &dqm->queues, list) {
292 		qpd = cur->qpd;
293 		list_for_each_entry(q, &qpd->queues_list, list) {
294 			if (q->properties.is_active) {
295 				retval = remove_queue_mes(dqm, q, qpd);
296 				if (retval) {
297 					pr_err("%s: Failed to remove queue %d for dev %d",
298 						__func__,
299 						q->properties.queue_id,
300 						dqm->dev->id);
301 					return retval;
302 				}
303 			}
304 		}
305 	}
306 
307 	return retval;
308 }
309 
310 static void increment_queue_count(struct device_queue_manager *dqm,
311 				  struct qcm_process_device *qpd,
312 				  struct queue *q)
313 {
314 	dqm->active_queue_count++;
315 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
316 	    q->properties.type == KFD_QUEUE_TYPE_DIQ)
317 		dqm->active_cp_queue_count++;
318 
319 	if (q->properties.is_gws) {
320 		dqm->gws_queue_count++;
321 		qpd->mapped_gws_queue = true;
322 	}
323 }
324 
325 static void decrement_queue_count(struct device_queue_manager *dqm,
326 				  struct qcm_process_device *qpd,
327 				  struct queue *q)
328 {
329 	dqm->active_queue_count--;
330 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
331 	    q->properties.type == KFD_QUEUE_TYPE_DIQ)
332 		dqm->active_cp_queue_count--;
333 
334 	if (q->properties.is_gws) {
335 		dqm->gws_queue_count--;
336 		qpd->mapped_gws_queue = false;
337 	}
338 }
339 
340 /*
341  * Allocate a doorbell ID to this queue.
342  * If doorbell_id is passed in, make sure requested ID is valid then allocate it.
343  */
344 static int allocate_doorbell(struct qcm_process_device *qpd,
345 			     struct queue *q,
346 			     uint32_t const *restore_id)
347 {
348 	struct kfd_node *dev = qpd->dqm->dev;
349 
350 	if (!KFD_IS_SOC15(dev)) {
351 		/* On pre-SOC15 chips we need to use the queue ID to
352 		 * preserve the user mode ABI.
353 		 */
354 
355 		if (restore_id && *restore_id != q->properties.queue_id)
356 			return -EINVAL;
357 
358 		q->doorbell_id = q->properties.queue_id;
359 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
360 			q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
361 		/* For SDMA queues on SOC15 with 8-byte doorbell, use static
362 		 * doorbell assignments based on the engine and queue id.
363 		 * The doobell index distance between RLC (2*i) and (2*i+1)
364 		 * for a SDMA engine is 512.
365 		 */
366 
367 		uint32_t *idx_offset = dev->kfd->shared_resources.sdma_doorbell_idx;
368 
369 		/*
370 		 * q->properties.sdma_engine_id corresponds to the virtual
371 		 * sdma engine number. However, for doorbell allocation,
372 		 * we need the physical sdma engine id in order to get the
373 		 * correct doorbell offset.
374 		 */
375 		uint32_t valid_id = idx_offset[qpd->dqm->dev->node_id *
376 					       get_num_all_sdma_engines(qpd->dqm) +
377 					       q->properties.sdma_engine_id]
378 						+ (q->properties.sdma_queue_id & 1)
379 						* KFD_QUEUE_DOORBELL_MIRROR_OFFSET
380 						+ (q->properties.sdma_queue_id >> 1);
381 
382 		if (restore_id && *restore_id != valid_id)
383 			return -EINVAL;
384 		q->doorbell_id = valid_id;
385 	} else {
386 		/* For CP queues on SOC15 */
387 		if (restore_id) {
388 			/* make sure that ID is free  */
389 			if (__test_and_set_bit(*restore_id, qpd->doorbell_bitmap))
390 				return -EINVAL;
391 
392 			q->doorbell_id = *restore_id;
393 		} else {
394 			/* or reserve a free doorbell ID */
395 			unsigned int found;
396 
397 			found = find_first_zero_bit(qpd->doorbell_bitmap,
398 						    KFD_MAX_NUM_OF_QUEUES_PER_PROCESS);
399 			if (found >= KFD_MAX_NUM_OF_QUEUES_PER_PROCESS) {
400 				pr_debug("No doorbells available");
401 				return -EBUSY;
402 			}
403 			set_bit(found, qpd->doorbell_bitmap);
404 			q->doorbell_id = found;
405 		}
406 	}
407 
408 	q->properties.doorbell_off = amdgpu_doorbell_index_on_bar(dev->adev,
409 								  qpd->proc_doorbells,
410 								  q->doorbell_id,
411 								  dev->kfd->device_info.doorbell_size);
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 	}
1683 
1684 	dqm_unlock(dqm);
1685 
1686 	return 0;
1687 fail_allocate_vidmem:
1688 fail_set_sched_resources:
1689 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1690 		pm_uninit(&dqm->packet_mgr, false);
1691 fail_packet_manager_init:
1692 	dqm_unlock(dqm);
1693 	return retval;
1694 }
1695 
1696 static int stop_cpsch(struct device_queue_manager *dqm)
1697 {
1698 	bool hanging;
1699 
1700 	dqm_lock(dqm);
1701 	if (!dqm->sched_running) {
1702 		dqm_unlock(dqm);
1703 		return 0;
1704 	}
1705 
1706 	if (!dqm->is_hws_hang) {
1707 		if (!dqm->dev->kfd->shared_resources.enable_mes)
1708 			unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD, false);
1709 		else
1710 			remove_all_queues_mes(dqm);
1711 	}
1712 
1713 	hanging = dqm->is_hws_hang || dqm->is_resetting;
1714 	dqm->sched_running = false;
1715 
1716 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1717 		pm_release_ib(&dqm->packet_mgr);
1718 
1719 	kfd_gtt_sa_free(dqm->dev, dqm->fence_mem);
1720 	if (!dqm->dev->kfd->shared_resources.enable_mes)
1721 		pm_uninit(&dqm->packet_mgr, hanging);
1722 	dqm_unlock(dqm);
1723 
1724 	return 0;
1725 }
1726 
1727 static int create_kernel_queue_cpsch(struct device_queue_manager *dqm,
1728 					struct kernel_queue *kq,
1729 					struct qcm_process_device *qpd)
1730 {
1731 	dqm_lock(dqm);
1732 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1733 		pr_warn("Can't create new kernel queue because %d queues were already created\n",
1734 				dqm->total_queue_count);
1735 		dqm_unlock(dqm);
1736 		return -EPERM;
1737 	}
1738 
1739 	/*
1740 	 * Unconditionally increment this counter, regardless of the queue's
1741 	 * type or whether the queue is active.
1742 	 */
1743 	dqm->total_queue_count++;
1744 	pr_debug("Total of %d queues are accountable so far\n",
1745 			dqm->total_queue_count);
1746 
1747 	list_add(&kq->list, &qpd->priv_queue_list);
1748 	increment_queue_count(dqm, qpd, kq->queue);
1749 	qpd->is_debug = true;
1750 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
1751 			USE_DEFAULT_GRACE_PERIOD);
1752 	dqm_unlock(dqm);
1753 
1754 	return 0;
1755 }
1756 
1757 static void destroy_kernel_queue_cpsch(struct device_queue_manager *dqm,
1758 					struct kernel_queue *kq,
1759 					struct qcm_process_device *qpd)
1760 {
1761 	dqm_lock(dqm);
1762 	list_del(&kq->list);
1763 	decrement_queue_count(dqm, qpd, kq->queue);
1764 	qpd->is_debug = false;
1765 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
1766 			USE_DEFAULT_GRACE_PERIOD);
1767 	/*
1768 	 * Unconditionally decrement this counter, regardless of the queue's
1769 	 * type.
1770 	 */
1771 	dqm->total_queue_count--;
1772 	pr_debug("Total of %d queues are accountable so far\n",
1773 			dqm->total_queue_count);
1774 	dqm_unlock(dqm);
1775 }
1776 
1777 static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
1778 			struct qcm_process_device *qpd,
1779 			const struct kfd_criu_queue_priv_data *qd,
1780 			const void *restore_mqd, const void *restore_ctl_stack)
1781 {
1782 	int retval;
1783 	struct mqd_manager *mqd_mgr;
1784 
1785 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1786 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
1787 				dqm->total_queue_count);
1788 		retval = -EPERM;
1789 		goto out;
1790 	}
1791 
1792 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1793 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1794 		dqm_lock(dqm);
1795 		retval = allocate_sdma_queue(dqm, q, qd ? &qd->sdma_id : NULL);
1796 		dqm_unlock(dqm);
1797 		if (retval)
1798 			goto out;
1799 	}
1800 
1801 	retval = allocate_doorbell(qpd, q, qd ? &qd->doorbell_id : NULL);
1802 	if (retval)
1803 		goto out_deallocate_sdma_queue;
1804 
1805 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1806 			q->properties.type)];
1807 
1808 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1809 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
1810 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
1811 	q->properties.tba_addr = qpd->tba_addr;
1812 	q->properties.tma_addr = qpd->tma_addr;
1813 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr->dev, &q->properties);
1814 	if (!q->mqd_mem_obj) {
1815 		retval = -ENOMEM;
1816 		goto out_deallocate_doorbell;
1817 	}
1818 
1819 	dqm_lock(dqm);
1820 	/*
1821 	 * Eviction state logic: mark all queues as evicted, even ones
1822 	 * not currently active. Restoring inactive queues later only
1823 	 * updates the is_evicted flag but is a no-op otherwise.
1824 	 */
1825 	q->properties.is_evicted = !!qpd->evicted;
1826 	q->properties.is_dbg_wa = qpd->pqm->process->debug_trap_enabled &&
1827 				  kfd_dbg_has_cwsr_workaround(q->device);
1828 
1829 	if (qd)
1830 		mqd_mgr->restore_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj, &q->gart_mqd_addr,
1831 				     &q->properties, restore_mqd, restore_ctl_stack,
1832 				     qd->ctl_stack_size);
1833 	else
1834 		mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
1835 					&q->gart_mqd_addr, &q->properties);
1836 
1837 	list_add(&q->list, &qpd->queues_list);
1838 	qpd->queue_count++;
1839 
1840 	if (q->properties.is_active) {
1841 		increment_queue_count(dqm, qpd, q);
1842 
1843 		if (!dqm->dev->kfd->shared_resources.enable_mes)
1844 			retval = execute_queues_cpsch(dqm,
1845 					KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, USE_DEFAULT_GRACE_PERIOD);
1846 		else
1847 			retval = add_queue_mes(dqm, q, qpd);
1848 		if (retval)
1849 			goto cleanup_queue;
1850 	}
1851 
1852 	/*
1853 	 * Unconditionally increment this counter, regardless of the queue's
1854 	 * type or whether the queue is active.
1855 	 */
1856 	dqm->total_queue_count++;
1857 
1858 	pr_debug("Total of %d queues are accountable so far\n",
1859 			dqm->total_queue_count);
1860 
1861 	dqm_unlock(dqm);
1862 	return retval;
1863 
1864 cleanup_queue:
1865 	qpd->queue_count--;
1866 	list_del(&q->list);
1867 	if (q->properties.is_active)
1868 		decrement_queue_count(dqm, qpd, q);
1869 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
1870 	dqm_unlock(dqm);
1871 out_deallocate_doorbell:
1872 	deallocate_doorbell(qpd, q);
1873 out_deallocate_sdma_queue:
1874 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1875 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1876 		dqm_lock(dqm);
1877 		deallocate_sdma_queue(dqm, q);
1878 		dqm_unlock(dqm);
1879 	}
1880 out:
1881 	return retval;
1882 }
1883 
1884 int amdkfd_fence_wait_timeout(uint64_t *fence_addr,
1885 				uint64_t fence_value,
1886 				unsigned int timeout_ms)
1887 {
1888 	unsigned long end_jiffies = msecs_to_jiffies(timeout_ms) + jiffies;
1889 
1890 	while (*fence_addr != fence_value) {
1891 		if (time_after(jiffies, end_jiffies)) {
1892 			pr_err("qcm fence wait loop timeout expired\n");
1893 			/* In HWS case, this is used to halt the driver thread
1894 			 * in order not to mess up CP states before doing
1895 			 * scandumps for FW debugging.
1896 			 */
1897 			while (halt_if_hws_hang)
1898 				schedule();
1899 
1900 			return -ETIME;
1901 		}
1902 		schedule();
1903 	}
1904 
1905 	return 0;
1906 }
1907 
1908 /* dqm->lock mutex has to be locked before calling this function */
1909 static int map_queues_cpsch(struct device_queue_manager *dqm)
1910 {
1911 	int retval;
1912 
1913 	if (!dqm->sched_running)
1914 		return 0;
1915 	if (dqm->active_queue_count <= 0 || dqm->processes_count <= 0)
1916 		return 0;
1917 	if (dqm->active_runlist)
1918 		return 0;
1919 
1920 	retval = pm_send_runlist(&dqm->packet_mgr, &dqm->queues);
1921 	pr_debug("%s sent runlist\n", __func__);
1922 	if (retval) {
1923 		pr_err("failed to execute runlist\n");
1924 		return retval;
1925 	}
1926 	dqm->active_runlist = true;
1927 
1928 	return retval;
1929 }
1930 
1931 /* dqm->lock mutex has to be locked before calling this function */
1932 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
1933 				enum kfd_unmap_queues_filter filter,
1934 				uint32_t filter_param,
1935 				uint32_t grace_period,
1936 				bool reset)
1937 {
1938 	int retval = 0;
1939 	struct mqd_manager *mqd_mgr;
1940 
1941 	if (!dqm->sched_running)
1942 		return 0;
1943 	if (dqm->is_hws_hang || dqm->is_resetting)
1944 		return -EIO;
1945 	if (!dqm->active_runlist)
1946 		return retval;
1947 
1948 	if (grace_period != USE_DEFAULT_GRACE_PERIOD) {
1949 		retval = pm_update_grace_period(&dqm->packet_mgr, grace_period);
1950 		if (retval)
1951 			return retval;
1952 	}
1953 
1954 	retval = pm_send_unmap_queue(&dqm->packet_mgr, filter, filter_param, reset);
1955 	if (retval)
1956 		return retval;
1957 
1958 	*dqm->fence_addr = KFD_FENCE_INIT;
1959 	pm_send_query_status(&dqm->packet_mgr, dqm->fence_gpu_addr,
1960 				KFD_FENCE_COMPLETED);
1961 	/* should be timed out */
1962 	retval = amdkfd_fence_wait_timeout(dqm->fence_addr, KFD_FENCE_COMPLETED,
1963 				queue_preemption_timeout_ms);
1964 	if (retval) {
1965 		pr_err("The cp might be in an unrecoverable state due to an unsuccessful queues preemption\n");
1966 		kfd_hws_hang(dqm);
1967 		return retval;
1968 	}
1969 
1970 	/* In the current MEC firmware implementation, if compute queue
1971 	 * doesn't response to the preemption request in time, HIQ will
1972 	 * abandon the unmap request without returning any timeout error
1973 	 * to driver. Instead, MEC firmware will log the doorbell of the
1974 	 * unresponding compute queue to HIQ.MQD.queue_doorbell_id fields.
1975 	 * To make sure the queue unmap was successful, driver need to
1976 	 * check those fields
1977 	 */
1978 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ];
1979 	if (mqd_mgr->read_doorbell_id(dqm->packet_mgr.priv_queue->queue->mqd)) {
1980 		pr_err("HIQ MQD's queue_doorbell_id0 is not 0, Queue preemption time out\n");
1981 		while (halt_if_hws_hang)
1982 			schedule();
1983 		return -ETIME;
1984 	}
1985 
1986 	/* We need to reset the grace period value for this device */
1987 	if (grace_period != USE_DEFAULT_GRACE_PERIOD) {
1988 		if (pm_update_grace_period(&dqm->packet_mgr,
1989 					USE_DEFAULT_GRACE_PERIOD))
1990 			pr_err("Failed to reset grace period\n");
1991 	}
1992 
1993 	pm_release_ib(&dqm->packet_mgr);
1994 	dqm->active_runlist = false;
1995 
1996 	return retval;
1997 }
1998 
1999 /* only for compute queue */
2000 static int reset_queues_cpsch(struct device_queue_manager *dqm,
2001 			uint16_t pasid)
2002 {
2003 	int retval;
2004 
2005 	dqm_lock(dqm);
2006 
2007 	retval = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_BY_PASID,
2008 			pasid, USE_DEFAULT_GRACE_PERIOD, true);
2009 
2010 	dqm_unlock(dqm);
2011 	return retval;
2012 }
2013 
2014 /* dqm->lock mutex has to be locked before calling this function */
2015 static int execute_queues_cpsch(struct device_queue_manager *dqm,
2016 				enum kfd_unmap_queues_filter filter,
2017 				uint32_t filter_param,
2018 				uint32_t grace_period)
2019 {
2020 	int retval;
2021 
2022 	if (dqm->is_hws_hang)
2023 		return -EIO;
2024 	retval = unmap_queues_cpsch(dqm, filter, filter_param, grace_period, false);
2025 	if (retval)
2026 		return retval;
2027 
2028 	return map_queues_cpsch(dqm);
2029 }
2030 
2031 static int wait_on_destroy_queue(struct device_queue_manager *dqm,
2032 				 struct queue *q)
2033 {
2034 	struct kfd_process_device *pdd = kfd_get_process_device_data(q->device,
2035 								q->process);
2036 	int ret = 0;
2037 
2038 	if (pdd->qpd.is_debug)
2039 		return ret;
2040 
2041 	q->properties.is_being_destroyed = true;
2042 
2043 	if (pdd->process->debug_trap_enabled && q->properties.is_suspended) {
2044 		dqm_unlock(dqm);
2045 		mutex_unlock(&q->process->mutex);
2046 		ret = wait_event_interruptible(dqm->destroy_wait,
2047 						!q->properties.is_suspended);
2048 
2049 		mutex_lock(&q->process->mutex);
2050 		dqm_lock(dqm);
2051 	}
2052 
2053 	return ret;
2054 }
2055 
2056 static int destroy_queue_cpsch(struct device_queue_manager *dqm,
2057 				struct qcm_process_device *qpd,
2058 				struct queue *q)
2059 {
2060 	int retval;
2061 	struct mqd_manager *mqd_mgr;
2062 	uint64_t sdma_val = 0;
2063 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
2064 
2065 	/* Get the SDMA queue stats */
2066 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
2067 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
2068 		retval = read_sdma_queue_counter((uint64_t __user *)q->properties.read_ptr,
2069 							&sdma_val);
2070 		if (retval)
2071 			pr_err("Failed to read SDMA queue counter for queue: %d\n",
2072 				q->properties.queue_id);
2073 	}
2074 
2075 	/* remove queue from list to prevent rescheduling after preemption */
2076 	dqm_lock(dqm);
2077 
2078 	retval = wait_on_destroy_queue(dqm, q);
2079 
2080 	if (retval) {
2081 		dqm_unlock(dqm);
2082 		return retval;
2083 	}
2084 
2085 	if (qpd->is_debug) {
2086 		/*
2087 		 * error, currently we do not allow to destroy a queue
2088 		 * of a currently debugged process
2089 		 */
2090 		retval = -EBUSY;
2091 		goto failed_try_destroy_debugged_queue;
2092 
2093 	}
2094 
2095 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2096 			q->properties.type)];
2097 
2098 	deallocate_doorbell(qpd, q);
2099 
2100 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
2101 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
2102 		deallocate_sdma_queue(dqm, q);
2103 		pdd->sdma_past_activity_counter += sdma_val;
2104 	}
2105 
2106 	list_del(&q->list);
2107 	qpd->queue_count--;
2108 	if (q->properties.is_active) {
2109 		decrement_queue_count(dqm, qpd, q);
2110 		if (!dqm->dev->kfd->shared_resources.enable_mes) {
2111 			retval = execute_queues_cpsch(dqm,
2112 						      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
2113 						      USE_DEFAULT_GRACE_PERIOD);
2114 			if (retval == -ETIME)
2115 				qpd->reset_wavefronts = true;
2116 		} else {
2117 			retval = remove_queue_mes(dqm, q, qpd);
2118 		}
2119 	}
2120 
2121 	/*
2122 	 * Unconditionally decrement this counter, regardless of the queue's
2123 	 * type
2124 	 */
2125 	dqm->total_queue_count--;
2126 	pr_debug("Total of %d queues are accountable so far\n",
2127 			dqm->total_queue_count);
2128 
2129 	dqm_unlock(dqm);
2130 
2131 	/*
2132 	 * Do free_mqd and raise delete event after dqm_unlock(dqm) to avoid
2133 	 * circular locking
2134 	 */
2135 	kfd_dbg_ev_raise(KFD_EC_MASK(EC_DEVICE_QUEUE_DELETE),
2136 				qpd->pqm->process, q->device,
2137 				-1, false, NULL, 0);
2138 
2139 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2140 
2141 	return retval;
2142 
2143 failed_try_destroy_debugged_queue:
2144 
2145 	dqm_unlock(dqm);
2146 	return retval;
2147 }
2148 
2149 /*
2150  * Low bits must be 0000/FFFF as required by HW, high bits must be 0 to
2151  * stay in user mode.
2152  */
2153 #define APE1_FIXED_BITS_MASK 0xFFFF80000000FFFFULL
2154 /* APE1 limit is inclusive and 64K aligned. */
2155 #define APE1_LIMIT_ALIGNMENT 0xFFFF
2156 
2157 static bool set_cache_memory_policy(struct device_queue_manager *dqm,
2158 				   struct qcm_process_device *qpd,
2159 				   enum cache_policy default_policy,
2160 				   enum cache_policy alternate_policy,
2161 				   void __user *alternate_aperture_base,
2162 				   uint64_t alternate_aperture_size)
2163 {
2164 	bool retval = true;
2165 
2166 	if (!dqm->asic_ops.set_cache_memory_policy)
2167 		return retval;
2168 
2169 	dqm_lock(dqm);
2170 
2171 	if (alternate_aperture_size == 0) {
2172 		/* base > limit disables APE1 */
2173 		qpd->sh_mem_ape1_base = 1;
2174 		qpd->sh_mem_ape1_limit = 0;
2175 	} else {
2176 		/*
2177 		 * In FSA64, APE1_Base[63:0] = { 16{SH_MEM_APE1_BASE[31]},
2178 		 *			SH_MEM_APE1_BASE[31:0], 0x0000 }
2179 		 * APE1_Limit[63:0] = { 16{SH_MEM_APE1_LIMIT[31]},
2180 		 *			SH_MEM_APE1_LIMIT[31:0], 0xFFFF }
2181 		 * Verify that the base and size parameters can be
2182 		 * represented in this format and convert them.
2183 		 * Additionally restrict APE1 to user-mode addresses.
2184 		 */
2185 
2186 		uint64_t base = (uintptr_t)alternate_aperture_base;
2187 		uint64_t limit = base + alternate_aperture_size - 1;
2188 
2189 		if (limit <= base || (base & APE1_FIXED_BITS_MASK) != 0 ||
2190 		   (limit & APE1_FIXED_BITS_MASK) != APE1_LIMIT_ALIGNMENT) {
2191 			retval = false;
2192 			goto out;
2193 		}
2194 
2195 		qpd->sh_mem_ape1_base = base >> 16;
2196 		qpd->sh_mem_ape1_limit = limit >> 16;
2197 	}
2198 
2199 	retval = dqm->asic_ops.set_cache_memory_policy(
2200 			dqm,
2201 			qpd,
2202 			default_policy,
2203 			alternate_policy,
2204 			alternate_aperture_base,
2205 			alternate_aperture_size);
2206 
2207 	if ((dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) && (qpd->vmid != 0))
2208 		program_sh_mem_settings(dqm, qpd);
2209 
2210 	pr_debug("sh_mem_config: 0x%x, ape1_base: 0x%x, ape1_limit: 0x%x\n",
2211 		qpd->sh_mem_config, qpd->sh_mem_ape1_base,
2212 		qpd->sh_mem_ape1_limit);
2213 
2214 out:
2215 	dqm_unlock(dqm);
2216 	return retval;
2217 }
2218 
2219 static int process_termination_nocpsch(struct device_queue_manager *dqm,
2220 		struct qcm_process_device *qpd)
2221 {
2222 	struct queue *q;
2223 	struct device_process_node *cur, *next_dpn;
2224 	int retval = 0;
2225 	bool found = false;
2226 
2227 	dqm_lock(dqm);
2228 
2229 	/* Clear all user mode queues */
2230 	while (!list_empty(&qpd->queues_list)) {
2231 		struct mqd_manager *mqd_mgr;
2232 		int ret;
2233 
2234 		q = list_first_entry(&qpd->queues_list, struct queue, list);
2235 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2236 				q->properties.type)];
2237 		ret = destroy_queue_nocpsch_locked(dqm, qpd, q);
2238 		if (ret)
2239 			retval = ret;
2240 		dqm_unlock(dqm);
2241 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2242 		dqm_lock(dqm);
2243 	}
2244 
2245 	/* Unregister process */
2246 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
2247 		if (qpd == cur->qpd) {
2248 			list_del(&cur->list);
2249 			kfree(cur);
2250 			dqm->processes_count--;
2251 			found = true;
2252 			break;
2253 		}
2254 	}
2255 
2256 	dqm_unlock(dqm);
2257 
2258 	/* Outside the DQM lock because under the DQM lock we can't do
2259 	 * reclaim or take other locks that others hold while reclaiming.
2260 	 */
2261 	if (found)
2262 		kfd_dec_compute_active(dqm->dev);
2263 
2264 	return retval;
2265 }
2266 
2267 static int get_wave_state(struct device_queue_manager *dqm,
2268 			  struct queue *q,
2269 			  void __user *ctl_stack,
2270 			  u32 *ctl_stack_used_size,
2271 			  u32 *save_area_used_size)
2272 {
2273 	struct mqd_manager *mqd_mgr;
2274 
2275 	dqm_lock(dqm);
2276 
2277 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_CP];
2278 
2279 	if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE ||
2280 	    q->properties.is_active || !q->device->kfd->cwsr_enabled ||
2281 	    !mqd_mgr->get_wave_state) {
2282 		dqm_unlock(dqm);
2283 		return -EINVAL;
2284 	}
2285 
2286 	dqm_unlock(dqm);
2287 
2288 	/*
2289 	 * get_wave_state is outside the dqm lock to prevent circular locking
2290 	 * and the queue should be protected against destruction by the process
2291 	 * lock.
2292 	 */
2293 	return mqd_mgr->get_wave_state(mqd_mgr, q->mqd, &q->properties,
2294 			ctl_stack, ctl_stack_used_size, save_area_used_size);
2295 }
2296 
2297 static void get_queue_checkpoint_info(struct device_queue_manager *dqm,
2298 			const struct queue *q,
2299 			u32 *mqd_size,
2300 			u32 *ctl_stack_size)
2301 {
2302 	struct mqd_manager *mqd_mgr;
2303 	enum KFD_MQD_TYPE mqd_type =
2304 			get_mqd_type_from_queue_type(q->properties.type);
2305 
2306 	dqm_lock(dqm);
2307 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
2308 	*mqd_size = mqd_mgr->mqd_size;
2309 	*ctl_stack_size = 0;
2310 
2311 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE && mqd_mgr->get_checkpoint_info)
2312 		mqd_mgr->get_checkpoint_info(mqd_mgr, q->mqd, ctl_stack_size);
2313 
2314 	dqm_unlock(dqm);
2315 }
2316 
2317 static int checkpoint_mqd(struct device_queue_manager *dqm,
2318 			  const struct queue *q,
2319 			  void *mqd,
2320 			  void *ctl_stack)
2321 {
2322 	struct mqd_manager *mqd_mgr;
2323 	int r = 0;
2324 	enum KFD_MQD_TYPE mqd_type =
2325 			get_mqd_type_from_queue_type(q->properties.type);
2326 
2327 	dqm_lock(dqm);
2328 
2329 	if (q->properties.is_active || !q->device->kfd->cwsr_enabled) {
2330 		r = -EINVAL;
2331 		goto dqm_unlock;
2332 	}
2333 
2334 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
2335 	if (!mqd_mgr->checkpoint_mqd) {
2336 		r = -EOPNOTSUPP;
2337 		goto dqm_unlock;
2338 	}
2339 
2340 	mqd_mgr->checkpoint_mqd(mqd_mgr, q->mqd, mqd, ctl_stack);
2341 
2342 dqm_unlock:
2343 	dqm_unlock(dqm);
2344 	return r;
2345 }
2346 
2347 static int process_termination_cpsch(struct device_queue_manager *dqm,
2348 		struct qcm_process_device *qpd)
2349 {
2350 	int retval;
2351 	struct queue *q;
2352 	struct kernel_queue *kq, *kq_next;
2353 	struct mqd_manager *mqd_mgr;
2354 	struct device_process_node *cur, *next_dpn;
2355 	enum kfd_unmap_queues_filter filter =
2356 		KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES;
2357 	bool found = false;
2358 
2359 	retval = 0;
2360 
2361 	dqm_lock(dqm);
2362 
2363 	/* Clean all kernel queues */
2364 	list_for_each_entry_safe(kq, kq_next, &qpd->priv_queue_list, list) {
2365 		list_del(&kq->list);
2366 		decrement_queue_count(dqm, qpd, kq->queue);
2367 		qpd->is_debug = false;
2368 		dqm->total_queue_count--;
2369 		filter = KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES;
2370 	}
2371 
2372 	/* Clear all user mode queues */
2373 	list_for_each_entry(q, &qpd->queues_list, list) {
2374 		if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
2375 			deallocate_sdma_queue(dqm, q);
2376 		else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
2377 			deallocate_sdma_queue(dqm, q);
2378 
2379 		if (q->properties.is_active) {
2380 			decrement_queue_count(dqm, qpd, q);
2381 
2382 			if (dqm->dev->kfd->shared_resources.enable_mes) {
2383 				retval = remove_queue_mes(dqm, q, qpd);
2384 				if (retval)
2385 					pr_err("Failed to remove queue %d\n",
2386 						q->properties.queue_id);
2387 			}
2388 		}
2389 
2390 		dqm->total_queue_count--;
2391 	}
2392 
2393 	/* Unregister process */
2394 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
2395 		if (qpd == cur->qpd) {
2396 			list_del(&cur->list);
2397 			kfree(cur);
2398 			dqm->processes_count--;
2399 			found = true;
2400 			break;
2401 		}
2402 	}
2403 
2404 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2405 		retval = execute_queues_cpsch(dqm, filter, 0, USE_DEFAULT_GRACE_PERIOD);
2406 
2407 	if ((!dqm->is_hws_hang) && (retval || qpd->reset_wavefronts)) {
2408 		pr_warn("Resetting wave fronts (cpsch) on dev %p\n", dqm->dev);
2409 		dbgdev_wave_reset_wavefronts(dqm->dev, qpd->pqm->process);
2410 		qpd->reset_wavefronts = false;
2411 	}
2412 
2413 	/* Lastly, free mqd resources.
2414 	 * Do free_mqd() after dqm_unlock to avoid circular locking.
2415 	 */
2416 	while (!list_empty(&qpd->queues_list)) {
2417 		q = list_first_entry(&qpd->queues_list, struct queue, list);
2418 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2419 				q->properties.type)];
2420 		list_del(&q->list);
2421 		qpd->queue_count--;
2422 		dqm_unlock(dqm);
2423 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2424 		dqm_lock(dqm);
2425 	}
2426 	dqm_unlock(dqm);
2427 
2428 	/* Outside the DQM lock because under the DQM lock we can't do
2429 	 * reclaim or take other locks that others hold while reclaiming.
2430 	 */
2431 	if (found)
2432 		kfd_dec_compute_active(dqm->dev);
2433 
2434 	return retval;
2435 }
2436 
2437 static int init_mqd_managers(struct device_queue_manager *dqm)
2438 {
2439 	int i, j;
2440 	struct mqd_manager *mqd_mgr;
2441 
2442 	for (i = 0; i < KFD_MQD_TYPE_MAX; i++) {
2443 		mqd_mgr = dqm->asic_ops.mqd_manager_init(i, dqm->dev);
2444 		if (!mqd_mgr) {
2445 			pr_err("mqd manager [%d] initialization failed\n", i);
2446 			goto out_free;
2447 		}
2448 		dqm->mqd_mgrs[i] = mqd_mgr;
2449 	}
2450 
2451 	return 0;
2452 
2453 out_free:
2454 	for (j = 0; j < i; j++) {
2455 		kfree(dqm->mqd_mgrs[j]);
2456 		dqm->mqd_mgrs[j] = NULL;
2457 	}
2458 
2459 	return -ENOMEM;
2460 }
2461 
2462 /* Allocate one hiq mqd (HWS) and all SDMA mqd in a continuous trunk*/
2463 static int allocate_hiq_sdma_mqd(struct device_queue_manager *dqm)
2464 {
2465 	int retval;
2466 	struct kfd_node *dev = dqm->dev;
2467 	struct kfd_mem_obj *mem_obj = &dqm->hiq_sdma_mqd;
2468 	uint32_t size = dqm->mqd_mgrs[KFD_MQD_TYPE_SDMA]->mqd_size *
2469 		get_num_all_sdma_engines(dqm) *
2470 		dev->kfd->device_info.num_sdma_queues_per_engine +
2471 		(dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ]->mqd_size *
2472 		NUM_XCC(dqm->dev->xcc_mask));
2473 
2474 	retval = amdgpu_amdkfd_alloc_gtt_mem(dev->adev, size,
2475 		&(mem_obj->gtt_mem), &(mem_obj->gpu_addr),
2476 		(void *)&(mem_obj->cpu_ptr), false);
2477 
2478 	return retval;
2479 }
2480 
2481 struct device_queue_manager *device_queue_manager_init(struct kfd_node *dev)
2482 {
2483 	struct device_queue_manager *dqm;
2484 
2485 	pr_debug("Loading device queue manager\n");
2486 
2487 	dqm = kzalloc(sizeof(*dqm), GFP_KERNEL);
2488 	if (!dqm)
2489 		return NULL;
2490 
2491 	switch (dev->adev->asic_type) {
2492 	/* HWS is not available on Hawaii. */
2493 	case CHIP_HAWAII:
2494 	/* HWS depends on CWSR for timely dequeue. CWSR is not
2495 	 * available on Tonga.
2496 	 *
2497 	 * FIXME: This argument also applies to Kaveri.
2498 	 */
2499 	case CHIP_TONGA:
2500 		dqm->sched_policy = KFD_SCHED_POLICY_NO_HWS;
2501 		break;
2502 	default:
2503 		dqm->sched_policy = sched_policy;
2504 		break;
2505 	}
2506 
2507 	dqm->dev = dev;
2508 	switch (dqm->sched_policy) {
2509 	case KFD_SCHED_POLICY_HWS:
2510 	case KFD_SCHED_POLICY_HWS_NO_OVERSUBSCRIPTION:
2511 		/* initialize dqm for cp scheduling */
2512 		dqm->ops.create_queue = create_queue_cpsch;
2513 		dqm->ops.initialize = initialize_cpsch;
2514 		dqm->ops.start = start_cpsch;
2515 		dqm->ops.stop = stop_cpsch;
2516 		dqm->ops.pre_reset = pre_reset;
2517 		dqm->ops.destroy_queue = destroy_queue_cpsch;
2518 		dqm->ops.update_queue = update_queue;
2519 		dqm->ops.register_process = register_process;
2520 		dqm->ops.unregister_process = unregister_process;
2521 		dqm->ops.uninitialize = uninitialize;
2522 		dqm->ops.create_kernel_queue = create_kernel_queue_cpsch;
2523 		dqm->ops.destroy_kernel_queue = destroy_kernel_queue_cpsch;
2524 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
2525 		dqm->ops.process_termination = process_termination_cpsch;
2526 		dqm->ops.evict_process_queues = evict_process_queues_cpsch;
2527 		dqm->ops.restore_process_queues = restore_process_queues_cpsch;
2528 		dqm->ops.get_wave_state = get_wave_state;
2529 		dqm->ops.reset_queues = reset_queues_cpsch;
2530 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
2531 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
2532 		break;
2533 	case KFD_SCHED_POLICY_NO_HWS:
2534 		/* initialize dqm for no cp scheduling */
2535 		dqm->ops.start = start_nocpsch;
2536 		dqm->ops.stop = stop_nocpsch;
2537 		dqm->ops.pre_reset = pre_reset;
2538 		dqm->ops.create_queue = create_queue_nocpsch;
2539 		dqm->ops.destroy_queue = destroy_queue_nocpsch;
2540 		dqm->ops.update_queue = update_queue;
2541 		dqm->ops.register_process = register_process;
2542 		dqm->ops.unregister_process = unregister_process;
2543 		dqm->ops.initialize = initialize_nocpsch;
2544 		dqm->ops.uninitialize = uninitialize;
2545 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
2546 		dqm->ops.process_termination = process_termination_nocpsch;
2547 		dqm->ops.evict_process_queues = evict_process_queues_nocpsch;
2548 		dqm->ops.restore_process_queues =
2549 			restore_process_queues_nocpsch;
2550 		dqm->ops.get_wave_state = get_wave_state;
2551 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
2552 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
2553 		break;
2554 	default:
2555 		pr_err("Invalid scheduling policy %d\n", dqm->sched_policy);
2556 		goto out_free;
2557 	}
2558 
2559 	switch (dev->adev->asic_type) {
2560 	case CHIP_KAVERI:
2561 	case CHIP_HAWAII:
2562 		device_queue_manager_init_cik(&dqm->asic_ops);
2563 		break;
2564 
2565 	case CHIP_CARRIZO:
2566 	case CHIP_TONGA:
2567 	case CHIP_FIJI:
2568 	case CHIP_POLARIS10:
2569 	case CHIP_POLARIS11:
2570 	case CHIP_POLARIS12:
2571 	case CHIP_VEGAM:
2572 		device_queue_manager_init_vi(&dqm->asic_ops);
2573 		break;
2574 
2575 	default:
2576 		if (KFD_GC_VERSION(dev) >= IP_VERSION(11, 0, 0))
2577 			device_queue_manager_init_v11(&dqm->asic_ops);
2578 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(10, 1, 1))
2579 			device_queue_manager_init_v10(&dqm->asic_ops);
2580 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(9, 0, 1))
2581 			device_queue_manager_init_v9(&dqm->asic_ops);
2582 		else {
2583 			WARN(1, "Unexpected ASIC family %u",
2584 			     dev->adev->asic_type);
2585 			goto out_free;
2586 		}
2587 	}
2588 
2589 	if (init_mqd_managers(dqm))
2590 		goto out_free;
2591 
2592 	if (!dev->kfd->shared_resources.enable_mes && allocate_hiq_sdma_mqd(dqm)) {
2593 		pr_err("Failed to allocate hiq sdma mqd trunk buffer\n");
2594 		goto out_free;
2595 	}
2596 
2597 	if (!dqm->ops.initialize(dqm)) {
2598 		init_waitqueue_head(&dqm->destroy_wait);
2599 		return dqm;
2600 	}
2601 
2602 out_free:
2603 	kfree(dqm);
2604 	return NULL;
2605 }
2606 
2607 static void deallocate_hiq_sdma_mqd(struct kfd_node *dev,
2608 				    struct kfd_mem_obj *mqd)
2609 {
2610 	WARN(!mqd, "No hiq sdma mqd trunk to free");
2611 
2612 	amdgpu_amdkfd_free_gtt_mem(dev->adev, mqd->gtt_mem);
2613 }
2614 
2615 void device_queue_manager_uninit(struct device_queue_manager *dqm)
2616 {
2617 	dqm->ops.stop(dqm);
2618 	dqm->ops.uninitialize(dqm);
2619 	if (!dqm->dev->kfd->shared_resources.enable_mes)
2620 		deallocate_hiq_sdma_mqd(dqm->dev, &dqm->hiq_sdma_mqd);
2621 	kfree(dqm);
2622 }
2623 
2624 int kfd_dqm_evict_pasid(struct device_queue_manager *dqm, u32 pasid)
2625 {
2626 	struct kfd_process_device *pdd;
2627 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid);
2628 	int ret = 0;
2629 
2630 	if (!p)
2631 		return -EINVAL;
2632 	WARN(debug_evictions, "Evicting pid %d", p->lead_thread->pid);
2633 	pdd = kfd_get_process_device_data(dqm->dev, p);
2634 	if (pdd)
2635 		ret = dqm->ops.evict_process_queues(dqm, &pdd->qpd);
2636 	kfd_unref_process(p);
2637 
2638 	return ret;
2639 }
2640 
2641 static void kfd_process_hw_exception(struct work_struct *work)
2642 {
2643 	struct device_queue_manager *dqm = container_of(work,
2644 			struct device_queue_manager, hw_exception_work);
2645 	amdgpu_amdkfd_gpu_reset(dqm->dev->adev);
2646 }
2647 
2648 int reserve_debug_trap_vmid(struct device_queue_manager *dqm,
2649 				struct qcm_process_device *qpd)
2650 {
2651 	int r;
2652 	int updated_vmid_mask;
2653 
2654 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
2655 		pr_err("Unsupported on sched_policy: %i\n", dqm->sched_policy);
2656 		return -EINVAL;
2657 	}
2658 
2659 	dqm_lock(dqm);
2660 
2661 	if (dqm->trap_debug_vmid != 0) {
2662 		pr_err("Trap debug id already reserved\n");
2663 		r = -EBUSY;
2664 		goto out_unlock;
2665 	}
2666 
2667 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
2668 			USE_DEFAULT_GRACE_PERIOD, false);
2669 	if (r)
2670 		goto out_unlock;
2671 
2672 	updated_vmid_mask = dqm->dev->kfd->shared_resources.compute_vmid_bitmap;
2673 	updated_vmid_mask &= ~(1 << dqm->dev->vm_info.last_vmid_kfd);
2674 
2675 	dqm->dev->kfd->shared_resources.compute_vmid_bitmap = updated_vmid_mask;
2676 	dqm->trap_debug_vmid = dqm->dev->vm_info.last_vmid_kfd;
2677 	r = set_sched_resources(dqm);
2678 	if (r)
2679 		goto out_unlock;
2680 
2681 	r = map_queues_cpsch(dqm);
2682 	if (r)
2683 		goto out_unlock;
2684 
2685 	pr_debug("Reserved VMID for trap debug: %i\n", dqm->trap_debug_vmid);
2686 
2687 out_unlock:
2688 	dqm_unlock(dqm);
2689 	return r;
2690 }
2691 
2692 /*
2693  * Releases vmid for the trap debugger
2694  */
2695 int release_debug_trap_vmid(struct device_queue_manager *dqm,
2696 			struct qcm_process_device *qpd)
2697 {
2698 	int r;
2699 	int updated_vmid_mask;
2700 	uint32_t trap_debug_vmid;
2701 
2702 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
2703 		pr_err("Unsupported on sched_policy: %i\n", dqm->sched_policy);
2704 		return -EINVAL;
2705 	}
2706 
2707 	dqm_lock(dqm);
2708 	trap_debug_vmid = dqm->trap_debug_vmid;
2709 	if (dqm->trap_debug_vmid == 0) {
2710 		pr_err("Trap debug id is not reserved\n");
2711 		r = -EINVAL;
2712 		goto out_unlock;
2713 	}
2714 
2715 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0,
2716 			USE_DEFAULT_GRACE_PERIOD, false);
2717 	if (r)
2718 		goto out_unlock;
2719 
2720 	updated_vmid_mask = dqm->dev->kfd->shared_resources.compute_vmid_bitmap;
2721 	updated_vmid_mask |= (1 << dqm->dev->vm_info.last_vmid_kfd);
2722 
2723 	dqm->dev->kfd->shared_resources.compute_vmid_bitmap = updated_vmid_mask;
2724 	dqm->trap_debug_vmid = 0;
2725 	r = set_sched_resources(dqm);
2726 	if (r)
2727 		goto out_unlock;
2728 
2729 	r = map_queues_cpsch(dqm);
2730 	if (r)
2731 		goto out_unlock;
2732 
2733 	pr_debug("Released VMID for trap debug: %i\n", trap_debug_vmid);
2734 
2735 out_unlock:
2736 	dqm_unlock(dqm);
2737 	return r;
2738 }
2739 
2740 #define QUEUE_NOT_FOUND		-1
2741 /* invalidate queue operation in array */
2742 static void q_array_invalidate(uint32_t num_queues, uint32_t *queue_ids)
2743 {
2744 	int i;
2745 
2746 	for (i = 0; i < num_queues; i++)
2747 		queue_ids[i] |= KFD_DBG_QUEUE_INVALID_MASK;
2748 }
2749 
2750 /* find queue index in array */
2751 static int q_array_get_index(unsigned int queue_id,
2752 		uint32_t num_queues,
2753 		uint32_t *queue_ids)
2754 {
2755 	int i;
2756 
2757 	for (i = 0; i < num_queues; i++)
2758 		if (queue_id == (queue_ids[i] & ~KFD_DBG_QUEUE_INVALID_MASK))
2759 			return i;
2760 
2761 	return QUEUE_NOT_FOUND;
2762 }
2763 
2764 struct copy_context_work_handler_workarea {
2765 	struct work_struct copy_context_work;
2766 	struct kfd_process *p;
2767 };
2768 
2769 static void copy_context_work_handler (struct work_struct *work)
2770 {
2771 	struct copy_context_work_handler_workarea *workarea;
2772 	struct mqd_manager *mqd_mgr;
2773 	struct queue *q;
2774 	struct mm_struct *mm;
2775 	struct kfd_process *p;
2776 	uint32_t tmp_ctl_stack_used_size, tmp_save_area_used_size;
2777 	int i;
2778 
2779 	workarea = container_of(work,
2780 			struct copy_context_work_handler_workarea,
2781 			copy_context_work);
2782 
2783 	p = workarea->p;
2784 	mm = get_task_mm(p->lead_thread);
2785 
2786 	if (!mm)
2787 		return;
2788 
2789 	kthread_use_mm(mm);
2790 	for (i = 0; i < p->n_pdds; i++) {
2791 		struct kfd_process_device *pdd = p->pdds[i];
2792 		struct device_queue_manager *dqm = pdd->dev->dqm;
2793 		struct qcm_process_device *qpd = &pdd->qpd;
2794 
2795 		list_for_each_entry(q, &qpd->queues_list, list) {
2796 			mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_CP];
2797 
2798 			/* We ignore the return value from get_wave_state
2799 			 * because
2800 			 * i) right now, it always returns 0, and
2801 			 * ii) if we hit an error, we would continue to the
2802 			 *      next queue anyway.
2803 			 */
2804 			mqd_mgr->get_wave_state(mqd_mgr,
2805 					q->mqd,
2806 					&q->properties,
2807 					(void __user *)	q->properties.ctx_save_restore_area_address,
2808 					&tmp_ctl_stack_used_size,
2809 					&tmp_save_area_used_size);
2810 		}
2811 	}
2812 	kthread_unuse_mm(mm);
2813 	mmput(mm);
2814 }
2815 
2816 static uint32_t *get_queue_ids(uint32_t num_queues, uint32_t *usr_queue_id_array)
2817 {
2818 	size_t array_size = num_queues * sizeof(uint32_t);
2819 
2820 	if (!usr_queue_id_array)
2821 		return NULL;
2822 
2823 	return memdup_user(usr_queue_id_array, array_size);
2824 }
2825 
2826 int resume_queues(struct kfd_process *p,
2827 		uint32_t num_queues,
2828 		uint32_t *usr_queue_id_array)
2829 {
2830 	uint32_t *queue_ids = NULL;
2831 	int total_resumed = 0;
2832 	int i;
2833 
2834 	if (usr_queue_id_array) {
2835 		queue_ids = get_queue_ids(num_queues, usr_queue_id_array);
2836 
2837 		if (IS_ERR(queue_ids))
2838 			return PTR_ERR(queue_ids);
2839 
2840 		/* mask all queues as invalid.  unmask per successful request */
2841 		q_array_invalidate(num_queues, queue_ids);
2842 	}
2843 
2844 	for (i = 0; i < p->n_pdds; i++) {
2845 		struct kfd_process_device *pdd = p->pdds[i];
2846 		struct device_queue_manager *dqm = pdd->dev->dqm;
2847 		struct qcm_process_device *qpd = &pdd->qpd;
2848 		struct queue *q;
2849 		int r, per_device_resumed = 0;
2850 
2851 		dqm_lock(dqm);
2852 
2853 		/* unmask queues that resume or already resumed as valid */
2854 		list_for_each_entry(q, &qpd->queues_list, list) {
2855 			int q_idx = QUEUE_NOT_FOUND;
2856 
2857 			if (queue_ids)
2858 				q_idx = q_array_get_index(
2859 						q->properties.queue_id,
2860 						num_queues,
2861 						queue_ids);
2862 
2863 			if (!queue_ids || q_idx != QUEUE_NOT_FOUND) {
2864 				int err = resume_single_queue(dqm, &pdd->qpd, q);
2865 
2866 				if (queue_ids) {
2867 					if (!err) {
2868 						queue_ids[q_idx] &=
2869 							~KFD_DBG_QUEUE_INVALID_MASK;
2870 					} else {
2871 						queue_ids[q_idx] |=
2872 							KFD_DBG_QUEUE_ERROR_MASK;
2873 						break;
2874 					}
2875 				}
2876 
2877 				if (dqm->dev->kfd->shared_resources.enable_mes) {
2878 					wake_up_all(&dqm->destroy_wait);
2879 					if (!err)
2880 						total_resumed++;
2881 				} else {
2882 					per_device_resumed++;
2883 				}
2884 			}
2885 		}
2886 
2887 		if (!per_device_resumed) {
2888 			dqm_unlock(dqm);
2889 			continue;
2890 		}
2891 
2892 		r = execute_queues_cpsch(dqm,
2893 					KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES,
2894 					0,
2895 					USE_DEFAULT_GRACE_PERIOD);
2896 		if (r) {
2897 			pr_err("Failed to resume process queues\n");
2898 			if (queue_ids) {
2899 				list_for_each_entry(q, &qpd->queues_list, list) {
2900 					int q_idx = q_array_get_index(
2901 							q->properties.queue_id,
2902 							num_queues,
2903 							queue_ids);
2904 
2905 					/* mask queue as error on resume fail */
2906 					if (q_idx != QUEUE_NOT_FOUND)
2907 						queue_ids[q_idx] |=
2908 							KFD_DBG_QUEUE_ERROR_MASK;
2909 				}
2910 			}
2911 		} else {
2912 			wake_up_all(&dqm->destroy_wait);
2913 			total_resumed += per_device_resumed;
2914 		}
2915 
2916 		dqm_unlock(dqm);
2917 	}
2918 
2919 	if (queue_ids) {
2920 		if (copy_to_user((void __user *)usr_queue_id_array, queue_ids,
2921 				num_queues * sizeof(uint32_t)))
2922 			pr_err("copy_to_user failed on queue resume\n");
2923 
2924 		kfree(queue_ids);
2925 	}
2926 
2927 	return total_resumed;
2928 }
2929 
2930 int suspend_queues(struct kfd_process *p,
2931 			uint32_t num_queues,
2932 			uint32_t grace_period,
2933 			uint64_t exception_clear_mask,
2934 			uint32_t *usr_queue_id_array)
2935 {
2936 	uint32_t *queue_ids = get_queue_ids(num_queues, usr_queue_id_array);
2937 	int total_suspended = 0;
2938 	int i;
2939 
2940 	if (IS_ERR(queue_ids))
2941 		return PTR_ERR(queue_ids);
2942 
2943 	/* mask all queues as invalid.  umask on successful request */
2944 	q_array_invalidate(num_queues, queue_ids);
2945 
2946 	for (i = 0; i < p->n_pdds; i++) {
2947 		struct kfd_process_device *pdd = p->pdds[i];
2948 		struct device_queue_manager *dqm = pdd->dev->dqm;
2949 		struct qcm_process_device *qpd = &pdd->qpd;
2950 		struct queue *q;
2951 		int r, per_device_suspended = 0;
2952 
2953 		mutex_lock(&p->event_mutex);
2954 		dqm_lock(dqm);
2955 
2956 		/* unmask queues that suspend or already suspended */
2957 		list_for_each_entry(q, &qpd->queues_list, list) {
2958 			int q_idx = q_array_get_index(q->properties.queue_id,
2959 							num_queues,
2960 							queue_ids);
2961 
2962 			if (q_idx != QUEUE_NOT_FOUND) {
2963 				int err = suspend_single_queue(dqm, pdd, q);
2964 				bool is_mes = dqm->dev->kfd->shared_resources.enable_mes;
2965 
2966 				if (!err) {
2967 					queue_ids[q_idx] &= ~KFD_DBG_QUEUE_INVALID_MASK;
2968 					if (exception_clear_mask && is_mes)
2969 						q->properties.exception_status &=
2970 							~exception_clear_mask;
2971 
2972 					if (is_mes)
2973 						total_suspended++;
2974 					else
2975 						per_device_suspended++;
2976 				} else if (err != -EBUSY) {
2977 					r = err;
2978 					queue_ids[q_idx] |= KFD_DBG_QUEUE_ERROR_MASK;
2979 					break;
2980 				}
2981 			}
2982 		}
2983 
2984 		if (!per_device_suspended) {
2985 			dqm_unlock(dqm);
2986 			mutex_unlock(&p->event_mutex);
2987 			if (total_suspended)
2988 				amdgpu_amdkfd_debug_mem_fence(dqm->dev->adev);
2989 			continue;
2990 		}
2991 
2992 		r = execute_queues_cpsch(dqm,
2993 			KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0,
2994 			grace_period);
2995 
2996 		if (r)
2997 			pr_err("Failed to suspend process queues.\n");
2998 		else
2999 			total_suspended += per_device_suspended;
3000 
3001 		list_for_each_entry(q, &qpd->queues_list, list) {
3002 			int q_idx = q_array_get_index(q->properties.queue_id,
3003 						num_queues, queue_ids);
3004 
3005 			if (q_idx == QUEUE_NOT_FOUND)
3006 				continue;
3007 
3008 			/* mask queue as error on suspend fail */
3009 			if (r)
3010 				queue_ids[q_idx] |= KFD_DBG_QUEUE_ERROR_MASK;
3011 			else if (exception_clear_mask)
3012 				q->properties.exception_status &=
3013 							~exception_clear_mask;
3014 		}
3015 
3016 		dqm_unlock(dqm);
3017 		mutex_unlock(&p->event_mutex);
3018 		amdgpu_device_flush_hdp(dqm->dev->adev, NULL);
3019 	}
3020 
3021 	if (total_suspended) {
3022 		struct copy_context_work_handler_workarea copy_context_worker;
3023 
3024 		INIT_WORK_ONSTACK(
3025 				&copy_context_worker.copy_context_work,
3026 				copy_context_work_handler);
3027 
3028 		copy_context_worker.p = p;
3029 
3030 		schedule_work(&copy_context_worker.copy_context_work);
3031 
3032 
3033 		flush_work(&copy_context_worker.copy_context_work);
3034 		destroy_work_on_stack(&copy_context_worker.copy_context_work);
3035 	}
3036 
3037 	if (copy_to_user((void __user *)usr_queue_id_array, queue_ids,
3038 			num_queues * sizeof(uint32_t)))
3039 		pr_err("copy_to_user failed on queue suspend\n");
3040 
3041 	kfree(queue_ids);
3042 
3043 	return total_suspended;
3044 }
3045 
3046 static uint32_t set_queue_type_for_user(struct queue_properties *q_props)
3047 {
3048 	switch (q_props->type) {
3049 	case KFD_QUEUE_TYPE_COMPUTE:
3050 		return q_props->format == KFD_QUEUE_FORMAT_PM4
3051 					? KFD_IOC_QUEUE_TYPE_COMPUTE
3052 					: KFD_IOC_QUEUE_TYPE_COMPUTE_AQL;
3053 	case KFD_QUEUE_TYPE_SDMA:
3054 		return KFD_IOC_QUEUE_TYPE_SDMA;
3055 	case KFD_QUEUE_TYPE_SDMA_XGMI:
3056 		return KFD_IOC_QUEUE_TYPE_SDMA_XGMI;
3057 	default:
3058 		WARN_ONCE(true, "queue type not recognized!");
3059 		return 0xffffffff;
3060 	};
3061 }
3062 
3063 void set_queue_snapshot_entry(struct queue *q,
3064 			      uint64_t exception_clear_mask,
3065 			      struct kfd_queue_snapshot_entry *qss_entry)
3066 {
3067 	qss_entry->ring_base_address = q->properties.queue_address;
3068 	qss_entry->write_pointer_address = (uint64_t)q->properties.write_ptr;
3069 	qss_entry->read_pointer_address = (uint64_t)q->properties.read_ptr;
3070 	qss_entry->ctx_save_restore_address =
3071 				q->properties.ctx_save_restore_area_address;
3072 	qss_entry->ctx_save_restore_area_size =
3073 				q->properties.ctx_save_restore_area_size;
3074 	qss_entry->exception_status = q->properties.exception_status;
3075 	qss_entry->queue_id = q->properties.queue_id;
3076 	qss_entry->gpu_id = q->device->id;
3077 	qss_entry->ring_size = (uint32_t)q->properties.queue_size;
3078 	qss_entry->queue_type = set_queue_type_for_user(&q->properties);
3079 	q->properties.exception_status &= ~exception_clear_mask;
3080 }
3081 
3082 int debug_lock_and_unmap(struct device_queue_manager *dqm)
3083 {
3084 	int r;
3085 
3086 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3087 		pr_err("Unsupported on sched_policy: %i\n", dqm->sched_policy);
3088 		return -EINVAL;
3089 	}
3090 
3091 	if (!kfd_dbg_is_per_vmid_supported(dqm->dev))
3092 		return 0;
3093 
3094 	dqm_lock(dqm);
3095 
3096 	r = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0, 0, false);
3097 	if (r)
3098 		dqm_unlock(dqm);
3099 
3100 	return r;
3101 }
3102 
3103 int debug_map_and_unlock(struct device_queue_manager *dqm)
3104 {
3105 	int r;
3106 
3107 	if (dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) {
3108 		pr_err("Unsupported on sched_policy: %i\n", dqm->sched_policy);
3109 		return -EINVAL;
3110 	}
3111 
3112 	if (!kfd_dbg_is_per_vmid_supported(dqm->dev))
3113 		return 0;
3114 
3115 	r = map_queues_cpsch(dqm);
3116 
3117 	dqm_unlock(dqm);
3118 
3119 	return r;
3120 }
3121 
3122 int debug_refresh_runlist(struct device_queue_manager *dqm)
3123 {
3124 	int r = debug_lock_and_unmap(dqm);
3125 
3126 	if (r)
3127 		return r;
3128 
3129 	return debug_map_and_unlock(dqm);
3130 }
3131 
3132 #if defined(CONFIG_DEBUG_FS)
3133 
3134 static void seq_reg_dump(struct seq_file *m,
3135 			 uint32_t (*dump)[2], uint32_t n_regs)
3136 {
3137 	uint32_t i, count;
3138 
3139 	for (i = 0, count = 0; i < n_regs; i++) {
3140 		if (count == 0 ||
3141 		    dump[i-1][0] + sizeof(uint32_t) != dump[i][0]) {
3142 			seq_printf(m, "%s    %08x: %08x",
3143 				   i ? "\n" : "",
3144 				   dump[i][0], dump[i][1]);
3145 			count = 7;
3146 		} else {
3147 			seq_printf(m, " %08x", dump[i][1]);
3148 			count--;
3149 		}
3150 	}
3151 
3152 	seq_puts(m, "\n");
3153 }
3154 
3155 int dqm_debugfs_hqds(struct seq_file *m, void *data)
3156 {
3157 	struct device_queue_manager *dqm = data;
3158 	uint32_t xcc_mask = dqm->dev->xcc_mask;
3159 	uint32_t (*dump)[2], n_regs;
3160 	int pipe, queue;
3161 	int r = 0, xcc_id;
3162 	uint32_t sdma_engine_start;
3163 
3164 	if (!dqm->sched_running) {
3165 		seq_puts(m, " Device is stopped\n");
3166 		return 0;
3167 	}
3168 
3169 	for_each_inst(xcc_id, xcc_mask) {
3170 		r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->adev,
3171 						KFD_CIK_HIQ_PIPE,
3172 						KFD_CIK_HIQ_QUEUE, &dump,
3173 						&n_regs, xcc_id);
3174 		if (!r) {
3175 			seq_printf(
3176 				m,
3177 				"   Inst %d, HIQ on MEC %d Pipe %d Queue %d\n",
3178 				xcc_id,
3179 				KFD_CIK_HIQ_PIPE / get_pipes_per_mec(dqm) + 1,
3180 				KFD_CIK_HIQ_PIPE % get_pipes_per_mec(dqm),
3181 				KFD_CIK_HIQ_QUEUE);
3182 			seq_reg_dump(m, dump, n_regs);
3183 
3184 			kfree(dump);
3185 		}
3186 
3187 		for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
3188 			int pipe_offset = pipe * get_queues_per_pipe(dqm);
3189 
3190 			for (queue = 0; queue < get_queues_per_pipe(dqm); queue++) {
3191 				if (!test_bit(pipe_offset + queue,
3192 				      dqm->dev->kfd->shared_resources.cp_queue_bitmap))
3193 					continue;
3194 
3195 				r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->adev,
3196 								pipe, queue,
3197 								&dump, &n_regs,
3198 								xcc_id);
3199 				if (r)
3200 					break;
3201 
3202 				seq_printf(m,
3203 					   " Inst %d,  CP Pipe %d, Queue %d\n",
3204 					   xcc_id, pipe, queue);
3205 				seq_reg_dump(m, dump, n_regs);
3206 
3207 				kfree(dump);
3208 			}
3209 		}
3210 	}
3211 
3212 	sdma_engine_start = dqm->dev->node_id * get_num_all_sdma_engines(dqm);
3213 	for (pipe = sdma_engine_start;
3214 	     pipe < (sdma_engine_start + get_num_all_sdma_engines(dqm));
3215 	     pipe++) {
3216 		for (queue = 0;
3217 		     queue < dqm->dev->kfd->device_info.num_sdma_queues_per_engine;
3218 		     queue++) {
3219 			r = dqm->dev->kfd2kgd->hqd_sdma_dump(
3220 				dqm->dev->adev, pipe, queue, &dump, &n_regs);
3221 			if (r)
3222 				break;
3223 
3224 			seq_printf(m, "  SDMA Engine %d, RLC %d\n",
3225 				  pipe, queue);
3226 			seq_reg_dump(m, dump, n_regs);
3227 
3228 			kfree(dump);
3229 		}
3230 	}
3231 
3232 	return r;
3233 }
3234 
3235 int dqm_debugfs_hang_hws(struct device_queue_manager *dqm)
3236 {
3237 	int r = 0;
3238 
3239 	dqm_lock(dqm);
3240 	r = pm_debugfs_hang_hws(&dqm->packet_mgr);
3241 	if (r) {
3242 		dqm_unlock(dqm);
3243 		return r;
3244 	}
3245 	dqm->active_runlist = true;
3246 	r = execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES,
3247 				0, USE_DEFAULT_GRACE_PERIOD);
3248 	dqm_unlock(dqm);
3249 
3250 	return r;
3251 }
3252 
3253 #endif
3254