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