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 
40 /* Size of the per-pipe EOP queue */
41 #define CIK_HPD_EOP_BYTES_LOG2 11
42 #define CIK_HPD_EOP_BYTES (1U << CIK_HPD_EOP_BYTES_LOG2)
43 
44 static int set_pasid_vmid_mapping(struct device_queue_manager *dqm,
45 				  u32 pasid, unsigned int vmid);
46 
47 static int execute_queues_cpsch(struct device_queue_manager *dqm,
48 				enum kfd_unmap_queues_filter filter,
49 				uint32_t filter_param);
50 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
51 				enum kfd_unmap_queues_filter filter,
52 				uint32_t filter_param, bool reset);
53 
54 static int map_queues_cpsch(struct device_queue_manager *dqm);
55 
56 static void deallocate_sdma_queue(struct device_queue_manager *dqm,
57 				struct queue *q);
58 
59 static inline void deallocate_hqd(struct device_queue_manager *dqm,
60 				struct queue *q);
61 static int allocate_hqd(struct device_queue_manager *dqm, struct queue *q);
62 static int allocate_sdma_queue(struct device_queue_manager *dqm,
63 				struct queue *q, const uint32_t *restore_sdma_id);
64 static void kfd_process_hw_exception(struct work_struct *work);
65 
66 static inline
67 enum KFD_MQD_TYPE get_mqd_type_from_queue_type(enum kfd_queue_type type)
68 {
69 	if (type == KFD_QUEUE_TYPE_SDMA || type == KFD_QUEUE_TYPE_SDMA_XGMI)
70 		return KFD_MQD_TYPE_SDMA;
71 	return KFD_MQD_TYPE_CP;
72 }
73 
74 static bool is_pipe_enabled(struct device_queue_manager *dqm, int mec, int pipe)
75 {
76 	int i;
77 	int pipe_offset = (mec * dqm->dev->shared_resources.num_pipe_per_mec
78 		+ pipe) * dqm->dev->shared_resources.num_queue_per_pipe;
79 
80 	/* queue is available for KFD usage if bit is 1 */
81 	for (i = 0; i <  dqm->dev->shared_resources.num_queue_per_pipe; ++i)
82 		if (test_bit(pipe_offset + i,
83 			      dqm->dev->shared_resources.cp_queue_bitmap))
84 			return true;
85 	return false;
86 }
87 
88 unsigned int get_cp_queues_num(struct device_queue_manager *dqm)
89 {
90 	return bitmap_weight(dqm->dev->shared_resources.cp_queue_bitmap,
91 				KGD_MAX_QUEUES);
92 }
93 
94 unsigned int get_queues_per_pipe(struct device_queue_manager *dqm)
95 {
96 	return dqm->dev->shared_resources.num_queue_per_pipe;
97 }
98 
99 unsigned int get_pipes_per_mec(struct device_queue_manager *dqm)
100 {
101 	return dqm->dev->shared_resources.num_pipe_per_mec;
102 }
103 
104 static unsigned int get_num_all_sdma_engines(struct device_queue_manager *dqm)
105 {
106 	return kfd_get_num_sdma_engines(dqm->dev) +
107 		kfd_get_num_xgmi_sdma_engines(dqm->dev);
108 }
109 
110 unsigned int get_num_sdma_queues(struct device_queue_manager *dqm)
111 {
112 	return kfd_get_num_sdma_engines(dqm->dev) *
113 		dqm->dev->device_info.num_sdma_queues_per_engine;
114 }
115 
116 unsigned int get_num_xgmi_sdma_queues(struct device_queue_manager *dqm)
117 {
118 	return kfd_get_num_xgmi_sdma_engines(dqm->dev) *
119 		dqm->dev->device_info.num_sdma_queues_per_engine;
120 }
121 
122 static inline uint64_t get_reserved_sdma_queues_bitmap(struct device_queue_manager *dqm)
123 {
124 	return dqm->dev->device_info.reserved_sdma_queues_bitmap;
125 }
126 
127 void program_sh_mem_settings(struct device_queue_manager *dqm,
128 					struct qcm_process_device *qpd)
129 {
130 	return dqm->dev->kfd2kgd->program_sh_mem_settings(
131 						dqm->dev->adev, qpd->vmid,
132 						qpd->sh_mem_config,
133 						qpd->sh_mem_ape1_base,
134 						qpd->sh_mem_ape1_limit,
135 						qpd->sh_mem_bases);
136 }
137 
138 static void kfd_hws_hang(struct device_queue_manager *dqm)
139 {
140 	/*
141 	 * Issue a GPU reset if HWS is unresponsive
142 	 */
143 	dqm->is_hws_hang = true;
144 
145 	/* It's possible we're detecting a HWS hang in the
146 	 * middle of a GPU reset. No need to schedule another
147 	 * reset in this case.
148 	 */
149 	if (!dqm->is_resetting)
150 		schedule_work(&dqm->hw_exception_work);
151 }
152 
153 static int convert_to_mes_queue_type(int queue_type)
154 {
155 	int mes_queue_type;
156 
157 	switch (queue_type) {
158 	case KFD_QUEUE_TYPE_COMPUTE:
159 		mes_queue_type = MES_QUEUE_TYPE_COMPUTE;
160 		break;
161 	case KFD_QUEUE_TYPE_SDMA:
162 		mes_queue_type = MES_QUEUE_TYPE_SDMA;
163 		break;
164 	default:
165 		WARN(1, "Invalid queue type %d", queue_type);
166 		mes_queue_type = -EINVAL;
167 		break;
168 	}
169 
170 	return mes_queue_type;
171 }
172 
173 static int add_queue_mes(struct device_queue_manager *dqm, struct queue *q,
174 			 struct qcm_process_device *qpd)
175 {
176 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
177 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
178 	struct mes_add_queue_input queue_input;
179 	int r, queue_type;
180 	uint64_t wptr_addr_off;
181 
182 	if (dqm->is_hws_hang)
183 		return -EIO;
184 
185 	memset(&queue_input, 0x0, sizeof(struct mes_add_queue_input));
186 	queue_input.process_id = qpd->pqm->process->pasid;
187 	queue_input.page_table_base_addr =  qpd->page_table_base;
188 	queue_input.process_va_start = 0;
189 	queue_input.process_va_end = adev->vm_manager.max_pfn - 1;
190 	/* MES unit for quantum is 100ns */
191 	queue_input.process_quantum = KFD_MES_PROCESS_QUANTUM;  /* Equivalent to 10ms. */
192 	queue_input.process_context_addr = pdd->proc_ctx_gpu_addr;
193 	queue_input.gang_quantum = KFD_MES_GANG_QUANTUM; /* Equivalent to 1ms */
194 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
195 	queue_input.inprocess_gang_priority = q->properties.priority;
196 	queue_input.gang_global_priority_level =
197 					AMDGPU_MES_PRIORITY_LEVEL_NORMAL;
198 	queue_input.doorbell_offset = q->properties.doorbell_off;
199 	queue_input.mqd_addr = q->gart_mqd_addr;
200 	queue_input.wptr_addr = (uint64_t)q->properties.write_ptr;
201 
202 	if (q->wptr_bo) {
203 		wptr_addr_off = (uint64_t)q->properties.write_ptr - (uint64_t)q->wptr_bo->kfd_bo->va;
204 		queue_input.wptr_mc_addr = ((uint64_t)q->wptr_bo->tbo.resource->start << PAGE_SHIFT) + wptr_addr_off;
205 	}
206 
207 	queue_input.is_kfd_process = 1;
208 	queue_input.is_aql_queue = (q->properties.format == KFD_QUEUE_FORMAT_AQL);
209 	queue_input.queue_size = q->properties.queue_size >> 2;
210 
211 	queue_input.paging = false;
212 	queue_input.tba_addr = qpd->tba_addr;
213 	queue_input.tma_addr = qpd->tma_addr;
214 
215 	queue_type = convert_to_mes_queue_type(q->properties.type);
216 	if (queue_type < 0) {
217 		pr_err("Queue type not supported with MES, queue:%d\n",
218 				q->properties.type);
219 		return -EINVAL;
220 	}
221 	queue_input.queue_type = (uint32_t)queue_type;
222 
223 	if (q->gws) {
224 		queue_input.gws_base = 0;
225 		queue_input.gws_size = qpd->num_gws;
226 	}
227 
228 	amdgpu_mes_lock(&adev->mes);
229 	r = adev->mes.funcs->add_hw_queue(&adev->mes, &queue_input);
230 	amdgpu_mes_unlock(&adev->mes);
231 	if (r) {
232 		pr_err("failed to add hardware queue to MES, doorbell=0x%x\n",
233 			q->properties.doorbell_off);
234 		pr_err("MES might be in unrecoverable state, issue a GPU reset\n");
235 		kfd_hws_hang(dqm);
236 }
237 
238 	return r;
239 }
240 
241 static int remove_queue_mes(struct device_queue_manager *dqm, struct queue *q,
242 			struct qcm_process_device *qpd)
243 {
244 	struct amdgpu_device *adev = (struct amdgpu_device *)dqm->dev->adev;
245 	int r;
246 	struct mes_remove_queue_input queue_input;
247 
248 	if (dqm->is_hws_hang)
249 		return -EIO;
250 
251 	memset(&queue_input, 0x0, sizeof(struct mes_remove_queue_input));
252 	queue_input.doorbell_offset = q->properties.doorbell_off;
253 	queue_input.gang_context_addr = q->gang_ctx_gpu_addr;
254 
255 	amdgpu_mes_lock(&adev->mes);
256 	r = adev->mes.funcs->remove_hw_queue(&adev->mes, &queue_input);
257 	amdgpu_mes_unlock(&adev->mes);
258 
259 	if (r) {
260 		pr_err("failed to remove hardware queue from MES, doorbell=0x%x\n",
261 			q->properties.doorbell_off);
262 		pr_err("MES might be in unrecoverable state, issue a GPU reset\n");
263 		kfd_hws_hang(dqm);
264 	}
265 
266 	return r;
267 }
268 
269 static int remove_all_queues_mes(struct device_queue_manager *dqm)
270 {
271 	struct device_process_node *cur;
272 	struct qcm_process_device *qpd;
273 	struct queue *q;
274 	int retval = 0;
275 
276 	list_for_each_entry(cur, &dqm->queues, list) {
277 		qpd = cur->qpd;
278 		list_for_each_entry(q, &qpd->queues_list, list) {
279 			if (q->properties.is_active) {
280 				retval = remove_queue_mes(dqm, q, qpd);
281 				if (retval) {
282 					pr_err("%s: Failed to remove queue %d for dev %d",
283 						__func__,
284 						q->properties.queue_id,
285 						dqm->dev->id);
286 					return retval;
287 				}
288 			}
289 		}
290 	}
291 
292 	return retval;
293 }
294 
295 static void increment_queue_count(struct device_queue_manager *dqm,
296 				  struct qcm_process_device *qpd,
297 				  struct queue *q)
298 {
299 	dqm->active_queue_count++;
300 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
301 	    q->properties.type == KFD_QUEUE_TYPE_DIQ)
302 		dqm->active_cp_queue_count++;
303 
304 	if (q->properties.is_gws) {
305 		dqm->gws_queue_count++;
306 		qpd->mapped_gws_queue = true;
307 	}
308 }
309 
310 static void decrement_queue_count(struct device_queue_manager *dqm,
311 				  struct qcm_process_device *qpd,
312 				  struct queue *q)
313 {
314 	dqm->active_queue_count--;
315 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
316 	    q->properties.type == KFD_QUEUE_TYPE_DIQ)
317 		dqm->active_cp_queue_count--;
318 
319 	if (q->properties.is_gws) {
320 		dqm->gws_queue_count--;
321 		qpd->mapped_gws_queue = false;
322 	}
323 }
324 
325 /*
326  * Allocate a doorbell ID to this queue.
327  * If doorbell_id is passed in, make sure requested ID is valid then allocate it.
328  */
329 static int allocate_doorbell(struct qcm_process_device *qpd,
330 			     struct queue *q,
331 			     uint32_t const *restore_id)
332 {
333 	struct kfd_dev *dev = qpd->dqm->dev;
334 
335 	if (!KFD_IS_SOC15(dev)) {
336 		/* On pre-SOC15 chips we need to use the queue ID to
337 		 * preserve the user mode ABI.
338 		 */
339 
340 		if (restore_id && *restore_id != q->properties.queue_id)
341 			return -EINVAL;
342 
343 		q->doorbell_id = q->properties.queue_id;
344 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
345 			q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
346 		/* For SDMA queues on SOC15 with 8-byte doorbell, use static
347 		 * doorbell assignments based on the engine and queue id.
348 		 * The doobell index distance between RLC (2*i) and (2*i+1)
349 		 * for a SDMA engine is 512.
350 		 */
351 
352 		uint32_t *idx_offset = dev->shared_resources.sdma_doorbell_idx;
353 		uint32_t valid_id = idx_offset[q->properties.sdma_engine_id]
354 						+ (q->properties.sdma_queue_id & 1)
355 						* KFD_QUEUE_DOORBELL_MIRROR_OFFSET
356 						+ (q->properties.sdma_queue_id >> 1);
357 
358 		if (restore_id && *restore_id != valid_id)
359 			return -EINVAL;
360 		q->doorbell_id = valid_id;
361 	} else {
362 		/* For CP queues on SOC15 */
363 		if (restore_id) {
364 			/* make sure that ID is free  */
365 			if (__test_and_set_bit(*restore_id, qpd->doorbell_bitmap))
366 				return -EINVAL;
367 
368 			q->doorbell_id = *restore_id;
369 		} else {
370 			/* or reserve a free doorbell ID */
371 			unsigned int found;
372 
373 			found = find_first_zero_bit(qpd->doorbell_bitmap,
374 						KFD_MAX_NUM_OF_QUEUES_PER_PROCESS);
375 			if (found >= KFD_MAX_NUM_OF_QUEUES_PER_PROCESS) {
376 				pr_debug("No doorbells available");
377 				return -EBUSY;
378 			}
379 			set_bit(found, qpd->doorbell_bitmap);
380 			q->doorbell_id = found;
381 		}
382 	}
383 
384 	q->properties.doorbell_off =
385 		kfd_get_doorbell_dw_offset_in_bar(dev, qpd_to_pdd(qpd),
386 					  q->doorbell_id);
387 	return 0;
388 }
389 
390 static void deallocate_doorbell(struct qcm_process_device *qpd,
391 				struct queue *q)
392 {
393 	unsigned int old;
394 	struct kfd_dev *dev = qpd->dqm->dev;
395 
396 	if (!KFD_IS_SOC15(dev) ||
397 	    q->properties.type == KFD_QUEUE_TYPE_SDMA ||
398 	    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
399 		return;
400 
401 	old = test_and_clear_bit(q->doorbell_id, qpd->doorbell_bitmap);
402 	WARN_ON(!old);
403 }
404 
405 static void program_trap_handler_settings(struct device_queue_manager *dqm,
406 				struct qcm_process_device *qpd)
407 {
408 	if (dqm->dev->kfd2kgd->program_trap_handler_settings)
409 		dqm->dev->kfd2kgd->program_trap_handler_settings(
410 						dqm->dev->adev, qpd->vmid,
411 						qpd->tba_addr, qpd->tma_addr);
412 }
413 
414 static int allocate_vmid(struct device_queue_manager *dqm,
415 			struct qcm_process_device *qpd,
416 			struct queue *q)
417 {
418 	int allocated_vmid = -1, i;
419 
420 	for (i = dqm->dev->vm_info.first_vmid_kfd;
421 			i <= dqm->dev->vm_info.last_vmid_kfd; i++) {
422 		if (!dqm->vmid_pasid[i]) {
423 			allocated_vmid = i;
424 			break;
425 		}
426 	}
427 
428 	if (allocated_vmid < 0) {
429 		pr_err("no more vmid to allocate\n");
430 		return -ENOSPC;
431 	}
432 
433 	pr_debug("vmid allocated: %d\n", allocated_vmid);
434 
435 	dqm->vmid_pasid[allocated_vmid] = q->process->pasid;
436 
437 	set_pasid_vmid_mapping(dqm, q->process->pasid, allocated_vmid);
438 
439 	qpd->vmid = allocated_vmid;
440 	q->properties.vmid = allocated_vmid;
441 
442 	program_sh_mem_settings(dqm, qpd);
443 
444 	if (KFD_IS_SOC15(dqm->dev) && dqm->dev->cwsr_enabled)
445 		program_trap_handler_settings(dqm, qpd);
446 
447 	/* qpd->page_table_base is set earlier when register_process()
448 	 * is called, i.e. when the first queue is created.
449 	 */
450 	dqm->dev->kfd2kgd->set_vm_context_page_table_base(dqm->dev->adev,
451 			qpd->vmid,
452 			qpd->page_table_base);
453 	/* invalidate the VM context after pasid and vmid mapping is set up */
454 	kfd_flush_tlb(qpd_to_pdd(qpd), TLB_FLUSH_LEGACY);
455 
456 	if (dqm->dev->kfd2kgd->set_scratch_backing_va)
457 		dqm->dev->kfd2kgd->set_scratch_backing_va(dqm->dev->adev,
458 				qpd->sh_hidden_private_base, qpd->vmid);
459 
460 	return 0;
461 }
462 
463 static int flush_texture_cache_nocpsch(struct kfd_dev *kdev,
464 				struct qcm_process_device *qpd)
465 {
466 	const struct packet_manager_funcs *pmf = qpd->dqm->packet_mgr.pmf;
467 	int ret;
468 
469 	if (!qpd->ib_kaddr)
470 		return -ENOMEM;
471 
472 	ret = pmf->release_mem(qpd->ib_base, (uint32_t *)qpd->ib_kaddr);
473 	if (ret)
474 		return ret;
475 
476 	return amdgpu_amdkfd_submit_ib(kdev->adev, KGD_ENGINE_MEC1, qpd->vmid,
477 				qpd->ib_base, (uint32_t *)qpd->ib_kaddr,
478 				pmf->release_mem_size / sizeof(uint32_t));
479 }
480 
481 static void deallocate_vmid(struct device_queue_manager *dqm,
482 				struct qcm_process_device *qpd,
483 				struct queue *q)
484 {
485 	/* On GFX v7, CP doesn't flush TC at dequeue */
486 	if (q->device->adev->asic_type == CHIP_HAWAII)
487 		if (flush_texture_cache_nocpsch(q->device, qpd))
488 			pr_err("Failed to flush TC\n");
489 
490 	kfd_flush_tlb(qpd_to_pdd(qpd), TLB_FLUSH_LEGACY);
491 
492 	/* Release the vmid mapping */
493 	set_pasid_vmid_mapping(dqm, 0, qpd->vmid);
494 	dqm->vmid_pasid[qpd->vmid] = 0;
495 
496 	qpd->vmid = 0;
497 	q->properties.vmid = 0;
498 }
499 
500 static int create_queue_nocpsch(struct device_queue_manager *dqm,
501 				struct queue *q,
502 				struct qcm_process_device *qpd,
503 				const struct kfd_criu_queue_priv_data *qd,
504 				const void *restore_mqd, const void *restore_ctl_stack)
505 {
506 	struct mqd_manager *mqd_mgr;
507 	int retval;
508 
509 	dqm_lock(dqm);
510 
511 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
512 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
513 				dqm->total_queue_count);
514 		retval = -EPERM;
515 		goto out_unlock;
516 	}
517 
518 	if (list_empty(&qpd->queues_list)) {
519 		retval = allocate_vmid(dqm, qpd, q);
520 		if (retval)
521 			goto out_unlock;
522 	}
523 	q->properties.vmid = qpd->vmid;
524 	/*
525 	 * Eviction state logic: mark all queues as evicted, even ones
526 	 * not currently active. Restoring inactive queues later only
527 	 * updates the is_evicted flag but is a no-op otherwise.
528 	 */
529 	q->properties.is_evicted = !!qpd->evicted;
530 
531 	q->properties.tba_addr = qpd->tba_addr;
532 	q->properties.tma_addr = qpd->tma_addr;
533 
534 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
535 			q->properties.type)];
536 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE) {
537 		retval = allocate_hqd(dqm, q);
538 		if (retval)
539 			goto deallocate_vmid;
540 		pr_debug("Loading mqd to hqd on pipe %d, queue %d\n",
541 			q->pipe, q->queue);
542 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
543 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
544 		retval = allocate_sdma_queue(dqm, q, qd ? &qd->sdma_id : NULL);
545 		if (retval)
546 			goto deallocate_vmid;
547 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
548 	}
549 
550 	retval = allocate_doorbell(qpd, q, qd ? &qd->doorbell_id : NULL);
551 	if (retval)
552 		goto out_deallocate_hqd;
553 
554 	/* Temporarily release dqm lock to avoid a circular lock dependency */
555 	dqm_unlock(dqm);
556 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr->dev, &q->properties);
557 	dqm_lock(dqm);
558 
559 	if (!q->mqd_mem_obj) {
560 		retval = -ENOMEM;
561 		goto out_deallocate_doorbell;
562 	}
563 
564 	if (qd)
565 		mqd_mgr->restore_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj, &q->gart_mqd_addr,
566 				     &q->properties, restore_mqd, restore_ctl_stack,
567 				     qd->ctl_stack_size);
568 	else
569 		mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
570 					&q->gart_mqd_addr, &q->properties);
571 
572 	if (q->properties.is_active) {
573 		if (!dqm->sched_running) {
574 			WARN_ONCE(1, "Load non-HWS mqd while stopped\n");
575 			goto add_queue_to_list;
576 		}
577 
578 		if (WARN(q->process->mm != current->mm,
579 					"should only run in user thread"))
580 			retval = -EFAULT;
581 		else
582 			retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd, q->pipe,
583 					q->queue, &q->properties, current->mm);
584 		if (retval)
585 			goto out_free_mqd;
586 	}
587 
588 add_queue_to_list:
589 	list_add(&q->list, &qpd->queues_list);
590 	qpd->queue_count++;
591 	if (q->properties.is_active)
592 		increment_queue_count(dqm, qpd, q);
593 
594 	/*
595 	 * Unconditionally increment this counter, regardless of the queue's
596 	 * type or whether the queue is active.
597 	 */
598 	dqm->total_queue_count++;
599 	pr_debug("Total of %d queues are accountable so far\n",
600 			dqm->total_queue_count);
601 	goto out_unlock;
602 
603 out_free_mqd:
604 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
605 out_deallocate_doorbell:
606 	deallocate_doorbell(qpd, q);
607 out_deallocate_hqd:
608 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE)
609 		deallocate_hqd(dqm, q);
610 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
611 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
612 		deallocate_sdma_queue(dqm, q);
613 deallocate_vmid:
614 	if (list_empty(&qpd->queues_list))
615 		deallocate_vmid(dqm, qpd, q);
616 out_unlock:
617 	dqm_unlock(dqm);
618 	return retval;
619 }
620 
621 static int allocate_hqd(struct device_queue_manager *dqm, struct queue *q)
622 {
623 	bool set;
624 	int pipe, bit, i;
625 
626 	set = false;
627 
628 	for (pipe = dqm->next_pipe_to_allocate, i = 0;
629 			i < get_pipes_per_mec(dqm);
630 			pipe = ((pipe + 1) % get_pipes_per_mec(dqm)), ++i) {
631 
632 		if (!is_pipe_enabled(dqm, 0, pipe))
633 			continue;
634 
635 		if (dqm->allocated_queues[pipe] != 0) {
636 			bit = ffs(dqm->allocated_queues[pipe]) - 1;
637 			dqm->allocated_queues[pipe] &= ~(1 << bit);
638 			q->pipe = pipe;
639 			q->queue = bit;
640 			set = true;
641 			break;
642 		}
643 	}
644 
645 	if (!set)
646 		return -EBUSY;
647 
648 	pr_debug("hqd slot - pipe %d, queue %d\n", q->pipe, q->queue);
649 	/* horizontal hqd allocation */
650 	dqm->next_pipe_to_allocate = (pipe + 1) % get_pipes_per_mec(dqm);
651 
652 	return 0;
653 }
654 
655 static inline void deallocate_hqd(struct device_queue_manager *dqm,
656 				struct queue *q)
657 {
658 	dqm->allocated_queues[q->pipe] |= (1 << q->queue);
659 }
660 
661 #define SQ_IND_CMD_CMD_KILL		0x00000003
662 #define SQ_IND_CMD_MODE_BROADCAST	0x00000001
663 
664 static int dbgdev_wave_reset_wavefronts(struct kfd_dev *dev, struct kfd_process *p)
665 {
666 	int status = 0;
667 	unsigned int vmid;
668 	uint16_t queried_pasid;
669 	union SQ_CMD_BITS reg_sq_cmd;
670 	union GRBM_GFX_INDEX_BITS reg_gfx_index;
671 	struct kfd_process_device *pdd;
672 	int first_vmid_to_scan = dev->vm_info.first_vmid_kfd;
673 	int last_vmid_to_scan = dev->vm_info.last_vmid_kfd;
674 
675 	reg_sq_cmd.u32All = 0;
676 	reg_gfx_index.u32All = 0;
677 
678 	pr_debug("Killing all process wavefronts\n");
679 
680 	if (!dev->kfd2kgd->get_atc_vmid_pasid_mapping_info) {
681 		pr_err("no vmid pasid mapping supported \n");
682 		return -EOPNOTSUPP;
683 	}
684 
685 	/* Scan all registers in the range ATC_VMID8_PASID_MAPPING ..
686 	 * ATC_VMID15_PASID_MAPPING
687 	 * to check which VMID the current process is mapped to.
688 	 */
689 
690 	for (vmid = first_vmid_to_scan; vmid <= last_vmid_to_scan; vmid++) {
691 		status = dev->kfd2kgd->get_atc_vmid_pasid_mapping_info
692 				(dev->adev, vmid, &queried_pasid);
693 
694 		if (status && queried_pasid == p->pasid) {
695 			pr_debug("Killing wave fronts of vmid %d and pasid 0x%x\n",
696 					vmid, p->pasid);
697 			break;
698 		}
699 	}
700 
701 	if (vmid > last_vmid_to_scan) {
702 		pr_err("Didn't find vmid for pasid 0x%x\n", p->pasid);
703 		return -EFAULT;
704 	}
705 
706 	/* taking the VMID for that process on the safe way using PDD */
707 	pdd = kfd_get_process_device_data(dev, p);
708 	if (!pdd)
709 		return -EFAULT;
710 
711 	reg_gfx_index.bits.sh_broadcast_writes = 1;
712 	reg_gfx_index.bits.se_broadcast_writes = 1;
713 	reg_gfx_index.bits.instance_broadcast_writes = 1;
714 	reg_sq_cmd.bits.mode = SQ_IND_CMD_MODE_BROADCAST;
715 	reg_sq_cmd.bits.cmd = SQ_IND_CMD_CMD_KILL;
716 	reg_sq_cmd.bits.vm_id = vmid;
717 
718 	dev->kfd2kgd->wave_control_execute(dev->adev,
719 					reg_gfx_index.u32All,
720 					reg_sq_cmd.u32All);
721 
722 	return 0;
723 }
724 
725 /* Access to DQM has to be locked before calling destroy_queue_nocpsch_locked
726  * to avoid asynchronized access
727  */
728 static int destroy_queue_nocpsch_locked(struct device_queue_manager *dqm,
729 				struct qcm_process_device *qpd,
730 				struct queue *q)
731 {
732 	int retval;
733 	struct mqd_manager *mqd_mgr;
734 
735 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
736 			q->properties.type)];
737 
738 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE)
739 		deallocate_hqd(dqm, q);
740 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
741 		deallocate_sdma_queue(dqm, q);
742 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
743 		deallocate_sdma_queue(dqm, q);
744 	else {
745 		pr_debug("q->properties.type %d is invalid\n",
746 				q->properties.type);
747 		return -EINVAL;
748 	}
749 	dqm->total_queue_count--;
750 
751 	deallocate_doorbell(qpd, q);
752 
753 	if (!dqm->sched_running) {
754 		WARN_ONCE(1, "Destroy non-HWS queue while stopped\n");
755 		return 0;
756 	}
757 
758 	retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
759 				KFD_PREEMPT_TYPE_WAVEFRONT_RESET,
760 				KFD_UNMAP_LATENCY_MS,
761 				q->pipe, q->queue);
762 	if (retval == -ETIME)
763 		qpd->reset_wavefronts = true;
764 
765 	list_del(&q->list);
766 	if (list_empty(&qpd->queues_list)) {
767 		if (qpd->reset_wavefronts) {
768 			pr_warn("Resetting wave fronts (nocpsch) on dev %p\n",
769 					dqm->dev);
770 			/* dbgdev_wave_reset_wavefronts has to be called before
771 			 * deallocate_vmid(), i.e. when vmid is still in use.
772 			 */
773 			dbgdev_wave_reset_wavefronts(dqm->dev,
774 					qpd->pqm->process);
775 			qpd->reset_wavefronts = false;
776 		}
777 
778 		deallocate_vmid(dqm, qpd, q);
779 	}
780 	qpd->queue_count--;
781 	if (q->properties.is_active)
782 		decrement_queue_count(dqm, qpd, q);
783 
784 	return retval;
785 }
786 
787 static int destroy_queue_nocpsch(struct device_queue_manager *dqm,
788 				struct qcm_process_device *qpd,
789 				struct queue *q)
790 {
791 	int retval;
792 	uint64_t sdma_val = 0;
793 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
794 	struct mqd_manager *mqd_mgr =
795 		dqm->mqd_mgrs[get_mqd_type_from_queue_type(q->properties.type)];
796 
797 	/* Get the SDMA queue stats */
798 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
799 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
800 		retval = read_sdma_queue_counter((uint64_t __user *)q->properties.read_ptr,
801 							&sdma_val);
802 		if (retval)
803 			pr_err("Failed to read SDMA queue counter for queue: %d\n",
804 				q->properties.queue_id);
805 	}
806 
807 	dqm_lock(dqm);
808 	retval = destroy_queue_nocpsch_locked(dqm, qpd, q);
809 	if (!retval)
810 		pdd->sdma_past_activity_counter += sdma_val;
811 	dqm_unlock(dqm);
812 
813 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
814 
815 	return retval;
816 }
817 
818 static int update_queue(struct device_queue_manager *dqm, struct queue *q,
819 			struct mqd_update_info *minfo)
820 {
821 	int retval = 0;
822 	struct mqd_manager *mqd_mgr;
823 	struct kfd_process_device *pdd;
824 	bool prev_active = false;
825 
826 	dqm_lock(dqm);
827 	pdd = kfd_get_process_device_data(q->device, q->process);
828 	if (!pdd) {
829 		retval = -ENODEV;
830 		goto out_unlock;
831 	}
832 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
833 			q->properties.type)];
834 
835 	/* Save previous activity state for counters */
836 	prev_active = q->properties.is_active;
837 
838 	/* Make sure the queue is unmapped before updating the MQD */
839 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
840 		if (!dqm->dev->shared_resources.enable_mes)
841 			retval = unmap_queues_cpsch(dqm,
842 						    KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, false);
843 		else if (prev_active)
844 			retval = remove_queue_mes(dqm, q, &pdd->qpd);
845 
846 		if (retval) {
847 			pr_err("unmap queue failed\n");
848 			goto out_unlock;
849 		}
850 	} else if (prev_active &&
851 		   (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
852 		    q->properties.type == KFD_QUEUE_TYPE_SDMA ||
853 		    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
854 
855 		if (!dqm->sched_running) {
856 			WARN_ONCE(1, "Update non-HWS queue while stopped\n");
857 			goto out_unlock;
858 		}
859 
860 		retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
861 				(dqm->dev->cwsr_enabled ?
862 				 KFD_PREEMPT_TYPE_WAVEFRONT_SAVE :
863 				 KFD_PREEMPT_TYPE_WAVEFRONT_DRAIN),
864 				KFD_UNMAP_LATENCY_MS, q->pipe, q->queue);
865 		if (retval) {
866 			pr_err("destroy mqd failed\n");
867 			goto out_unlock;
868 		}
869 	}
870 
871 	mqd_mgr->update_mqd(mqd_mgr, q->mqd, &q->properties, minfo);
872 
873 	/*
874 	 * check active state vs. the previous state and modify
875 	 * counter accordingly. map_queues_cpsch uses the
876 	 * dqm->active_queue_count to determine whether a new runlist must be
877 	 * uploaded.
878 	 */
879 	if (q->properties.is_active && !prev_active) {
880 		increment_queue_count(dqm, &pdd->qpd, q);
881 	} else if (!q->properties.is_active && prev_active) {
882 		decrement_queue_count(dqm, &pdd->qpd, q);
883 	} else if (q->gws && !q->properties.is_gws) {
884 		if (q->properties.is_active) {
885 			dqm->gws_queue_count++;
886 			pdd->qpd.mapped_gws_queue = true;
887 		}
888 		q->properties.is_gws = true;
889 	} else if (!q->gws && q->properties.is_gws) {
890 		if (q->properties.is_active) {
891 			dqm->gws_queue_count--;
892 			pdd->qpd.mapped_gws_queue = false;
893 		}
894 		q->properties.is_gws = false;
895 	}
896 
897 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
898 		if (!dqm->dev->shared_resources.enable_mes)
899 			retval = map_queues_cpsch(dqm);
900 		else if (q->properties.is_active)
901 			retval = add_queue_mes(dqm, q, &pdd->qpd);
902 	} else if (q->properties.is_active &&
903 		 (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
904 		  q->properties.type == KFD_QUEUE_TYPE_SDMA ||
905 		  q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
906 		if (WARN(q->process->mm != current->mm,
907 			 "should only run in user thread"))
908 			retval = -EFAULT;
909 		else
910 			retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd,
911 						   q->pipe, q->queue,
912 						   &q->properties, current->mm);
913 	}
914 
915 out_unlock:
916 	dqm_unlock(dqm);
917 	return retval;
918 }
919 
920 static int evict_process_queues_nocpsch(struct device_queue_manager *dqm,
921 					struct qcm_process_device *qpd)
922 {
923 	struct queue *q;
924 	struct mqd_manager *mqd_mgr;
925 	struct kfd_process_device *pdd;
926 	int retval, ret = 0;
927 
928 	dqm_lock(dqm);
929 	if (qpd->evicted++ > 0) /* already evicted, do nothing */
930 		goto out;
931 
932 	pdd = qpd_to_pdd(qpd);
933 	pr_debug_ratelimited("Evicting PASID 0x%x queues\n",
934 			    pdd->process->pasid);
935 
936 	pdd->last_evict_timestamp = get_jiffies_64();
937 	/* Mark all queues as evicted. Deactivate all active queues on
938 	 * the qpd.
939 	 */
940 	list_for_each_entry(q, &qpd->queues_list, list) {
941 		q->properties.is_evicted = true;
942 		if (!q->properties.is_active)
943 			continue;
944 
945 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
946 				q->properties.type)];
947 		q->properties.is_active = false;
948 		decrement_queue_count(dqm, qpd, q);
949 
950 		if (WARN_ONCE(!dqm->sched_running, "Evict when stopped\n"))
951 			continue;
952 
953 		retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
954 				(dqm->dev->cwsr_enabled ?
955 				 KFD_PREEMPT_TYPE_WAVEFRONT_SAVE :
956 				 KFD_PREEMPT_TYPE_WAVEFRONT_DRAIN),
957 				KFD_UNMAP_LATENCY_MS, q->pipe, q->queue);
958 		if (retval && !ret)
959 			/* Return the first error, but keep going to
960 			 * maintain a consistent eviction state
961 			 */
962 			ret = retval;
963 	}
964 
965 out:
966 	dqm_unlock(dqm);
967 	return ret;
968 }
969 
970 static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
971 				      struct qcm_process_device *qpd)
972 {
973 	struct queue *q;
974 	struct kfd_process_device *pdd;
975 	int retval = 0;
976 
977 	dqm_lock(dqm);
978 	if (qpd->evicted++ > 0) /* already evicted, do nothing */
979 		goto out;
980 
981 	pdd = qpd_to_pdd(qpd);
982 	pr_debug_ratelimited("Evicting PASID 0x%x queues\n",
983 			    pdd->process->pasid);
984 
985 	/* Mark all queues as evicted. Deactivate all active queues on
986 	 * the qpd.
987 	 */
988 	list_for_each_entry(q, &qpd->queues_list, list) {
989 		q->properties.is_evicted = true;
990 		if (!q->properties.is_active)
991 			continue;
992 
993 		q->properties.is_active = false;
994 		decrement_queue_count(dqm, qpd, q);
995 
996 		if (dqm->dev->shared_resources.enable_mes) {
997 			retval = remove_queue_mes(dqm, q, qpd);
998 			if (retval) {
999 				pr_err("Failed to evict queue %d\n",
1000 					q->properties.queue_id);
1001 				goto out;
1002 			}
1003 		}
1004 	}
1005 	pdd->last_evict_timestamp = get_jiffies_64();
1006 	if (!dqm->dev->shared_resources.enable_mes)
1007 		retval = execute_queues_cpsch(dqm,
1008 					      qpd->is_debug ?
1009 					      KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES :
1010 					      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1011 
1012 out:
1013 	dqm_unlock(dqm);
1014 	return retval;
1015 }
1016 
1017 static int restore_process_queues_nocpsch(struct device_queue_manager *dqm,
1018 					  struct qcm_process_device *qpd)
1019 {
1020 	struct mm_struct *mm = NULL;
1021 	struct queue *q;
1022 	struct mqd_manager *mqd_mgr;
1023 	struct kfd_process_device *pdd;
1024 	uint64_t pd_base;
1025 	uint64_t eviction_duration;
1026 	int retval, ret = 0;
1027 
1028 	pdd = qpd_to_pdd(qpd);
1029 	/* Retrieve PD base */
1030 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1031 
1032 	dqm_lock(dqm);
1033 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
1034 		goto out;
1035 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
1036 		qpd->evicted--;
1037 		goto out;
1038 	}
1039 
1040 	pr_debug_ratelimited("Restoring PASID 0x%x queues\n",
1041 			    pdd->process->pasid);
1042 
1043 	/* Update PD Base in QPD */
1044 	qpd->page_table_base = pd_base;
1045 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
1046 
1047 	if (!list_empty(&qpd->queues_list)) {
1048 		dqm->dev->kfd2kgd->set_vm_context_page_table_base(
1049 				dqm->dev->adev,
1050 				qpd->vmid,
1051 				qpd->page_table_base);
1052 		kfd_flush_tlb(pdd, TLB_FLUSH_LEGACY);
1053 	}
1054 
1055 	/* Take a safe reference to the mm_struct, which may otherwise
1056 	 * disappear even while the kfd_process is still referenced.
1057 	 */
1058 	mm = get_task_mm(pdd->process->lead_thread);
1059 	if (!mm) {
1060 		ret = -EFAULT;
1061 		goto out;
1062 	}
1063 
1064 	/* Remove the eviction flags. Activate queues that are not
1065 	 * inactive for other reasons.
1066 	 */
1067 	list_for_each_entry(q, &qpd->queues_list, list) {
1068 		q->properties.is_evicted = false;
1069 		if (!QUEUE_IS_ACTIVE(q->properties))
1070 			continue;
1071 
1072 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1073 				q->properties.type)];
1074 		q->properties.is_active = true;
1075 		increment_queue_count(dqm, qpd, q);
1076 
1077 		if (WARN_ONCE(!dqm->sched_running, "Restore when stopped\n"))
1078 			continue;
1079 
1080 		retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd, q->pipe,
1081 				       q->queue, &q->properties, mm);
1082 		if (retval && !ret)
1083 			/* Return the first error, but keep going to
1084 			 * maintain a consistent eviction state
1085 			 */
1086 			ret = retval;
1087 	}
1088 	qpd->evicted = 0;
1089 	eviction_duration = get_jiffies_64() - pdd->last_evict_timestamp;
1090 	atomic64_add(eviction_duration, &pdd->evict_duration_counter);
1091 out:
1092 	if (mm)
1093 		mmput(mm);
1094 	dqm_unlock(dqm);
1095 	return ret;
1096 }
1097 
1098 static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
1099 					struct qcm_process_device *qpd)
1100 {
1101 	struct queue *q;
1102 	struct kfd_process_device *pdd;
1103 	uint64_t pd_base;
1104 	uint64_t eviction_duration;
1105 	int retval = 0;
1106 
1107 	pdd = qpd_to_pdd(qpd);
1108 	/* Retrieve PD base */
1109 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1110 
1111 	dqm_lock(dqm);
1112 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
1113 		goto out;
1114 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
1115 		qpd->evicted--;
1116 		goto out;
1117 	}
1118 
1119 	pr_debug_ratelimited("Restoring PASID 0x%x queues\n",
1120 			    pdd->process->pasid);
1121 
1122 	/* Update PD Base in QPD */
1123 	qpd->page_table_base = pd_base;
1124 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
1125 
1126 	/* activate all active queues on the qpd */
1127 	list_for_each_entry(q, &qpd->queues_list, list) {
1128 		q->properties.is_evicted = false;
1129 		if (!QUEUE_IS_ACTIVE(q->properties))
1130 			continue;
1131 
1132 		q->properties.is_active = true;
1133 		increment_queue_count(dqm, &pdd->qpd, q);
1134 
1135 		if (dqm->dev->shared_resources.enable_mes) {
1136 			retval = add_queue_mes(dqm, q, qpd);
1137 			if (retval) {
1138 				pr_err("Failed to restore queue %d\n",
1139 					q->properties.queue_id);
1140 				goto out;
1141 			}
1142 		}
1143 	}
1144 	if (!dqm->dev->shared_resources.enable_mes)
1145 		retval = execute_queues_cpsch(dqm,
1146 					      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1147 	qpd->evicted = 0;
1148 	eviction_duration = get_jiffies_64() - pdd->last_evict_timestamp;
1149 	atomic64_add(eviction_duration, &pdd->evict_duration_counter);
1150 out:
1151 	dqm_unlock(dqm);
1152 	return retval;
1153 }
1154 
1155 static int register_process(struct device_queue_manager *dqm,
1156 					struct qcm_process_device *qpd)
1157 {
1158 	struct device_process_node *n;
1159 	struct kfd_process_device *pdd;
1160 	uint64_t pd_base;
1161 	int retval;
1162 
1163 	n = kzalloc(sizeof(*n), GFP_KERNEL);
1164 	if (!n)
1165 		return -ENOMEM;
1166 
1167 	n->qpd = qpd;
1168 
1169 	pdd = qpd_to_pdd(qpd);
1170 	/* Retrieve PD base */
1171 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->drm_priv);
1172 
1173 	dqm_lock(dqm);
1174 	list_add(&n->list, &dqm->queues);
1175 
1176 	/* Update PD Base in QPD */
1177 	qpd->page_table_base = pd_base;
1178 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
1179 
1180 	retval = dqm->asic_ops.update_qpd(dqm, qpd);
1181 
1182 	dqm->processes_count++;
1183 
1184 	dqm_unlock(dqm);
1185 
1186 	/* Outside the DQM lock because under the DQM lock we can't do
1187 	 * reclaim or take other locks that others hold while reclaiming.
1188 	 */
1189 	kfd_inc_compute_active(dqm->dev);
1190 
1191 	return retval;
1192 }
1193 
1194 static int unregister_process(struct device_queue_manager *dqm,
1195 					struct qcm_process_device *qpd)
1196 {
1197 	int retval;
1198 	struct device_process_node *cur, *next;
1199 
1200 	pr_debug("qpd->queues_list is %s\n",
1201 			list_empty(&qpd->queues_list) ? "empty" : "not empty");
1202 
1203 	retval = 0;
1204 	dqm_lock(dqm);
1205 
1206 	list_for_each_entry_safe(cur, next, &dqm->queues, list) {
1207 		if (qpd == cur->qpd) {
1208 			list_del(&cur->list);
1209 			kfree(cur);
1210 			dqm->processes_count--;
1211 			goto out;
1212 		}
1213 	}
1214 	/* qpd not found in dqm list */
1215 	retval = 1;
1216 out:
1217 	dqm_unlock(dqm);
1218 
1219 	/* Outside the DQM lock because under the DQM lock we can't do
1220 	 * reclaim or take other locks that others hold while reclaiming.
1221 	 */
1222 	if (!retval)
1223 		kfd_dec_compute_active(dqm->dev);
1224 
1225 	return retval;
1226 }
1227 
1228 static int
1229 set_pasid_vmid_mapping(struct device_queue_manager *dqm, u32 pasid,
1230 			unsigned int vmid)
1231 {
1232 	return dqm->dev->kfd2kgd->set_pasid_vmid_mapping(
1233 						dqm->dev->adev, pasid, vmid);
1234 }
1235 
1236 static void init_interrupts(struct device_queue_manager *dqm)
1237 {
1238 	unsigned int i;
1239 
1240 	for (i = 0 ; i < get_pipes_per_mec(dqm) ; i++)
1241 		if (is_pipe_enabled(dqm, 0, i))
1242 			dqm->dev->kfd2kgd->init_interrupts(dqm->dev->adev, i);
1243 }
1244 
1245 static int initialize_nocpsch(struct device_queue_manager *dqm)
1246 {
1247 	int pipe, queue;
1248 
1249 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
1250 
1251 	dqm->allocated_queues = kcalloc(get_pipes_per_mec(dqm),
1252 					sizeof(unsigned int), GFP_KERNEL);
1253 	if (!dqm->allocated_queues)
1254 		return -ENOMEM;
1255 
1256 	mutex_init(&dqm->lock_hidden);
1257 	INIT_LIST_HEAD(&dqm->queues);
1258 	dqm->active_queue_count = dqm->next_pipe_to_allocate = 0;
1259 	dqm->active_cp_queue_count = 0;
1260 	dqm->gws_queue_count = 0;
1261 
1262 	for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
1263 		int pipe_offset = pipe * get_queues_per_pipe(dqm);
1264 
1265 		for (queue = 0; queue < get_queues_per_pipe(dqm); queue++)
1266 			if (test_bit(pipe_offset + queue,
1267 				     dqm->dev->shared_resources.cp_queue_bitmap))
1268 				dqm->allocated_queues[pipe] |= 1 << queue;
1269 	}
1270 
1271 	memset(dqm->vmid_pasid, 0, sizeof(dqm->vmid_pasid));
1272 
1273 	dqm->sdma_bitmap = ~0ULL >> (64 - get_num_sdma_queues(dqm));
1274 	dqm->sdma_bitmap &= ~(get_reserved_sdma_queues_bitmap(dqm));
1275 	pr_info("sdma_bitmap: %llx\n", dqm->sdma_bitmap);
1276 
1277 	dqm->xgmi_sdma_bitmap = ~0ULL >> (64 - get_num_xgmi_sdma_queues(dqm));
1278 
1279 	return 0;
1280 }
1281 
1282 static void uninitialize(struct device_queue_manager *dqm)
1283 {
1284 	int i;
1285 
1286 	WARN_ON(dqm->active_queue_count > 0 || dqm->processes_count > 0);
1287 
1288 	kfree(dqm->allocated_queues);
1289 	for (i = 0 ; i < KFD_MQD_TYPE_MAX ; i++)
1290 		kfree(dqm->mqd_mgrs[i]);
1291 	mutex_destroy(&dqm->lock_hidden);
1292 }
1293 
1294 static int start_nocpsch(struct device_queue_manager *dqm)
1295 {
1296 	int r = 0;
1297 
1298 	pr_info("SW scheduler is used");
1299 	init_interrupts(dqm);
1300 
1301 	if (dqm->dev->adev->asic_type == CHIP_HAWAII)
1302 		r = pm_init(&dqm->packet_mgr, dqm);
1303 	if (!r)
1304 		dqm->sched_running = true;
1305 
1306 	return r;
1307 }
1308 
1309 static int stop_nocpsch(struct device_queue_manager *dqm)
1310 {
1311 	if (dqm->dev->adev->asic_type == CHIP_HAWAII)
1312 		pm_uninit(&dqm->packet_mgr, false);
1313 	dqm->sched_running = false;
1314 
1315 	return 0;
1316 }
1317 
1318 static void pre_reset(struct device_queue_manager *dqm)
1319 {
1320 	dqm_lock(dqm);
1321 	dqm->is_resetting = true;
1322 	dqm_unlock(dqm);
1323 }
1324 
1325 static int allocate_sdma_queue(struct device_queue_manager *dqm,
1326 				struct queue *q, const uint32_t *restore_sdma_id)
1327 {
1328 	int bit;
1329 
1330 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1331 		if (dqm->sdma_bitmap == 0) {
1332 			pr_err("No more SDMA queue to allocate\n");
1333 			return -ENOMEM;
1334 		}
1335 
1336 		if (restore_sdma_id) {
1337 			/* Re-use existing sdma_id */
1338 			if (!(dqm->sdma_bitmap & (1ULL << *restore_sdma_id))) {
1339 				pr_err("SDMA queue already in use\n");
1340 				return -EBUSY;
1341 			}
1342 			dqm->sdma_bitmap &= ~(1ULL << *restore_sdma_id);
1343 			q->sdma_id = *restore_sdma_id;
1344 		} else {
1345 			/* Find first available sdma_id */
1346 			bit = __ffs64(dqm->sdma_bitmap);
1347 			dqm->sdma_bitmap &= ~(1ULL << bit);
1348 			q->sdma_id = bit;
1349 		}
1350 
1351 		q->properties.sdma_engine_id = q->sdma_id %
1352 				kfd_get_num_sdma_engines(dqm->dev);
1353 		q->properties.sdma_queue_id = q->sdma_id /
1354 				kfd_get_num_sdma_engines(dqm->dev);
1355 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1356 		if (dqm->xgmi_sdma_bitmap == 0) {
1357 			pr_err("No more XGMI SDMA queue to allocate\n");
1358 			return -ENOMEM;
1359 		}
1360 		if (restore_sdma_id) {
1361 			/* Re-use existing sdma_id */
1362 			if (!(dqm->xgmi_sdma_bitmap & (1ULL << *restore_sdma_id))) {
1363 				pr_err("SDMA queue already in use\n");
1364 				return -EBUSY;
1365 			}
1366 			dqm->xgmi_sdma_bitmap &= ~(1ULL << *restore_sdma_id);
1367 			q->sdma_id = *restore_sdma_id;
1368 		} else {
1369 			bit = __ffs64(dqm->xgmi_sdma_bitmap);
1370 			dqm->xgmi_sdma_bitmap &= ~(1ULL << bit);
1371 			q->sdma_id = bit;
1372 		}
1373 		/* sdma_engine_id is sdma id including
1374 		 * both PCIe-optimized SDMAs and XGMI-
1375 		 * optimized SDMAs. The calculation below
1376 		 * assumes the first N engines are always
1377 		 * PCIe-optimized ones
1378 		 */
1379 		q->properties.sdma_engine_id =
1380 			kfd_get_num_sdma_engines(dqm->dev) +
1381 			q->sdma_id % kfd_get_num_xgmi_sdma_engines(dqm->dev);
1382 		q->properties.sdma_queue_id = q->sdma_id /
1383 			kfd_get_num_xgmi_sdma_engines(dqm->dev);
1384 	}
1385 
1386 	pr_debug("SDMA engine id: %d\n", q->properties.sdma_engine_id);
1387 	pr_debug("SDMA queue id: %d\n", q->properties.sdma_queue_id);
1388 
1389 	return 0;
1390 }
1391 
1392 static void deallocate_sdma_queue(struct device_queue_manager *dqm,
1393 				struct queue *q)
1394 {
1395 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1396 		if (q->sdma_id >= get_num_sdma_queues(dqm))
1397 			return;
1398 		dqm->sdma_bitmap |= (1ULL << q->sdma_id);
1399 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1400 		if (q->sdma_id >= get_num_xgmi_sdma_queues(dqm))
1401 			return;
1402 		dqm->xgmi_sdma_bitmap |= (1ULL << q->sdma_id);
1403 	}
1404 }
1405 
1406 /*
1407  * Device Queue Manager implementation for cp scheduler
1408  */
1409 
1410 static int set_sched_resources(struct device_queue_manager *dqm)
1411 {
1412 	int i, mec;
1413 	struct scheduling_resources res;
1414 
1415 	res.vmid_mask = dqm->dev->shared_resources.compute_vmid_bitmap;
1416 
1417 	res.queue_mask = 0;
1418 	for (i = 0; i < KGD_MAX_QUEUES; ++i) {
1419 		mec = (i / dqm->dev->shared_resources.num_queue_per_pipe)
1420 			/ dqm->dev->shared_resources.num_pipe_per_mec;
1421 
1422 		if (!test_bit(i, dqm->dev->shared_resources.cp_queue_bitmap))
1423 			continue;
1424 
1425 		/* only acquire queues from the first MEC */
1426 		if (mec > 0)
1427 			continue;
1428 
1429 		/* This situation may be hit in the future if a new HW
1430 		 * generation exposes more than 64 queues. If so, the
1431 		 * definition of res.queue_mask needs updating
1432 		 */
1433 		if (WARN_ON(i >= (sizeof(res.queue_mask)*8))) {
1434 			pr_err("Invalid queue enabled by amdgpu: %d\n", i);
1435 			break;
1436 		}
1437 
1438 		res.queue_mask |= 1ull
1439 			<< amdgpu_queue_mask_bit_to_set_resource_bit(
1440 				dqm->dev->adev, i);
1441 	}
1442 	res.gws_mask = ~0ull;
1443 	res.oac_mask = res.gds_heap_base = res.gds_heap_size = 0;
1444 
1445 	pr_debug("Scheduling resources:\n"
1446 			"vmid mask: 0x%8X\n"
1447 			"queue mask: 0x%8llX\n",
1448 			res.vmid_mask, res.queue_mask);
1449 
1450 	return pm_send_set_resources(&dqm->packet_mgr, &res);
1451 }
1452 
1453 static int initialize_cpsch(struct device_queue_manager *dqm)
1454 {
1455 	uint64_t num_sdma_queues;
1456 	uint64_t num_xgmi_sdma_queues;
1457 
1458 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
1459 
1460 	mutex_init(&dqm->lock_hidden);
1461 	INIT_LIST_HEAD(&dqm->queues);
1462 	dqm->active_queue_count = dqm->processes_count = 0;
1463 	dqm->active_cp_queue_count = 0;
1464 	dqm->gws_queue_count = 0;
1465 	dqm->active_runlist = false;
1466 
1467 	num_sdma_queues = get_num_sdma_queues(dqm);
1468 	if (num_sdma_queues >= BITS_PER_TYPE(dqm->sdma_bitmap))
1469 		dqm->sdma_bitmap = ULLONG_MAX;
1470 	else
1471 		dqm->sdma_bitmap = (BIT_ULL(num_sdma_queues) - 1);
1472 
1473 	dqm->sdma_bitmap &= ~(get_reserved_sdma_queues_bitmap(dqm));
1474 	pr_info("sdma_bitmap: %llx\n", dqm->sdma_bitmap);
1475 
1476 	num_xgmi_sdma_queues = get_num_xgmi_sdma_queues(dqm);
1477 	if (num_xgmi_sdma_queues >= BITS_PER_TYPE(dqm->xgmi_sdma_bitmap))
1478 		dqm->xgmi_sdma_bitmap = ULLONG_MAX;
1479 	else
1480 		dqm->xgmi_sdma_bitmap = (BIT_ULL(num_xgmi_sdma_queues) - 1);
1481 
1482 	INIT_WORK(&dqm->hw_exception_work, kfd_process_hw_exception);
1483 
1484 	return 0;
1485 }
1486 
1487 static int start_cpsch(struct device_queue_manager *dqm)
1488 {
1489 	int retval;
1490 
1491 	retval = 0;
1492 
1493 	dqm_lock(dqm);
1494 
1495 	if (!dqm->dev->shared_resources.enable_mes) {
1496 		retval = pm_init(&dqm->packet_mgr, dqm);
1497 		if (retval)
1498 			goto fail_packet_manager_init;
1499 
1500 		retval = set_sched_resources(dqm);
1501 		if (retval)
1502 			goto fail_set_sched_resources;
1503 	}
1504 	pr_debug("Allocating fence memory\n");
1505 
1506 	/* allocate fence memory on the gart */
1507 	retval = kfd_gtt_sa_allocate(dqm->dev, sizeof(*dqm->fence_addr),
1508 					&dqm->fence_mem);
1509 
1510 	if (retval)
1511 		goto fail_allocate_vidmem;
1512 
1513 	dqm->fence_addr = (uint64_t *)dqm->fence_mem->cpu_ptr;
1514 	dqm->fence_gpu_addr = dqm->fence_mem->gpu_addr;
1515 
1516 	init_interrupts(dqm);
1517 
1518 	/* clear hang status when driver try to start the hw scheduler */
1519 	dqm->is_hws_hang = false;
1520 	dqm->is_resetting = false;
1521 	dqm->sched_running = true;
1522 	if (!dqm->dev->shared_resources.enable_mes)
1523 		execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1524 	dqm_unlock(dqm);
1525 
1526 	return 0;
1527 fail_allocate_vidmem:
1528 fail_set_sched_resources:
1529 	if (!dqm->dev->shared_resources.enable_mes)
1530 		pm_uninit(&dqm->packet_mgr, false);
1531 fail_packet_manager_init:
1532 	dqm_unlock(dqm);
1533 	return retval;
1534 }
1535 
1536 static int stop_cpsch(struct device_queue_manager *dqm)
1537 {
1538 	bool hanging;
1539 
1540 	dqm_lock(dqm);
1541 	if (!dqm->sched_running) {
1542 		dqm_unlock(dqm);
1543 		return 0;
1544 	}
1545 
1546 	if (!dqm->is_hws_hang) {
1547 		if (!dqm->dev->shared_resources.enable_mes)
1548 			unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0, false);
1549 		else
1550 			remove_all_queues_mes(dqm);
1551 	}
1552 
1553 	hanging = dqm->is_hws_hang || dqm->is_resetting;
1554 	dqm->sched_running = false;
1555 
1556 	if (!dqm->dev->shared_resources.enable_mes)
1557 		pm_release_ib(&dqm->packet_mgr);
1558 
1559 	kfd_gtt_sa_free(dqm->dev, dqm->fence_mem);
1560 	if (!dqm->dev->shared_resources.enable_mes)
1561 		pm_uninit(&dqm->packet_mgr, hanging);
1562 	dqm_unlock(dqm);
1563 
1564 	return 0;
1565 }
1566 
1567 static int create_kernel_queue_cpsch(struct device_queue_manager *dqm,
1568 					struct kernel_queue *kq,
1569 					struct qcm_process_device *qpd)
1570 {
1571 	dqm_lock(dqm);
1572 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1573 		pr_warn("Can't create new kernel queue because %d queues were already created\n",
1574 				dqm->total_queue_count);
1575 		dqm_unlock(dqm);
1576 		return -EPERM;
1577 	}
1578 
1579 	/*
1580 	 * Unconditionally increment this counter, regardless of the queue's
1581 	 * type or whether the queue is active.
1582 	 */
1583 	dqm->total_queue_count++;
1584 	pr_debug("Total of %d queues are accountable so far\n",
1585 			dqm->total_queue_count);
1586 
1587 	list_add(&kq->list, &qpd->priv_queue_list);
1588 	increment_queue_count(dqm, qpd, kq->queue);
1589 	qpd->is_debug = true;
1590 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1591 	dqm_unlock(dqm);
1592 
1593 	return 0;
1594 }
1595 
1596 static void destroy_kernel_queue_cpsch(struct device_queue_manager *dqm,
1597 					struct kernel_queue *kq,
1598 					struct qcm_process_device *qpd)
1599 {
1600 	dqm_lock(dqm);
1601 	list_del(&kq->list);
1602 	decrement_queue_count(dqm, qpd, kq->queue);
1603 	qpd->is_debug = false;
1604 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0);
1605 	/*
1606 	 * Unconditionally decrement this counter, regardless of the queue's
1607 	 * type.
1608 	 */
1609 	dqm->total_queue_count--;
1610 	pr_debug("Total of %d queues are accountable so far\n",
1611 			dqm->total_queue_count);
1612 	dqm_unlock(dqm);
1613 }
1614 
1615 static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
1616 			struct qcm_process_device *qpd,
1617 			const struct kfd_criu_queue_priv_data *qd,
1618 			const void *restore_mqd, const void *restore_ctl_stack)
1619 {
1620 	int retval;
1621 	struct mqd_manager *mqd_mgr;
1622 
1623 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1624 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
1625 				dqm->total_queue_count);
1626 		retval = -EPERM;
1627 		goto out;
1628 	}
1629 
1630 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1631 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1632 		dqm_lock(dqm);
1633 		retval = allocate_sdma_queue(dqm, q, qd ? &qd->sdma_id : NULL);
1634 		dqm_unlock(dqm);
1635 		if (retval)
1636 			goto out;
1637 	}
1638 
1639 	retval = allocate_doorbell(qpd, q, qd ? &qd->doorbell_id : NULL);
1640 	if (retval)
1641 		goto out_deallocate_sdma_queue;
1642 
1643 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1644 			q->properties.type)];
1645 
1646 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1647 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
1648 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
1649 	q->properties.tba_addr = qpd->tba_addr;
1650 	q->properties.tma_addr = qpd->tma_addr;
1651 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr->dev, &q->properties);
1652 	if (!q->mqd_mem_obj) {
1653 		retval = -ENOMEM;
1654 		goto out_deallocate_doorbell;
1655 	}
1656 
1657 	dqm_lock(dqm);
1658 	/*
1659 	 * Eviction state logic: mark all queues as evicted, even ones
1660 	 * not currently active. Restoring inactive queues later only
1661 	 * updates the is_evicted flag but is a no-op otherwise.
1662 	 */
1663 	q->properties.is_evicted = !!qpd->evicted;
1664 
1665 	if (qd)
1666 		mqd_mgr->restore_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj, &q->gart_mqd_addr,
1667 				     &q->properties, restore_mqd, restore_ctl_stack,
1668 				     qd->ctl_stack_size);
1669 	else
1670 		mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
1671 					&q->gart_mqd_addr, &q->properties);
1672 
1673 	list_add(&q->list, &qpd->queues_list);
1674 	qpd->queue_count++;
1675 
1676 	if (q->properties.is_active) {
1677 		increment_queue_count(dqm, qpd, q);
1678 
1679 		if (!dqm->dev->shared_resources.enable_mes)
1680 			retval = execute_queues_cpsch(dqm,
1681 					KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1682 		else
1683 			retval = add_queue_mes(dqm, q, qpd);
1684 		if (retval)
1685 			goto cleanup_queue;
1686 	}
1687 
1688 	/*
1689 	 * Unconditionally increment this counter, regardless of the queue's
1690 	 * type or whether the queue is active.
1691 	 */
1692 	dqm->total_queue_count++;
1693 
1694 	pr_debug("Total of %d queues are accountable so far\n",
1695 			dqm->total_queue_count);
1696 
1697 	dqm_unlock(dqm);
1698 	return retval;
1699 
1700 cleanup_queue:
1701 	qpd->queue_count--;
1702 	list_del(&q->list);
1703 	if (q->properties.is_active)
1704 		decrement_queue_count(dqm, qpd, q);
1705 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
1706 	dqm_unlock(dqm);
1707 out_deallocate_doorbell:
1708 	deallocate_doorbell(qpd, q);
1709 out_deallocate_sdma_queue:
1710 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1711 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1712 		dqm_lock(dqm);
1713 		deallocate_sdma_queue(dqm, q);
1714 		dqm_unlock(dqm);
1715 	}
1716 out:
1717 	return retval;
1718 }
1719 
1720 int amdkfd_fence_wait_timeout(uint64_t *fence_addr,
1721 				uint64_t fence_value,
1722 				unsigned int timeout_ms)
1723 {
1724 	unsigned long end_jiffies = msecs_to_jiffies(timeout_ms) + jiffies;
1725 
1726 	while (*fence_addr != fence_value) {
1727 		if (time_after(jiffies, end_jiffies)) {
1728 			pr_err("qcm fence wait loop timeout expired\n");
1729 			/* In HWS case, this is used to halt the driver thread
1730 			 * in order not to mess up CP states before doing
1731 			 * scandumps for FW debugging.
1732 			 */
1733 			while (halt_if_hws_hang)
1734 				schedule();
1735 
1736 			return -ETIME;
1737 		}
1738 		schedule();
1739 	}
1740 
1741 	return 0;
1742 }
1743 
1744 /* dqm->lock mutex has to be locked before calling this function */
1745 static int map_queues_cpsch(struct device_queue_manager *dqm)
1746 {
1747 	int retval;
1748 
1749 	if (!dqm->sched_running)
1750 		return 0;
1751 	if (dqm->active_queue_count <= 0 || dqm->processes_count <= 0)
1752 		return 0;
1753 	if (dqm->active_runlist)
1754 		return 0;
1755 
1756 	retval = pm_send_runlist(&dqm->packet_mgr, &dqm->queues);
1757 	pr_debug("%s sent runlist\n", __func__);
1758 	if (retval) {
1759 		pr_err("failed to execute runlist\n");
1760 		return retval;
1761 	}
1762 	dqm->active_runlist = true;
1763 
1764 	return retval;
1765 }
1766 
1767 /* dqm->lock mutex has to be locked before calling this function */
1768 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
1769 				enum kfd_unmap_queues_filter filter,
1770 				uint32_t filter_param, bool reset)
1771 {
1772 	int retval = 0;
1773 	struct mqd_manager *mqd_mgr;
1774 
1775 	if (!dqm->sched_running)
1776 		return 0;
1777 	if (dqm->is_hws_hang || dqm->is_resetting)
1778 		return -EIO;
1779 	if (!dqm->active_runlist)
1780 		return retval;
1781 
1782 	retval = pm_send_unmap_queue(&dqm->packet_mgr, filter, filter_param, reset);
1783 	if (retval)
1784 		return retval;
1785 
1786 	*dqm->fence_addr = KFD_FENCE_INIT;
1787 	pm_send_query_status(&dqm->packet_mgr, dqm->fence_gpu_addr,
1788 				KFD_FENCE_COMPLETED);
1789 	/* should be timed out */
1790 	retval = amdkfd_fence_wait_timeout(dqm->fence_addr, KFD_FENCE_COMPLETED,
1791 				queue_preemption_timeout_ms);
1792 	if (retval) {
1793 		pr_err("The cp might be in an unrecoverable state due to an unsuccessful queues preemption\n");
1794 		kfd_hws_hang(dqm);
1795 		return retval;
1796 	}
1797 
1798 	/* In the current MEC firmware implementation, if compute queue
1799 	 * doesn't response to the preemption request in time, HIQ will
1800 	 * abandon the unmap request without returning any timeout error
1801 	 * to driver. Instead, MEC firmware will log the doorbell of the
1802 	 * unresponding compute queue to HIQ.MQD.queue_doorbell_id fields.
1803 	 * To make sure the queue unmap was successful, driver need to
1804 	 * check those fields
1805 	 */
1806 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ];
1807 	if (mqd_mgr->read_doorbell_id(dqm->packet_mgr.priv_queue->queue->mqd)) {
1808 		pr_err("HIQ MQD's queue_doorbell_id0 is not 0, Queue preemption time out\n");
1809 		while (halt_if_hws_hang)
1810 			schedule();
1811 		return -ETIME;
1812 	}
1813 
1814 	pm_release_ib(&dqm->packet_mgr);
1815 	dqm->active_runlist = false;
1816 
1817 	return retval;
1818 }
1819 
1820 /* only for compute queue */
1821 static int reset_queues_cpsch(struct device_queue_manager *dqm,
1822 			uint16_t pasid)
1823 {
1824 	int retval;
1825 
1826 	dqm_lock(dqm);
1827 
1828 	retval = unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_BY_PASID,
1829 			pasid, true);
1830 
1831 	dqm_unlock(dqm);
1832 	return retval;
1833 }
1834 
1835 /* dqm->lock mutex has to be locked before calling this function */
1836 static int execute_queues_cpsch(struct device_queue_manager *dqm,
1837 				enum kfd_unmap_queues_filter filter,
1838 				uint32_t filter_param)
1839 {
1840 	int retval;
1841 
1842 	if (dqm->is_hws_hang)
1843 		return -EIO;
1844 	retval = unmap_queues_cpsch(dqm, filter, filter_param, false);
1845 	if (retval)
1846 		return retval;
1847 
1848 	return map_queues_cpsch(dqm);
1849 }
1850 
1851 static int destroy_queue_cpsch(struct device_queue_manager *dqm,
1852 				struct qcm_process_device *qpd,
1853 				struct queue *q)
1854 {
1855 	int retval;
1856 	struct mqd_manager *mqd_mgr;
1857 	uint64_t sdma_val = 0;
1858 	struct kfd_process_device *pdd = qpd_to_pdd(qpd);
1859 
1860 	/* Get the SDMA queue stats */
1861 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
1862 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
1863 		retval = read_sdma_queue_counter((uint64_t __user *)q->properties.read_ptr,
1864 							&sdma_val);
1865 		if (retval)
1866 			pr_err("Failed to read SDMA queue counter for queue: %d\n",
1867 				q->properties.queue_id);
1868 	}
1869 
1870 	retval = 0;
1871 
1872 	/* remove queue from list to prevent rescheduling after preemption */
1873 	dqm_lock(dqm);
1874 
1875 	if (qpd->is_debug) {
1876 		/*
1877 		 * error, currently we do not allow to destroy a queue
1878 		 * of a currently debugged process
1879 		 */
1880 		retval = -EBUSY;
1881 		goto failed_try_destroy_debugged_queue;
1882 
1883 	}
1884 
1885 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1886 			q->properties.type)];
1887 
1888 	deallocate_doorbell(qpd, q);
1889 
1890 	if ((q->properties.type == KFD_QUEUE_TYPE_SDMA) ||
1891 	    (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
1892 		deallocate_sdma_queue(dqm, q);
1893 		pdd->sdma_past_activity_counter += sdma_val;
1894 	}
1895 
1896 	list_del(&q->list);
1897 	qpd->queue_count--;
1898 	if (q->properties.is_active) {
1899 		if (!dqm->dev->shared_resources.enable_mes) {
1900 			decrement_queue_count(dqm, qpd, q);
1901 			retval = execute_queues_cpsch(dqm,
1902 						      KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1903 			if (retval == -ETIME)
1904 				qpd->reset_wavefronts = true;
1905 		} else {
1906 			retval = remove_queue_mes(dqm, q, qpd);
1907 		}
1908 	}
1909 
1910 	/*
1911 	 * Unconditionally decrement this counter, regardless of the queue's
1912 	 * type
1913 	 */
1914 	dqm->total_queue_count--;
1915 	pr_debug("Total of %d queues are accountable so far\n",
1916 			dqm->total_queue_count);
1917 
1918 	dqm_unlock(dqm);
1919 
1920 	/* Do free_mqd after dqm_unlock(dqm) to avoid circular locking */
1921 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
1922 
1923 	return retval;
1924 
1925 failed_try_destroy_debugged_queue:
1926 
1927 	dqm_unlock(dqm);
1928 	return retval;
1929 }
1930 
1931 /*
1932  * Low bits must be 0000/FFFF as required by HW, high bits must be 0 to
1933  * stay in user mode.
1934  */
1935 #define APE1_FIXED_BITS_MASK 0xFFFF80000000FFFFULL
1936 /* APE1 limit is inclusive and 64K aligned. */
1937 #define APE1_LIMIT_ALIGNMENT 0xFFFF
1938 
1939 static bool set_cache_memory_policy(struct device_queue_manager *dqm,
1940 				   struct qcm_process_device *qpd,
1941 				   enum cache_policy default_policy,
1942 				   enum cache_policy alternate_policy,
1943 				   void __user *alternate_aperture_base,
1944 				   uint64_t alternate_aperture_size)
1945 {
1946 	bool retval = true;
1947 
1948 	if (!dqm->asic_ops.set_cache_memory_policy)
1949 		return retval;
1950 
1951 	dqm_lock(dqm);
1952 
1953 	if (alternate_aperture_size == 0) {
1954 		/* base > limit disables APE1 */
1955 		qpd->sh_mem_ape1_base = 1;
1956 		qpd->sh_mem_ape1_limit = 0;
1957 	} else {
1958 		/*
1959 		 * In FSA64, APE1_Base[63:0] = { 16{SH_MEM_APE1_BASE[31]},
1960 		 *			SH_MEM_APE1_BASE[31:0], 0x0000 }
1961 		 * APE1_Limit[63:0] = { 16{SH_MEM_APE1_LIMIT[31]},
1962 		 *			SH_MEM_APE1_LIMIT[31:0], 0xFFFF }
1963 		 * Verify that the base and size parameters can be
1964 		 * represented in this format and convert them.
1965 		 * Additionally restrict APE1 to user-mode addresses.
1966 		 */
1967 
1968 		uint64_t base = (uintptr_t)alternate_aperture_base;
1969 		uint64_t limit = base + alternate_aperture_size - 1;
1970 
1971 		if (limit <= base || (base & APE1_FIXED_BITS_MASK) != 0 ||
1972 		   (limit & APE1_FIXED_BITS_MASK) != APE1_LIMIT_ALIGNMENT) {
1973 			retval = false;
1974 			goto out;
1975 		}
1976 
1977 		qpd->sh_mem_ape1_base = base >> 16;
1978 		qpd->sh_mem_ape1_limit = limit >> 16;
1979 	}
1980 
1981 	retval = dqm->asic_ops.set_cache_memory_policy(
1982 			dqm,
1983 			qpd,
1984 			default_policy,
1985 			alternate_policy,
1986 			alternate_aperture_base,
1987 			alternate_aperture_size);
1988 
1989 	if ((dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) && (qpd->vmid != 0))
1990 		program_sh_mem_settings(dqm, qpd);
1991 
1992 	pr_debug("sh_mem_config: 0x%x, ape1_base: 0x%x, ape1_limit: 0x%x\n",
1993 		qpd->sh_mem_config, qpd->sh_mem_ape1_base,
1994 		qpd->sh_mem_ape1_limit);
1995 
1996 out:
1997 	dqm_unlock(dqm);
1998 	return retval;
1999 }
2000 
2001 static int process_termination_nocpsch(struct device_queue_manager *dqm,
2002 		struct qcm_process_device *qpd)
2003 {
2004 	struct queue *q;
2005 	struct device_process_node *cur, *next_dpn;
2006 	int retval = 0;
2007 	bool found = false;
2008 
2009 	dqm_lock(dqm);
2010 
2011 	/* Clear all user mode queues */
2012 	while (!list_empty(&qpd->queues_list)) {
2013 		struct mqd_manager *mqd_mgr;
2014 		int ret;
2015 
2016 		q = list_first_entry(&qpd->queues_list, struct queue, list);
2017 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2018 				q->properties.type)];
2019 		ret = destroy_queue_nocpsch_locked(dqm, qpd, q);
2020 		if (ret)
2021 			retval = ret;
2022 		dqm_unlock(dqm);
2023 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2024 		dqm_lock(dqm);
2025 	}
2026 
2027 	/* Unregister process */
2028 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
2029 		if (qpd == cur->qpd) {
2030 			list_del(&cur->list);
2031 			kfree(cur);
2032 			dqm->processes_count--;
2033 			found = true;
2034 			break;
2035 		}
2036 	}
2037 
2038 	dqm_unlock(dqm);
2039 
2040 	/* Outside the DQM lock because under the DQM lock we can't do
2041 	 * reclaim or take other locks that others hold while reclaiming.
2042 	 */
2043 	if (found)
2044 		kfd_dec_compute_active(dqm->dev);
2045 
2046 	return retval;
2047 }
2048 
2049 static int get_wave_state(struct device_queue_manager *dqm,
2050 			  struct queue *q,
2051 			  void __user *ctl_stack,
2052 			  u32 *ctl_stack_used_size,
2053 			  u32 *save_area_used_size)
2054 {
2055 	struct mqd_manager *mqd_mgr;
2056 
2057 	dqm_lock(dqm);
2058 
2059 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_CP];
2060 
2061 	if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE ||
2062 	    q->properties.is_active || !q->device->cwsr_enabled ||
2063 	    !mqd_mgr->get_wave_state) {
2064 		dqm_unlock(dqm);
2065 		return -EINVAL;
2066 	}
2067 
2068 	dqm_unlock(dqm);
2069 
2070 	/*
2071 	 * get_wave_state is outside the dqm lock to prevent circular locking
2072 	 * and the queue should be protected against destruction by the process
2073 	 * lock.
2074 	 */
2075 	return mqd_mgr->get_wave_state(mqd_mgr, q->mqd, ctl_stack,
2076 			ctl_stack_used_size, save_area_used_size);
2077 }
2078 
2079 static void get_queue_checkpoint_info(struct device_queue_manager *dqm,
2080 			const struct queue *q,
2081 			u32 *mqd_size,
2082 			u32 *ctl_stack_size)
2083 {
2084 	struct mqd_manager *mqd_mgr;
2085 	enum KFD_MQD_TYPE mqd_type =
2086 			get_mqd_type_from_queue_type(q->properties.type);
2087 
2088 	dqm_lock(dqm);
2089 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
2090 	*mqd_size = mqd_mgr->mqd_size;
2091 	*ctl_stack_size = 0;
2092 
2093 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE && mqd_mgr->get_checkpoint_info)
2094 		mqd_mgr->get_checkpoint_info(mqd_mgr, q->mqd, ctl_stack_size);
2095 
2096 	dqm_unlock(dqm);
2097 }
2098 
2099 static int checkpoint_mqd(struct device_queue_manager *dqm,
2100 			  const struct queue *q,
2101 			  void *mqd,
2102 			  void *ctl_stack)
2103 {
2104 	struct mqd_manager *mqd_mgr;
2105 	int r = 0;
2106 	enum KFD_MQD_TYPE mqd_type =
2107 			get_mqd_type_from_queue_type(q->properties.type);
2108 
2109 	dqm_lock(dqm);
2110 
2111 	if (q->properties.is_active || !q->device->cwsr_enabled) {
2112 		r = -EINVAL;
2113 		goto dqm_unlock;
2114 	}
2115 
2116 	mqd_mgr = dqm->mqd_mgrs[mqd_type];
2117 	if (!mqd_mgr->checkpoint_mqd) {
2118 		r = -EOPNOTSUPP;
2119 		goto dqm_unlock;
2120 	}
2121 
2122 	mqd_mgr->checkpoint_mqd(mqd_mgr, q->mqd, mqd, ctl_stack);
2123 
2124 dqm_unlock:
2125 	dqm_unlock(dqm);
2126 	return r;
2127 }
2128 
2129 static int process_termination_cpsch(struct device_queue_manager *dqm,
2130 		struct qcm_process_device *qpd)
2131 {
2132 	int retval;
2133 	struct queue *q;
2134 	struct kernel_queue *kq, *kq_next;
2135 	struct mqd_manager *mqd_mgr;
2136 	struct device_process_node *cur, *next_dpn;
2137 	enum kfd_unmap_queues_filter filter =
2138 		KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES;
2139 	bool found = false;
2140 
2141 	retval = 0;
2142 
2143 	dqm_lock(dqm);
2144 
2145 	/* Clean all kernel queues */
2146 	list_for_each_entry_safe(kq, kq_next, &qpd->priv_queue_list, list) {
2147 		list_del(&kq->list);
2148 		decrement_queue_count(dqm, qpd, kq->queue);
2149 		qpd->is_debug = false;
2150 		dqm->total_queue_count--;
2151 		filter = KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES;
2152 	}
2153 
2154 	/* Clear all user mode queues */
2155 	list_for_each_entry(q, &qpd->queues_list, list) {
2156 		if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
2157 			deallocate_sdma_queue(dqm, q);
2158 		else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
2159 			deallocate_sdma_queue(dqm, q);
2160 
2161 		if (q->properties.is_active) {
2162 			decrement_queue_count(dqm, qpd, q);
2163 
2164 			if (dqm->dev->shared_resources.enable_mes) {
2165 				retval = remove_queue_mes(dqm, q, qpd);
2166 				if (retval)
2167 					pr_err("Failed to remove queue %d\n",
2168 						q->properties.queue_id);
2169 			}
2170 		}
2171 
2172 		dqm->total_queue_count--;
2173 	}
2174 
2175 	/* Unregister process */
2176 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
2177 		if (qpd == cur->qpd) {
2178 			list_del(&cur->list);
2179 			kfree(cur);
2180 			dqm->processes_count--;
2181 			found = true;
2182 			break;
2183 		}
2184 	}
2185 
2186 	if (!dqm->dev->shared_resources.enable_mes)
2187 		retval = execute_queues_cpsch(dqm, filter, 0);
2188 
2189 	if ((!dqm->is_hws_hang) && (retval || qpd->reset_wavefronts)) {
2190 		pr_warn("Resetting wave fronts (cpsch) on dev %p\n", dqm->dev);
2191 		dbgdev_wave_reset_wavefronts(dqm->dev, qpd->pqm->process);
2192 		qpd->reset_wavefronts = false;
2193 	}
2194 
2195 	/* Lastly, free mqd resources.
2196 	 * Do free_mqd() after dqm_unlock to avoid circular locking.
2197 	 */
2198 	while (!list_empty(&qpd->queues_list)) {
2199 		q = list_first_entry(&qpd->queues_list, struct queue, list);
2200 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
2201 				q->properties.type)];
2202 		list_del(&q->list);
2203 		qpd->queue_count--;
2204 		dqm_unlock(dqm);
2205 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
2206 		dqm_lock(dqm);
2207 	}
2208 	dqm_unlock(dqm);
2209 
2210 	/* Outside the DQM lock because under the DQM lock we can't do
2211 	 * reclaim or take other locks that others hold while reclaiming.
2212 	 */
2213 	if (found)
2214 		kfd_dec_compute_active(dqm->dev);
2215 
2216 	return retval;
2217 }
2218 
2219 static int init_mqd_managers(struct device_queue_manager *dqm)
2220 {
2221 	int i, j;
2222 	struct mqd_manager *mqd_mgr;
2223 
2224 	for (i = 0; i < KFD_MQD_TYPE_MAX; i++) {
2225 		mqd_mgr = dqm->asic_ops.mqd_manager_init(i, dqm->dev);
2226 		if (!mqd_mgr) {
2227 			pr_err("mqd manager [%d] initialization failed\n", i);
2228 			goto out_free;
2229 		}
2230 		dqm->mqd_mgrs[i] = mqd_mgr;
2231 	}
2232 
2233 	return 0;
2234 
2235 out_free:
2236 	for (j = 0; j < i; j++) {
2237 		kfree(dqm->mqd_mgrs[j]);
2238 		dqm->mqd_mgrs[j] = NULL;
2239 	}
2240 
2241 	return -ENOMEM;
2242 }
2243 
2244 /* Allocate one hiq mqd (HWS) and all SDMA mqd in a continuous trunk*/
2245 static int allocate_hiq_sdma_mqd(struct device_queue_manager *dqm)
2246 {
2247 	int retval;
2248 	struct kfd_dev *dev = dqm->dev;
2249 	struct kfd_mem_obj *mem_obj = &dqm->hiq_sdma_mqd;
2250 	uint32_t size = dqm->mqd_mgrs[KFD_MQD_TYPE_SDMA]->mqd_size *
2251 		get_num_all_sdma_engines(dqm) *
2252 		dev->device_info.num_sdma_queues_per_engine +
2253 		dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ]->mqd_size;
2254 
2255 	retval = amdgpu_amdkfd_alloc_gtt_mem(dev->adev, size,
2256 		&(mem_obj->gtt_mem), &(mem_obj->gpu_addr),
2257 		(void *)&(mem_obj->cpu_ptr), false);
2258 
2259 	return retval;
2260 }
2261 
2262 struct device_queue_manager *device_queue_manager_init(struct kfd_dev *dev)
2263 {
2264 	struct device_queue_manager *dqm;
2265 
2266 	pr_debug("Loading device queue manager\n");
2267 
2268 	dqm = kzalloc(sizeof(*dqm), GFP_KERNEL);
2269 	if (!dqm)
2270 		return NULL;
2271 
2272 	switch (dev->adev->asic_type) {
2273 	/* HWS is not available on Hawaii. */
2274 	case CHIP_HAWAII:
2275 	/* HWS depends on CWSR for timely dequeue. CWSR is not
2276 	 * available on Tonga.
2277 	 *
2278 	 * FIXME: This argument also applies to Kaveri.
2279 	 */
2280 	case CHIP_TONGA:
2281 		dqm->sched_policy = KFD_SCHED_POLICY_NO_HWS;
2282 		break;
2283 	default:
2284 		dqm->sched_policy = sched_policy;
2285 		break;
2286 	}
2287 
2288 	dqm->dev = dev;
2289 	switch (dqm->sched_policy) {
2290 	case KFD_SCHED_POLICY_HWS:
2291 	case KFD_SCHED_POLICY_HWS_NO_OVERSUBSCRIPTION:
2292 		/* initialize dqm for cp scheduling */
2293 		dqm->ops.create_queue = create_queue_cpsch;
2294 		dqm->ops.initialize = initialize_cpsch;
2295 		dqm->ops.start = start_cpsch;
2296 		dqm->ops.stop = stop_cpsch;
2297 		dqm->ops.pre_reset = pre_reset;
2298 		dqm->ops.destroy_queue = destroy_queue_cpsch;
2299 		dqm->ops.update_queue = update_queue;
2300 		dqm->ops.register_process = register_process;
2301 		dqm->ops.unregister_process = unregister_process;
2302 		dqm->ops.uninitialize = uninitialize;
2303 		dqm->ops.create_kernel_queue = create_kernel_queue_cpsch;
2304 		dqm->ops.destroy_kernel_queue = destroy_kernel_queue_cpsch;
2305 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
2306 		dqm->ops.process_termination = process_termination_cpsch;
2307 		dqm->ops.evict_process_queues = evict_process_queues_cpsch;
2308 		dqm->ops.restore_process_queues = restore_process_queues_cpsch;
2309 		dqm->ops.get_wave_state = get_wave_state;
2310 		dqm->ops.reset_queues = reset_queues_cpsch;
2311 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
2312 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
2313 		break;
2314 	case KFD_SCHED_POLICY_NO_HWS:
2315 		/* initialize dqm for no cp scheduling */
2316 		dqm->ops.start = start_nocpsch;
2317 		dqm->ops.stop = stop_nocpsch;
2318 		dqm->ops.pre_reset = pre_reset;
2319 		dqm->ops.create_queue = create_queue_nocpsch;
2320 		dqm->ops.destroy_queue = destroy_queue_nocpsch;
2321 		dqm->ops.update_queue = update_queue;
2322 		dqm->ops.register_process = register_process;
2323 		dqm->ops.unregister_process = unregister_process;
2324 		dqm->ops.initialize = initialize_nocpsch;
2325 		dqm->ops.uninitialize = uninitialize;
2326 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
2327 		dqm->ops.process_termination = process_termination_nocpsch;
2328 		dqm->ops.evict_process_queues = evict_process_queues_nocpsch;
2329 		dqm->ops.restore_process_queues =
2330 			restore_process_queues_nocpsch;
2331 		dqm->ops.get_wave_state = get_wave_state;
2332 		dqm->ops.get_queue_checkpoint_info = get_queue_checkpoint_info;
2333 		dqm->ops.checkpoint_mqd = checkpoint_mqd;
2334 		break;
2335 	default:
2336 		pr_err("Invalid scheduling policy %d\n", dqm->sched_policy);
2337 		goto out_free;
2338 	}
2339 
2340 	switch (dev->adev->asic_type) {
2341 	case CHIP_CARRIZO:
2342 		device_queue_manager_init_vi(&dqm->asic_ops);
2343 		break;
2344 
2345 	case CHIP_KAVERI:
2346 		device_queue_manager_init_cik(&dqm->asic_ops);
2347 		break;
2348 
2349 	case CHIP_HAWAII:
2350 		device_queue_manager_init_cik_hawaii(&dqm->asic_ops);
2351 		break;
2352 
2353 	case CHIP_TONGA:
2354 	case CHIP_FIJI:
2355 	case CHIP_POLARIS10:
2356 	case CHIP_POLARIS11:
2357 	case CHIP_POLARIS12:
2358 	case CHIP_VEGAM:
2359 		device_queue_manager_init_vi_tonga(&dqm->asic_ops);
2360 		break;
2361 
2362 	default:
2363 		if (KFD_GC_VERSION(dev) >= IP_VERSION(11, 0, 0))
2364 			device_queue_manager_init_v11(&dqm->asic_ops);
2365 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(10, 1, 1))
2366 			device_queue_manager_init_v10_navi10(&dqm->asic_ops);
2367 		else if (KFD_GC_VERSION(dev) >= IP_VERSION(9, 0, 1))
2368 			device_queue_manager_init_v9(&dqm->asic_ops);
2369 		else {
2370 			WARN(1, "Unexpected ASIC family %u",
2371 			     dev->adev->asic_type);
2372 			goto out_free;
2373 		}
2374 	}
2375 
2376 	if (init_mqd_managers(dqm))
2377 		goto out_free;
2378 
2379 	if (allocate_hiq_sdma_mqd(dqm)) {
2380 		pr_err("Failed to allocate hiq sdma mqd trunk buffer\n");
2381 		goto out_free;
2382 	}
2383 
2384 	if (!dqm->ops.initialize(dqm))
2385 		return dqm;
2386 
2387 out_free:
2388 	kfree(dqm);
2389 	return NULL;
2390 }
2391 
2392 static void deallocate_hiq_sdma_mqd(struct kfd_dev *dev,
2393 				    struct kfd_mem_obj *mqd)
2394 {
2395 	WARN(!mqd, "No hiq sdma mqd trunk to free");
2396 
2397 	amdgpu_amdkfd_free_gtt_mem(dev->adev, mqd->gtt_mem);
2398 }
2399 
2400 void device_queue_manager_uninit(struct device_queue_manager *dqm)
2401 {
2402 	dqm->ops.uninitialize(dqm);
2403 	deallocate_hiq_sdma_mqd(dqm->dev, &dqm->hiq_sdma_mqd);
2404 	kfree(dqm);
2405 }
2406 
2407 int kfd_dqm_evict_pasid(struct device_queue_manager *dqm, u32 pasid)
2408 {
2409 	struct kfd_process_device *pdd;
2410 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid);
2411 	int ret = 0;
2412 
2413 	if (!p)
2414 		return -EINVAL;
2415 	WARN(debug_evictions, "Evicting pid %d", p->lead_thread->pid);
2416 	pdd = kfd_get_process_device_data(dqm->dev, p);
2417 	if (pdd)
2418 		ret = dqm->ops.evict_process_queues(dqm, &pdd->qpd);
2419 	kfd_unref_process(p);
2420 
2421 	return ret;
2422 }
2423 
2424 static void kfd_process_hw_exception(struct work_struct *work)
2425 {
2426 	struct device_queue_manager *dqm = container_of(work,
2427 			struct device_queue_manager, hw_exception_work);
2428 	amdgpu_amdkfd_gpu_reset(dqm->dev->adev);
2429 }
2430 
2431 #if defined(CONFIG_DEBUG_FS)
2432 
2433 static void seq_reg_dump(struct seq_file *m,
2434 			 uint32_t (*dump)[2], uint32_t n_regs)
2435 {
2436 	uint32_t i, count;
2437 
2438 	for (i = 0, count = 0; i < n_regs; i++) {
2439 		if (count == 0 ||
2440 		    dump[i-1][0] + sizeof(uint32_t) != dump[i][0]) {
2441 			seq_printf(m, "%s    %08x: %08x",
2442 				   i ? "\n" : "",
2443 				   dump[i][0], dump[i][1]);
2444 			count = 7;
2445 		} else {
2446 			seq_printf(m, " %08x", dump[i][1]);
2447 			count--;
2448 		}
2449 	}
2450 
2451 	seq_puts(m, "\n");
2452 }
2453 
2454 int dqm_debugfs_hqds(struct seq_file *m, void *data)
2455 {
2456 	struct device_queue_manager *dqm = data;
2457 	uint32_t (*dump)[2], n_regs;
2458 	int pipe, queue;
2459 	int r = 0;
2460 
2461 	if (!dqm->sched_running) {
2462 		seq_puts(m, " Device is stopped\n");
2463 		return 0;
2464 	}
2465 
2466 	r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->adev,
2467 					KFD_CIK_HIQ_PIPE, KFD_CIK_HIQ_QUEUE,
2468 					&dump, &n_regs);
2469 	if (!r) {
2470 		seq_printf(m, "  HIQ on MEC %d Pipe %d Queue %d\n",
2471 			   KFD_CIK_HIQ_PIPE/get_pipes_per_mec(dqm)+1,
2472 			   KFD_CIK_HIQ_PIPE%get_pipes_per_mec(dqm),
2473 			   KFD_CIK_HIQ_QUEUE);
2474 		seq_reg_dump(m, dump, n_regs);
2475 
2476 		kfree(dump);
2477 	}
2478 
2479 	for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
2480 		int pipe_offset = pipe * get_queues_per_pipe(dqm);
2481 
2482 		for (queue = 0; queue < get_queues_per_pipe(dqm); queue++) {
2483 			if (!test_bit(pipe_offset + queue,
2484 				      dqm->dev->shared_resources.cp_queue_bitmap))
2485 				continue;
2486 
2487 			r = dqm->dev->kfd2kgd->hqd_dump(
2488 				dqm->dev->adev, pipe, queue, &dump, &n_regs);
2489 			if (r)
2490 				break;
2491 
2492 			seq_printf(m, "  CP Pipe %d, Queue %d\n",
2493 				  pipe, queue);
2494 			seq_reg_dump(m, dump, n_regs);
2495 
2496 			kfree(dump);
2497 		}
2498 	}
2499 
2500 	for (pipe = 0; pipe < get_num_all_sdma_engines(dqm); pipe++) {
2501 		for (queue = 0;
2502 		     queue < dqm->dev->device_info.num_sdma_queues_per_engine;
2503 		     queue++) {
2504 			r = dqm->dev->kfd2kgd->hqd_sdma_dump(
2505 				dqm->dev->adev, pipe, queue, &dump, &n_regs);
2506 			if (r)
2507 				break;
2508 
2509 			seq_printf(m, "  SDMA Engine %d, RLC %d\n",
2510 				  pipe, queue);
2511 			seq_reg_dump(m, dump, n_regs);
2512 
2513 			kfree(dump);
2514 		}
2515 	}
2516 
2517 	return r;
2518 }
2519 
2520 int dqm_debugfs_hang_hws(struct device_queue_manager *dqm)
2521 {
2522 	int r = 0;
2523 
2524 	dqm_lock(dqm);
2525 	r = pm_debugfs_hang_hws(&dqm->packet_mgr);
2526 	if (r) {
2527 		dqm_unlock(dqm);
2528 		return r;
2529 	}
2530 	dqm->active_runlist = true;
2531 	r = execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0);
2532 	dqm_unlock(dqm);
2533 
2534 	return r;
2535 }
2536 
2537 #endif
2538