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