1 /*
2  * Copyright 2014 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  */
23 
24 #include <linux/ratelimit.h>
25 #include <linux/printk.h>
26 #include <linux/slab.h>
27 #include <linux/list.h>
28 #include <linux/types.h>
29 #include <linux/bitops.h>
30 #include <linux/sched.h>
31 #include "kfd_priv.h"
32 #include "kfd_device_queue_manager.h"
33 #include "kfd_mqd_manager.h"
34 #include "cik_regs.h"
35 #include "kfd_kernel_queue.h"
36 #include "amdgpu_amdkfd.h"
37 
38 /* Size of the per-pipe EOP queue */
39 #define CIK_HPD_EOP_BYTES_LOG2 11
40 #define CIK_HPD_EOP_BYTES (1U << CIK_HPD_EOP_BYTES_LOG2)
41 
42 static int set_pasid_vmid_mapping(struct device_queue_manager *dqm,
43 					unsigned int pasid, unsigned int vmid);
44 
45 static int execute_queues_cpsch(struct device_queue_manager *dqm,
46 				enum kfd_unmap_queues_filter filter,
47 				uint32_t filter_param);
48 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
49 				enum kfd_unmap_queues_filter filter,
50 				uint32_t filter_param);
51 
52 static int map_queues_cpsch(struct device_queue_manager *dqm);
53 
54 static void deallocate_sdma_queue(struct device_queue_manager *dqm,
55 				struct queue *q);
56 
57 static inline void deallocate_hqd(struct device_queue_manager *dqm,
58 				struct queue *q);
59 static int allocate_hqd(struct device_queue_manager *dqm, struct queue *q);
60 static int allocate_sdma_queue(struct device_queue_manager *dqm,
61 				struct queue *q);
62 static void kfd_process_hw_exception(struct work_struct *work);
63 
64 static inline
65 enum KFD_MQD_TYPE get_mqd_type_from_queue_type(enum kfd_queue_type type)
66 {
67 	if (type == KFD_QUEUE_TYPE_SDMA || type == KFD_QUEUE_TYPE_SDMA_XGMI)
68 		return KFD_MQD_TYPE_SDMA;
69 	return KFD_MQD_TYPE_CP;
70 }
71 
72 static bool is_pipe_enabled(struct device_queue_manager *dqm, int mec, int pipe)
73 {
74 	int i;
75 	int pipe_offset = mec * dqm->dev->shared_resources.num_pipe_per_mec
76 		+ pipe * dqm->dev->shared_resources.num_queue_per_pipe;
77 
78 	/* queue is available for KFD usage if bit is 1 */
79 	for (i = 0; i <  dqm->dev->shared_resources.num_queue_per_pipe; ++i)
80 		if (test_bit(pipe_offset + i,
81 			      dqm->dev->shared_resources.queue_bitmap))
82 			return true;
83 	return false;
84 }
85 
86 unsigned int get_queues_num(struct device_queue_manager *dqm)
87 {
88 	return bitmap_weight(dqm->dev->shared_resources.queue_bitmap,
89 				KGD_MAX_QUEUES);
90 }
91 
92 unsigned int get_queues_per_pipe(struct device_queue_manager *dqm)
93 {
94 	return dqm->dev->shared_resources.num_queue_per_pipe;
95 }
96 
97 unsigned int get_pipes_per_mec(struct device_queue_manager *dqm)
98 {
99 	return dqm->dev->shared_resources.num_pipe_per_mec;
100 }
101 
102 static unsigned int get_num_sdma_engines(struct device_queue_manager *dqm)
103 {
104 	return dqm->dev->device_info->num_sdma_engines;
105 }
106 
107 static unsigned int get_num_xgmi_sdma_engines(struct device_queue_manager *dqm)
108 {
109 	return dqm->dev->device_info->num_xgmi_sdma_engines;
110 }
111 
112 unsigned int get_num_sdma_queues(struct device_queue_manager *dqm)
113 {
114 	return dqm->dev->device_info->num_sdma_engines
115 			* dqm->dev->device_info->num_sdma_queues_per_engine;
116 }
117 
118 unsigned int get_num_xgmi_sdma_queues(struct device_queue_manager *dqm)
119 {
120 	return dqm->dev->device_info->num_xgmi_sdma_engines
121 			* dqm->dev->device_info->num_sdma_queues_per_engine;
122 }
123 
124 void program_sh_mem_settings(struct device_queue_manager *dqm,
125 					struct qcm_process_device *qpd)
126 {
127 	return dqm->dev->kfd2kgd->program_sh_mem_settings(
128 						dqm->dev->kgd, qpd->vmid,
129 						qpd->sh_mem_config,
130 						qpd->sh_mem_ape1_base,
131 						qpd->sh_mem_ape1_limit,
132 						qpd->sh_mem_bases);
133 }
134 
135 static int allocate_doorbell(struct qcm_process_device *qpd, struct queue *q)
136 {
137 	struct kfd_dev *dev = qpd->dqm->dev;
138 
139 	if (!KFD_IS_SOC15(dev->device_info->asic_family)) {
140 		/* On pre-SOC15 chips we need to use the queue ID to
141 		 * preserve the user mode ABI.
142 		 */
143 		q->doorbell_id = q->properties.queue_id;
144 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
145 			q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
146 		/* For SDMA queues on SOC15 with 8-byte doorbell, use static
147 		 * doorbell assignments based on the engine and queue id.
148 		 * The doobell index distance between RLC (2*i) and (2*i+1)
149 		 * for a SDMA engine is 512.
150 		 */
151 		uint32_t *idx_offset =
152 				dev->shared_resources.sdma_doorbell_idx;
153 
154 		q->doorbell_id = idx_offset[q->properties.sdma_engine_id]
155 			+ (q->properties.sdma_queue_id & 1)
156 			* KFD_QUEUE_DOORBELL_MIRROR_OFFSET
157 			+ (q->properties.sdma_queue_id >> 1);
158 	} else {
159 		/* For CP queues on SOC15 reserve a free doorbell ID */
160 		unsigned int found;
161 
162 		found = find_first_zero_bit(qpd->doorbell_bitmap,
163 					    KFD_MAX_NUM_OF_QUEUES_PER_PROCESS);
164 		if (found >= KFD_MAX_NUM_OF_QUEUES_PER_PROCESS) {
165 			pr_debug("No doorbells available");
166 			return -EBUSY;
167 		}
168 		set_bit(found, qpd->doorbell_bitmap);
169 		q->doorbell_id = found;
170 	}
171 
172 	q->properties.doorbell_off =
173 		kfd_doorbell_id_to_offset(dev, q->process,
174 					  q->doorbell_id);
175 
176 	return 0;
177 }
178 
179 static void deallocate_doorbell(struct qcm_process_device *qpd,
180 				struct queue *q)
181 {
182 	unsigned int old;
183 	struct kfd_dev *dev = qpd->dqm->dev;
184 
185 	if (!KFD_IS_SOC15(dev->device_info->asic_family) ||
186 	    q->properties.type == KFD_QUEUE_TYPE_SDMA ||
187 	    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
188 		return;
189 
190 	old = test_and_clear_bit(q->doorbell_id, qpd->doorbell_bitmap);
191 	WARN_ON(!old);
192 }
193 
194 static int allocate_vmid(struct device_queue_manager *dqm,
195 			struct qcm_process_device *qpd,
196 			struct queue *q)
197 {
198 	int allocated_vmid = -1, i;
199 
200 	for (i = dqm->dev->vm_info.first_vmid_kfd;
201 			i <= dqm->dev->vm_info.last_vmid_kfd; i++) {
202 		if (!dqm->vmid_pasid[i]) {
203 			allocated_vmid = i;
204 			break;
205 		}
206 	}
207 
208 	if (allocated_vmid < 0) {
209 		pr_err("no more vmid to allocate\n");
210 		return -ENOSPC;
211 	}
212 
213 	pr_debug("vmid allocated: %d\n", allocated_vmid);
214 
215 	dqm->vmid_pasid[allocated_vmid] = q->process->pasid;
216 
217 	set_pasid_vmid_mapping(dqm, q->process->pasid, allocated_vmid);
218 
219 	qpd->vmid = allocated_vmid;
220 	q->properties.vmid = allocated_vmid;
221 
222 	program_sh_mem_settings(dqm, qpd);
223 
224 	/* qpd->page_table_base is set earlier when register_process()
225 	 * is called, i.e. when the first queue is created.
226 	 */
227 	dqm->dev->kfd2kgd->set_vm_context_page_table_base(dqm->dev->kgd,
228 			qpd->vmid,
229 			qpd->page_table_base);
230 	/* invalidate the VM context after pasid and vmid mapping is set up */
231 	kfd_flush_tlb(qpd_to_pdd(qpd));
232 
233 	if (dqm->dev->kfd2kgd->set_scratch_backing_va)
234 		dqm->dev->kfd2kgd->set_scratch_backing_va(dqm->dev->kgd,
235 				qpd->sh_hidden_private_base, qpd->vmid);
236 
237 	return 0;
238 }
239 
240 static int flush_texture_cache_nocpsch(struct kfd_dev *kdev,
241 				struct qcm_process_device *qpd)
242 {
243 	const struct packet_manager_funcs *pmf = qpd->dqm->packets.pmf;
244 	int ret;
245 
246 	if (!qpd->ib_kaddr)
247 		return -ENOMEM;
248 
249 	ret = pmf->release_mem(qpd->ib_base, (uint32_t *)qpd->ib_kaddr);
250 	if (ret)
251 		return ret;
252 
253 	return amdgpu_amdkfd_submit_ib(kdev->kgd, KGD_ENGINE_MEC1, qpd->vmid,
254 				qpd->ib_base, (uint32_t *)qpd->ib_kaddr,
255 				pmf->release_mem_size / sizeof(uint32_t));
256 }
257 
258 static void deallocate_vmid(struct device_queue_manager *dqm,
259 				struct qcm_process_device *qpd,
260 				struct queue *q)
261 {
262 	/* On GFX v7, CP doesn't flush TC at dequeue */
263 	if (q->device->device_info->asic_family == CHIP_HAWAII)
264 		if (flush_texture_cache_nocpsch(q->device, qpd))
265 			pr_err("Failed to flush TC\n");
266 
267 	kfd_flush_tlb(qpd_to_pdd(qpd));
268 
269 	/* Release the vmid mapping */
270 	set_pasid_vmid_mapping(dqm, 0, qpd->vmid);
271 	dqm->vmid_pasid[qpd->vmid] = 0;
272 
273 	qpd->vmid = 0;
274 	q->properties.vmid = 0;
275 }
276 
277 static int create_queue_nocpsch(struct device_queue_manager *dqm,
278 				struct queue *q,
279 				struct qcm_process_device *qpd)
280 {
281 	struct mqd_manager *mqd_mgr;
282 	int retval;
283 
284 	print_queue(q);
285 
286 	dqm_lock(dqm);
287 
288 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
289 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
290 				dqm->total_queue_count);
291 		retval = -EPERM;
292 		goto out_unlock;
293 	}
294 
295 	if (list_empty(&qpd->queues_list)) {
296 		retval = allocate_vmid(dqm, qpd, q);
297 		if (retval)
298 			goto out_unlock;
299 	}
300 	q->properties.vmid = qpd->vmid;
301 	/*
302 	 * Eviction state logic: mark all queues as evicted, even ones
303 	 * not currently active. Restoring inactive queues later only
304 	 * updates the is_evicted flag but is a no-op otherwise.
305 	 */
306 	q->properties.is_evicted = !!qpd->evicted;
307 
308 	q->properties.tba_addr = qpd->tba_addr;
309 	q->properties.tma_addr = qpd->tma_addr;
310 
311 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
312 			q->properties.type)];
313 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE) {
314 		retval = allocate_hqd(dqm, q);
315 		if (retval)
316 			goto deallocate_vmid;
317 		pr_debug("Loading mqd to hqd on pipe %d, queue %d\n",
318 			q->pipe, q->queue);
319 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
320 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
321 		retval = allocate_sdma_queue(dqm, q);
322 		if (retval)
323 			goto deallocate_vmid;
324 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
325 	}
326 
327 	retval = allocate_doorbell(qpd, q);
328 	if (retval)
329 		goto out_deallocate_hqd;
330 
331 	/* Temporarily release dqm lock to avoid a circular lock dependency */
332 	dqm_unlock(dqm);
333 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr->dev, &q->properties);
334 	dqm_lock(dqm);
335 
336 	if (!q->mqd_mem_obj) {
337 		retval = -ENOMEM;
338 		goto out_deallocate_doorbell;
339 	}
340 	mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
341 				&q->gart_mqd_addr, &q->properties);
342 	if (q->properties.is_active) {
343 
344 		if (WARN(q->process->mm != current->mm,
345 					"should only run in user thread"))
346 			retval = -EFAULT;
347 		else
348 			retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd, q->pipe,
349 					q->queue, &q->properties, current->mm);
350 		if (retval)
351 			goto out_free_mqd;
352 	}
353 
354 	list_add(&q->list, &qpd->queues_list);
355 	qpd->queue_count++;
356 	if (q->properties.is_active)
357 		dqm->queue_count++;
358 
359 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
360 		dqm->sdma_queue_count++;
361 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
362 		dqm->xgmi_sdma_queue_count++;
363 
364 	/*
365 	 * Unconditionally increment this counter, regardless of the queue's
366 	 * type or whether the queue is active.
367 	 */
368 	dqm->total_queue_count++;
369 	pr_debug("Total of %d queues are accountable so far\n",
370 			dqm->total_queue_count);
371 	goto out_unlock;
372 
373 out_free_mqd:
374 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
375 out_deallocate_doorbell:
376 	deallocate_doorbell(qpd, q);
377 out_deallocate_hqd:
378 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE)
379 		deallocate_hqd(dqm, q);
380 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
381 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
382 		deallocate_sdma_queue(dqm, q);
383 deallocate_vmid:
384 	if (list_empty(&qpd->queues_list))
385 		deallocate_vmid(dqm, qpd, q);
386 out_unlock:
387 	dqm_unlock(dqm);
388 	return retval;
389 }
390 
391 static int allocate_hqd(struct device_queue_manager *dqm, struct queue *q)
392 {
393 	bool set;
394 	int pipe, bit, i;
395 
396 	set = false;
397 
398 	for (pipe = dqm->next_pipe_to_allocate, i = 0;
399 			i < get_pipes_per_mec(dqm);
400 			pipe = ((pipe + 1) % get_pipes_per_mec(dqm)), ++i) {
401 
402 		if (!is_pipe_enabled(dqm, 0, pipe))
403 			continue;
404 
405 		if (dqm->allocated_queues[pipe] != 0) {
406 			bit = ffs(dqm->allocated_queues[pipe]) - 1;
407 			dqm->allocated_queues[pipe] &= ~(1 << bit);
408 			q->pipe = pipe;
409 			q->queue = bit;
410 			set = true;
411 			break;
412 		}
413 	}
414 
415 	if (!set)
416 		return -EBUSY;
417 
418 	pr_debug("hqd slot - pipe %d, queue %d\n", q->pipe, q->queue);
419 	/* horizontal hqd allocation */
420 	dqm->next_pipe_to_allocate = (pipe + 1) % get_pipes_per_mec(dqm);
421 
422 	return 0;
423 }
424 
425 static inline void deallocate_hqd(struct device_queue_manager *dqm,
426 				struct queue *q)
427 {
428 	dqm->allocated_queues[q->pipe] |= (1 << q->queue);
429 }
430 
431 /* Access to DQM has to be locked before calling destroy_queue_nocpsch_locked
432  * to avoid asynchronized access
433  */
434 static int destroy_queue_nocpsch_locked(struct device_queue_manager *dqm,
435 				struct qcm_process_device *qpd,
436 				struct queue *q)
437 {
438 	int retval;
439 	struct mqd_manager *mqd_mgr;
440 
441 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
442 			q->properties.type)];
443 
444 	if (q->properties.type == KFD_QUEUE_TYPE_COMPUTE) {
445 		deallocate_hqd(dqm, q);
446 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
447 		dqm->sdma_queue_count--;
448 		deallocate_sdma_queue(dqm, q);
449 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
450 		dqm->xgmi_sdma_queue_count--;
451 		deallocate_sdma_queue(dqm, q);
452 	} else {
453 		pr_debug("q->properties.type %d is invalid\n",
454 				q->properties.type);
455 		return -EINVAL;
456 	}
457 	dqm->total_queue_count--;
458 
459 	deallocate_doorbell(qpd, q);
460 
461 	retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
462 				KFD_PREEMPT_TYPE_WAVEFRONT_RESET,
463 				KFD_UNMAP_LATENCY_MS,
464 				q->pipe, q->queue);
465 	if (retval == -ETIME)
466 		qpd->reset_wavefronts = true;
467 
468 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
469 
470 	list_del(&q->list);
471 	if (list_empty(&qpd->queues_list)) {
472 		if (qpd->reset_wavefronts) {
473 			pr_warn("Resetting wave fronts (nocpsch) on dev %p\n",
474 					dqm->dev);
475 			/* dbgdev_wave_reset_wavefronts has to be called before
476 			 * deallocate_vmid(), i.e. when vmid is still in use.
477 			 */
478 			dbgdev_wave_reset_wavefronts(dqm->dev,
479 					qpd->pqm->process);
480 			qpd->reset_wavefronts = false;
481 		}
482 
483 		deallocate_vmid(dqm, qpd, q);
484 	}
485 	qpd->queue_count--;
486 	if (q->properties.is_active)
487 		dqm->queue_count--;
488 
489 	return retval;
490 }
491 
492 static int destroy_queue_nocpsch(struct device_queue_manager *dqm,
493 				struct qcm_process_device *qpd,
494 				struct queue *q)
495 {
496 	int retval;
497 
498 	dqm_lock(dqm);
499 	retval = destroy_queue_nocpsch_locked(dqm, qpd, q);
500 	dqm_unlock(dqm);
501 
502 	return retval;
503 }
504 
505 static int update_queue(struct device_queue_manager *dqm, struct queue *q)
506 {
507 	int retval = 0;
508 	struct mqd_manager *mqd_mgr;
509 	struct kfd_process_device *pdd;
510 	bool prev_active = false;
511 
512 	dqm_lock(dqm);
513 	pdd = kfd_get_process_device_data(q->device, q->process);
514 	if (!pdd) {
515 		retval = -ENODEV;
516 		goto out_unlock;
517 	}
518 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
519 			q->properties.type)];
520 
521 	/* Save previous activity state for counters */
522 	prev_active = q->properties.is_active;
523 
524 	/* Make sure the queue is unmapped before updating the MQD */
525 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS) {
526 		retval = unmap_queues_cpsch(dqm,
527 				KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
528 		if (retval) {
529 			pr_err("unmap queue failed\n");
530 			goto out_unlock;
531 		}
532 	} else if (prev_active &&
533 		   (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
534 		    q->properties.type == KFD_QUEUE_TYPE_SDMA ||
535 		    q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
536 		retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
537 				KFD_PREEMPT_TYPE_WAVEFRONT_DRAIN,
538 				KFD_UNMAP_LATENCY_MS, q->pipe, q->queue);
539 		if (retval) {
540 			pr_err("destroy mqd failed\n");
541 			goto out_unlock;
542 		}
543 	}
544 
545 	mqd_mgr->update_mqd(mqd_mgr, q->mqd, &q->properties);
546 
547 	/*
548 	 * check active state vs. the previous state and modify
549 	 * counter accordingly. map_queues_cpsch uses the
550 	 * dqm->queue_count to determine whether a new runlist must be
551 	 * uploaded.
552 	 */
553 	if (q->properties.is_active && !prev_active)
554 		dqm->queue_count++;
555 	else if (!q->properties.is_active && prev_active)
556 		dqm->queue_count--;
557 
558 	if (dqm->sched_policy != KFD_SCHED_POLICY_NO_HWS)
559 		retval = map_queues_cpsch(dqm);
560 	else if (q->properties.is_active &&
561 		 (q->properties.type == KFD_QUEUE_TYPE_COMPUTE ||
562 		  q->properties.type == KFD_QUEUE_TYPE_SDMA ||
563 		  q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)) {
564 		if (WARN(q->process->mm != current->mm,
565 			 "should only run in user thread"))
566 			retval = -EFAULT;
567 		else
568 			retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd,
569 						   q->pipe, q->queue,
570 						   &q->properties, current->mm);
571 	}
572 
573 out_unlock:
574 	dqm_unlock(dqm);
575 	return retval;
576 }
577 
578 static int evict_process_queues_nocpsch(struct device_queue_manager *dqm,
579 					struct qcm_process_device *qpd)
580 {
581 	struct queue *q;
582 	struct mqd_manager *mqd_mgr;
583 	struct kfd_process_device *pdd;
584 	int retval, ret = 0;
585 
586 	dqm_lock(dqm);
587 	if (qpd->evicted++ > 0) /* already evicted, do nothing */
588 		goto out;
589 
590 	pdd = qpd_to_pdd(qpd);
591 	pr_info_ratelimited("Evicting PASID 0x%x queues\n",
592 			    pdd->process->pasid);
593 
594 	/* Mark all queues as evicted. Deactivate all active queues on
595 	 * the qpd.
596 	 */
597 	list_for_each_entry(q, &qpd->queues_list, list) {
598 		q->properties.is_evicted = true;
599 		if (!q->properties.is_active)
600 			continue;
601 
602 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
603 				q->properties.type)];
604 		q->properties.is_active = false;
605 		retval = mqd_mgr->destroy_mqd(mqd_mgr, q->mqd,
606 				KFD_PREEMPT_TYPE_WAVEFRONT_DRAIN,
607 				KFD_UNMAP_LATENCY_MS, q->pipe, q->queue);
608 		if (retval && !ret)
609 			/* Return the first error, but keep going to
610 			 * maintain a consistent eviction state
611 			 */
612 			ret = retval;
613 		dqm->queue_count--;
614 	}
615 
616 out:
617 	dqm_unlock(dqm);
618 	return ret;
619 }
620 
621 static int evict_process_queues_cpsch(struct device_queue_manager *dqm,
622 				      struct qcm_process_device *qpd)
623 {
624 	struct queue *q;
625 	struct kfd_process_device *pdd;
626 	int retval = 0;
627 
628 	dqm_lock(dqm);
629 	if (qpd->evicted++ > 0) /* already evicted, do nothing */
630 		goto out;
631 
632 	pdd = qpd_to_pdd(qpd);
633 	pr_info_ratelimited("Evicting PASID 0x%x queues\n",
634 			    pdd->process->pasid);
635 
636 	/* Mark all queues as evicted. Deactivate all active queues on
637 	 * the qpd.
638 	 */
639 	list_for_each_entry(q, &qpd->queues_list, list) {
640 		q->properties.is_evicted = true;
641 		if (!q->properties.is_active)
642 			continue;
643 
644 		q->properties.is_active = false;
645 		dqm->queue_count--;
646 	}
647 	retval = execute_queues_cpsch(dqm,
648 				qpd->is_debug ?
649 				KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES :
650 				KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
651 
652 out:
653 	dqm_unlock(dqm);
654 	return retval;
655 }
656 
657 static int restore_process_queues_nocpsch(struct device_queue_manager *dqm,
658 					  struct qcm_process_device *qpd)
659 {
660 	struct mm_struct *mm = NULL;
661 	struct queue *q;
662 	struct mqd_manager *mqd_mgr;
663 	struct kfd_process_device *pdd;
664 	uint64_t pd_base;
665 	int retval, ret = 0;
666 
667 	pdd = qpd_to_pdd(qpd);
668 	/* Retrieve PD base */
669 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->vm);
670 
671 	dqm_lock(dqm);
672 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
673 		goto out;
674 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
675 		qpd->evicted--;
676 		goto out;
677 	}
678 
679 	pr_info_ratelimited("Restoring PASID 0x%x queues\n",
680 			    pdd->process->pasid);
681 
682 	/* Update PD Base in QPD */
683 	qpd->page_table_base = pd_base;
684 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
685 
686 	if (!list_empty(&qpd->queues_list)) {
687 		dqm->dev->kfd2kgd->set_vm_context_page_table_base(
688 				dqm->dev->kgd,
689 				qpd->vmid,
690 				qpd->page_table_base);
691 		kfd_flush_tlb(pdd);
692 	}
693 
694 	/* Take a safe reference to the mm_struct, which may otherwise
695 	 * disappear even while the kfd_process is still referenced.
696 	 */
697 	mm = get_task_mm(pdd->process->lead_thread);
698 	if (!mm) {
699 		ret = -EFAULT;
700 		goto out;
701 	}
702 
703 	/* Remove the eviction flags. Activate queues that are not
704 	 * inactive for other reasons.
705 	 */
706 	list_for_each_entry(q, &qpd->queues_list, list) {
707 		q->properties.is_evicted = false;
708 		if (!QUEUE_IS_ACTIVE(q->properties))
709 			continue;
710 
711 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
712 				q->properties.type)];
713 		q->properties.is_active = true;
714 		retval = mqd_mgr->load_mqd(mqd_mgr, q->mqd, q->pipe,
715 				       q->queue, &q->properties, mm);
716 		if (retval && !ret)
717 			/* Return the first error, but keep going to
718 			 * maintain a consistent eviction state
719 			 */
720 			ret = retval;
721 		dqm->queue_count++;
722 	}
723 	qpd->evicted = 0;
724 out:
725 	if (mm)
726 		mmput(mm);
727 	dqm_unlock(dqm);
728 	return ret;
729 }
730 
731 static int restore_process_queues_cpsch(struct device_queue_manager *dqm,
732 					struct qcm_process_device *qpd)
733 {
734 	struct queue *q;
735 	struct kfd_process_device *pdd;
736 	uint64_t pd_base;
737 	int retval = 0;
738 
739 	pdd = qpd_to_pdd(qpd);
740 	/* Retrieve PD base */
741 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->vm);
742 
743 	dqm_lock(dqm);
744 	if (WARN_ON_ONCE(!qpd->evicted)) /* already restored, do nothing */
745 		goto out;
746 	if (qpd->evicted > 1) { /* ref count still > 0, decrement & quit */
747 		qpd->evicted--;
748 		goto out;
749 	}
750 
751 	pr_info_ratelimited("Restoring PASID 0x%x queues\n",
752 			    pdd->process->pasid);
753 
754 	/* Update PD Base in QPD */
755 	qpd->page_table_base = pd_base;
756 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
757 
758 	/* activate all active queues on the qpd */
759 	list_for_each_entry(q, &qpd->queues_list, list) {
760 		q->properties.is_evicted = false;
761 		if (!QUEUE_IS_ACTIVE(q->properties))
762 			continue;
763 
764 		q->properties.is_active = true;
765 		dqm->queue_count++;
766 	}
767 	retval = execute_queues_cpsch(dqm,
768 				KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
769 	qpd->evicted = 0;
770 out:
771 	dqm_unlock(dqm);
772 	return retval;
773 }
774 
775 static int register_process(struct device_queue_manager *dqm,
776 					struct qcm_process_device *qpd)
777 {
778 	struct device_process_node *n;
779 	struct kfd_process_device *pdd;
780 	uint64_t pd_base;
781 	int retval;
782 
783 	n = kzalloc(sizeof(*n), GFP_KERNEL);
784 	if (!n)
785 		return -ENOMEM;
786 
787 	n->qpd = qpd;
788 
789 	pdd = qpd_to_pdd(qpd);
790 	/* Retrieve PD base */
791 	pd_base = amdgpu_amdkfd_gpuvm_get_process_page_dir(pdd->vm);
792 
793 	dqm_lock(dqm);
794 	list_add(&n->list, &dqm->queues);
795 
796 	/* Update PD Base in QPD */
797 	qpd->page_table_base = pd_base;
798 	pr_debug("Updated PD address to 0x%llx\n", pd_base);
799 
800 	retval = dqm->asic_ops.update_qpd(dqm, qpd);
801 
802 	dqm->processes_count++;
803 
804 	dqm_unlock(dqm);
805 
806 	/* Outside the DQM lock because under the DQM lock we can't do
807 	 * reclaim or take other locks that others hold while reclaiming.
808 	 */
809 	kfd_inc_compute_active(dqm->dev);
810 
811 	return retval;
812 }
813 
814 static int unregister_process(struct device_queue_manager *dqm,
815 					struct qcm_process_device *qpd)
816 {
817 	int retval;
818 	struct device_process_node *cur, *next;
819 
820 	pr_debug("qpd->queues_list is %s\n",
821 			list_empty(&qpd->queues_list) ? "empty" : "not empty");
822 
823 	retval = 0;
824 	dqm_lock(dqm);
825 
826 	list_for_each_entry_safe(cur, next, &dqm->queues, list) {
827 		if (qpd == cur->qpd) {
828 			list_del(&cur->list);
829 			kfree(cur);
830 			dqm->processes_count--;
831 			goto out;
832 		}
833 	}
834 	/* qpd not found in dqm list */
835 	retval = 1;
836 out:
837 	dqm_unlock(dqm);
838 
839 	/* Outside the DQM lock because under the DQM lock we can't do
840 	 * reclaim or take other locks that others hold while reclaiming.
841 	 */
842 	if (!retval)
843 		kfd_dec_compute_active(dqm->dev);
844 
845 	return retval;
846 }
847 
848 static int
849 set_pasid_vmid_mapping(struct device_queue_manager *dqm, unsigned int pasid,
850 			unsigned int vmid)
851 {
852 	return dqm->dev->kfd2kgd->set_pasid_vmid_mapping(
853 						dqm->dev->kgd, pasid, vmid);
854 }
855 
856 static void init_interrupts(struct device_queue_manager *dqm)
857 {
858 	unsigned int i;
859 
860 	for (i = 0 ; i < get_pipes_per_mec(dqm) ; i++)
861 		if (is_pipe_enabled(dqm, 0, i))
862 			dqm->dev->kfd2kgd->init_interrupts(dqm->dev->kgd, i);
863 }
864 
865 static int initialize_nocpsch(struct device_queue_manager *dqm)
866 {
867 	int pipe, queue;
868 
869 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
870 
871 	dqm->allocated_queues = kcalloc(get_pipes_per_mec(dqm),
872 					sizeof(unsigned int), GFP_KERNEL);
873 	if (!dqm->allocated_queues)
874 		return -ENOMEM;
875 
876 	mutex_init(&dqm->lock_hidden);
877 	INIT_LIST_HEAD(&dqm->queues);
878 	dqm->queue_count = dqm->next_pipe_to_allocate = 0;
879 	dqm->sdma_queue_count = 0;
880 	dqm->xgmi_sdma_queue_count = 0;
881 
882 	for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
883 		int pipe_offset = pipe * get_queues_per_pipe(dqm);
884 
885 		for (queue = 0; queue < get_queues_per_pipe(dqm); queue++)
886 			if (test_bit(pipe_offset + queue,
887 				     dqm->dev->shared_resources.queue_bitmap))
888 				dqm->allocated_queues[pipe] |= 1 << queue;
889 	}
890 
891 	memset(dqm->vmid_pasid, 0, sizeof(dqm->vmid_pasid));
892 
893 	dqm->sdma_bitmap = ~0ULL >> (64 - get_num_sdma_queues(dqm));
894 	dqm->xgmi_sdma_bitmap = ~0ULL >> (64 - get_num_xgmi_sdma_queues(dqm));
895 
896 	return 0;
897 }
898 
899 static void uninitialize(struct device_queue_manager *dqm)
900 {
901 	int i;
902 
903 	WARN_ON(dqm->queue_count > 0 || dqm->processes_count > 0);
904 
905 	kfree(dqm->allocated_queues);
906 	for (i = 0 ; i < KFD_MQD_TYPE_MAX ; i++)
907 		kfree(dqm->mqd_mgrs[i]);
908 	mutex_destroy(&dqm->lock_hidden);
909 	kfd_gtt_sa_free(dqm->dev, dqm->pipeline_mem);
910 }
911 
912 static int start_nocpsch(struct device_queue_manager *dqm)
913 {
914 	init_interrupts(dqm);
915 
916 	if (dqm->dev->device_info->asic_family == CHIP_HAWAII)
917 		return pm_init(&dqm->packets, dqm);
918 
919 	return 0;
920 }
921 
922 static int stop_nocpsch(struct device_queue_manager *dqm)
923 {
924 	if (dqm->dev->device_info->asic_family == CHIP_HAWAII)
925 		pm_uninit(&dqm->packets);
926 
927 	return 0;
928 }
929 
930 static int allocate_sdma_queue(struct device_queue_manager *dqm,
931 				struct queue *q)
932 {
933 	int bit;
934 
935 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
936 		if (dqm->sdma_bitmap == 0)
937 			return -ENOMEM;
938 		bit = __ffs64(dqm->sdma_bitmap);
939 		dqm->sdma_bitmap &= ~(1ULL << bit);
940 		q->sdma_id = bit;
941 		q->properties.sdma_engine_id = q->sdma_id %
942 				get_num_sdma_engines(dqm);
943 		q->properties.sdma_queue_id = q->sdma_id /
944 				get_num_sdma_engines(dqm);
945 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
946 		if (dqm->xgmi_sdma_bitmap == 0)
947 			return -ENOMEM;
948 		bit = __ffs64(dqm->xgmi_sdma_bitmap);
949 		dqm->xgmi_sdma_bitmap &= ~(1ULL << bit);
950 		q->sdma_id = bit;
951 		/* sdma_engine_id is sdma id including
952 		 * both PCIe-optimized SDMAs and XGMI-
953 		 * optimized SDMAs. The calculation below
954 		 * assumes the first N engines are always
955 		 * PCIe-optimized ones
956 		 */
957 		q->properties.sdma_engine_id = get_num_sdma_engines(dqm) +
958 				q->sdma_id % get_num_xgmi_sdma_engines(dqm);
959 		q->properties.sdma_queue_id = q->sdma_id /
960 				get_num_xgmi_sdma_engines(dqm);
961 	}
962 
963 	pr_debug("SDMA engine id: %d\n", q->properties.sdma_engine_id);
964 	pr_debug("SDMA queue id: %d\n", q->properties.sdma_queue_id);
965 
966 	return 0;
967 }
968 
969 static void deallocate_sdma_queue(struct device_queue_manager *dqm,
970 				struct queue *q)
971 {
972 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
973 		if (q->sdma_id >= get_num_sdma_queues(dqm))
974 			return;
975 		dqm->sdma_bitmap |= (1ULL << q->sdma_id);
976 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
977 		if (q->sdma_id >= get_num_xgmi_sdma_queues(dqm))
978 			return;
979 		dqm->xgmi_sdma_bitmap |= (1ULL << q->sdma_id);
980 	}
981 }
982 
983 /*
984  * Device Queue Manager implementation for cp scheduler
985  */
986 
987 static int set_sched_resources(struct device_queue_manager *dqm)
988 {
989 	int i, mec;
990 	struct scheduling_resources res;
991 
992 	res.vmid_mask = dqm->dev->shared_resources.compute_vmid_bitmap;
993 
994 	res.queue_mask = 0;
995 	for (i = 0; i < KGD_MAX_QUEUES; ++i) {
996 		mec = (i / dqm->dev->shared_resources.num_queue_per_pipe)
997 			/ dqm->dev->shared_resources.num_pipe_per_mec;
998 
999 		if (!test_bit(i, dqm->dev->shared_resources.queue_bitmap))
1000 			continue;
1001 
1002 		/* only acquire queues from the first MEC */
1003 		if (mec > 0)
1004 			continue;
1005 
1006 		/* This situation may be hit in the future if a new HW
1007 		 * generation exposes more than 64 queues. If so, the
1008 		 * definition of res.queue_mask needs updating
1009 		 */
1010 		if (WARN_ON(i >= (sizeof(res.queue_mask)*8))) {
1011 			pr_err("Invalid queue enabled by amdgpu: %d\n", i);
1012 			break;
1013 		}
1014 
1015 		res.queue_mask |= (1ull << i);
1016 	}
1017 	res.gws_mask = ~0ull;
1018 	res.oac_mask = res.gds_heap_base = res.gds_heap_size = 0;
1019 
1020 	pr_debug("Scheduling resources:\n"
1021 			"vmid mask: 0x%8X\n"
1022 			"queue mask: 0x%8llX\n",
1023 			res.vmid_mask, res.queue_mask);
1024 
1025 	return pm_send_set_resources(&dqm->packets, &res);
1026 }
1027 
1028 static int initialize_cpsch(struct device_queue_manager *dqm)
1029 {
1030 	pr_debug("num of pipes: %d\n", get_pipes_per_mec(dqm));
1031 
1032 	mutex_init(&dqm->lock_hidden);
1033 	INIT_LIST_HEAD(&dqm->queues);
1034 	dqm->queue_count = dqm->processes_count = 0;
1035 	dqm->sdma_queue_count = 0;
1036 	dqm->xgmi_sdma_queue_count = 0;
1037 	dqm->active_runlist = false;
1038 	dqm->sdma_bitmap = ~0ULL >> (64 - get_num_sdma_queues(dqm));
1039 	dqm->xgmi_sdma_bitmap = ~0ULL >> (64 - get_num_xgmi_sdma_queues(dqm));
1040 
1041 	INIT_WORK(&dqm->hw_exception_work, kfd_process_hw_exception);
1042 
1043 	return 0;
1044 }
1045 
1046 static int start_cpsch(struct device_queue_manager *dqm)
1047 {
1048 	int retval;
1049 
1050 	retval = 0;
1051 
1052 	retval = pm_init(&dqm->packets, dqm);
1053 	if (retval)
1054 		goto fail_packet_manager_init;
1055 
1056 	retval = set_sched_resources(dqm);
1057 	if (retval)
1058 		goto fail_set_sched_resources;
1059 
1060 	pr_debug("Allocating fence memory\n");
1061 
1062 	/* allocate fence memory on the gart */
1063 	retval = kfd_gtt_sa_allocate(dqm->dev, sizeof(*dqm->fence_addr),
1064 					&dqm->fence_mem);
1065 
1066 	if (retval)
1067 		goto fail_allocate_vidmem;
1068 
1069 	dqm->fence_addr = dqm->fence_mem->cpu_ptr;
1070 	dqm->fence_gpu_addr = dqm->fence_mem->gpu_addr;
1071 
1072 	init_interrupts(dqm);
1073 
1074 	dqm_lock(dqm);
1075 	/* clear hang status when driver try to start the hw scheduler */
1076 	dqm->is_hws_hang = false;
1077 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1078 	dqm_unlock(dqm);
1079 
1080 	return 0;
1081 fail_allocate_vidmem:
1082 fail_set_sched_resources:
1083 	pm_uninit(&dqm->packets);
1084 fail_packet_manager_init:
1085 	return retval;
1086 }
1087 
1088 static int stop_cpsch(struct device_queue_manager *dqm)
1089 {
1090 	dqm_lock(dqm);
1091 	unmap_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0);
1092 	dqm_unlock(dqm);
1093 
1094 	kfd_gtt_sa_free(dqm->dev, dqm->fence_mem);
1095 	pm_uninit(&dqm->packets);
1096 
1097 	return 0;
1098 }
1099 
1100 static int create_kernel_queue_cpsch(struct device_queue_manager *dqm,
1101 					struct kernel_queue *kq,
1102 					struct qcm_process_device *qpd)
1103 {
1104 	dqm_lock(dqm);
1105 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1106 		pr_warn("Can't create new kernel queue because %d queues were already created\n",
1107 				dqm->total_queue_count);
1108 		dqm_unlock(dqm);
1109 		return -EPERM;
1110 	}
1111 
1112 	/*
1113 	 * Unconditionally increment this counter, regardless of the queue's
1114 	 * type or whether the queue is active.
1115 	 */
1116 	dqm->total_queue_count++;
1117 	pr_debug("Total of %d queues are accountable so far\n",
1118 			dqm->total_queue_count);
1119 
1120 	list_add(&kq->list, &qpd->priv_queue_list);
1121 	dqm->queue_count++;
1122 	qpd->is_debug = true;
1123 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1124 	dqm_unlock(dqm);
1125 
1126 	return 0;
1127 }
1128 
1129 static void destroy_kernel_queue_cpsch(struct device_queue_manager *dqm,
1130 					struct kernel_queue *kq,
1131 					struct qcm_process_device *qpd)
1132 {
1133 	dqm_lock(dqm);
1134 	list_del(&kq->list);
1135 	dqm->queue_count--;
1136 	qpd->is_debug = false;
1137 	execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0);
1138 	/*
1139 	 * Unconditionally decrement this counter, regardless of the queue's
1140 	 * type.
1141 	 */
1142 	dqm->total_queue_count--;
1143 	pr_debug("Total of %d queues are accountable so far\n",
1144 			dqm->total_queue_count);
1145 	dqm_unlock(dqm);
1146 }
1147 
1148 static int create_queue_cpsch(struct device_queue_manager *dqm, struct queue *q,
1149 			struct qcm_process_device *qpd)
1150 {
1151 	int retval;
1152 	struct mqd_manager *mqd_mgr;
1153 
1154 	if (dqm->total_queue_count >= max_num_of_queues_per_device) {
1155 		pr_warn("Can't create new usermode queue because %d queues were already created\n",
1156 				dqm->total_queue_count);
1157 		retval = -EPERM;
1158 		goto out;
1159 	}
1160 
1161 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1162 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1163 		dqm_lock(dqm);
1164 		retval = allocate_sdma_queue(dqm, q);
1165 		dqm_unlock(dqm);
1166 		if (retval)
1167 			goto out;
1168 	}
1169 
1170 	retval = allocate_doorbell(qpd, q);
1171 	if (retval)
1172 		goto out_deallocate_sdma_queue;
1173 
1174 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1175 			q->properties.type)];
1176 
1177 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1178 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
1179 		dqm->asic_ops.init_sdma_vm(dqm, q, qpd);
1180 	q->properties.tba_addr = qpd->tba_addr;
1181 	q->properties.tma_addr = qpd->tma_addr;
1182 	q->mqd_mem_obj = mqd_mgr->allocate_mqd(mqd_mgr->dev, &q->properties);
1183 	if (!q->mqd_mem_obj) {
1184 		retval = -ENOMEM;
1185 		goto out_deallocate_doorbell;
1186 	}
1187 
1188 	dqm_lock(dqm);
1189 	/*
1190 	 * Eviction state logic: mark all queues as evicted, even ones
1191 	 * not currently active. Restoring inactive queues later only
1192 	 * updates the is_evicted flag but is a no-op otherwise.
1193 	 */
1194 	q->properties.is_evicted = !!qpd->evicted;
1195 	mqd_mgr->init_mqd(mqd_mgr, &q->mqd, q->mqd_mem_obj,
1196 				&q->gart_mqd_addr, &q->properties);
1197 
1198 	list_add(&q->list, &qpd->queues_list);
1199 	qpd->queue_count++;
1200 	if (q->properties.is_active) {
1201 		dqm->queue_count++;
1202 		retval = execute_queues_cpsch(dqm,
1203 				KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1204 	}
1205 
1206 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA)
1207 		dqm->sdma_queue_count++;
1208 	else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI)
1209 		dqm->xgmi_sdma_queue_count++;
1210 	/*
1211 	 * Unconditionally increment this counter, regardless of the queue's
1212 	 * type or whether the queue is active.
1213 	 */
1214 	dqm->total_queue_count++;
1215 
1216 	pr_debug("Total of %d queues are accountable so far\n",
1217 			dqm->total_queue_count);
1218 
1219 	dqm_unlock(dqm);
1220 	return retval;
1221 
1222 out_deallocate_doorbell:
1223 	deallocate_doorbell(qpd, q);
1224 out_deallocate_sdma_queue:
1225 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA ||
1226 		q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1227 		dqm_lock(dqm);
1228 		deallocate_sdma_queue(dqm, q);
1229 		dqm_unlock(dqm);
1230 	}
1231 out:
1232 	return retval;
1233 }
1234 
1235 int amdkfd_fence_wait_timeout(unsigned int *fence_addr,
1236 				unsigned int fence_value,
1237 				unsigned int timeout_ms)
1238 {
1239 	unsigned long end_jiffies = msecs_to_jiffies(timeout_ms) + jiffies;
1240 
1241 	while (*fence_addr != fence_value) {
1242 		if (time_after(jiffies, end_jiffies)) {
1243 			pr_err("qcm fence wait loop timeout expired\n");
1244 			/* In HWS case, this is used to halt the driver thread
1245 			 * in order not to mess up CP states before doing
1246 			 * scandumps for FW debugging.
1247 			 */
1248 			while (halt_if_hws_hang)
1249 				schedule();
1250 
1251 			return -ETIME;
1252 		}
1253 		schedule();
1254 	}
1255 
1256 	return 0;
1257 }
1258 
1259 static int unmap_sdma_queues(struct device_queue_manager *dqm)
1260 {
1261 	int i, retval = 0;
1262 
1263 	for (i = 0; i < dqm->dev->device_info->num_sdma_engines +
1264 		dqm->dev->device_info->num_xgmi_sdma_engines; i++) {
1265 		retval = pm_send_unmap_queue(&dqm->packets, KFD_QUEUE_TYPE_SDMA,
1266 			KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0, false, i);
1267 		if (retval)
1268 			return retval;
1269 	}
1270 	return retval;
1271 }
1272 
1273 /* dqm->lock mutex has to be locked before calling this function */
1274 static int map_queues_cpsch(struct device_queue_manager *dqm)
1275 {
1276 	int retval;
1277 
1278 	if (dqm->queue_count <= 0 || dqm->processes_count <= 0)
1279 		return 0;
1280 
1281 	if (dqm->active_runlist)
1282 		return 0;
1283 
1284 	retval = pm_send_runlist(&dqm->packets, &dqm->queues);
1285 	pr_debug("%s sent runlist\n", __func__);
1286 	if (retval) {
1287 		pr_err("failed to execute runlist\n");
1288 		return retval;
1289 	}
1290 	dqm->active_runlist = true;
1291 
1292 	return retval;
1293 }
1294 
1295 /* dqm->lock mutex has to be locked before calling this function */
1296 static int unmap_queues_cpsch(struct device_queue_manager *dqm,
1297 				enum kfd_unmap_queues_filter filter,
1298 				uint32_t filter_param)
1299 {
1300 	int retval = 0;
1301 
1302 	if (dqm->is_hws_hang)
1303 		return -EIO;
1304 	if (!dqm->active_runlist)
1305 		return retval;
1306 
1307 	pr_debug("Before destroying queues, sdma queue count is : %u, xgmi sdma queue count is : %u\n",
1308 		dqm->sdma_queue_count, dqm->xgmi_sdma_queue_count);
1309 
1310 	if (dqm->sdma_queue_count > 0 || dqm->xgmi_sdma_queue_count)
1311 		unmap_sdma_queues(dqm);
1312 
1313 	retval = pm_send_unmap_queue(&dqm->packets, KFD_QUEUE_TYPE_COMPUTE,
1314 			filter, filter_param, false, 0);
1315 	if (retval)
1316 		return retval;
1317 
1318 	*dqm->fence_addr = KFD_FENCE_INIT;
1319 	pm_send_query_status(&dqm->packets, dqm->fence_gpu_addr,
1320 				KFD_FENCE_COMPLETED);
1321 	/* should be timed out */
1322 	retval = amdkfd_fence_wait_timeout(dqm->fence_addr, KFD_FENCE_COMPLETED,
1323 				queue_preemption_timeout_ms);
1324 	if (retval)
1325 		return retval;
1326 
1327 	pm_release_ib(&dqm->packets);
1328 	dqm->active_runlist = false;
1329 
1330 	return retval;
1331 }
1332 
1333 /* dqm->lock mutex has to be locked before calling this function */
1334 static int execute_queues_cpsch(struct device_queue_manager *dqm,
1335 				enum kfd_unmap_queues_filter filter,
1336 				uint32_t filter_param)
1337 {
1338 	int retval;
1339 
1340 	if (dqm->is_hws_hang)
1341 		return -EIO;
1342 	retval = unmap_queues_cpsch(dqm, filter, filter_param);
1343 	if (retval) {
1344 		pr_err("The cp might be in an unrecoverable state due to an unsuccessful queues preemption\n");
1345 		dqm->is_hws_hang = true;
1346 		schedule_work(&dqm->hw_exception_work);
1347 		return retval;
1348 	}
1349 
1350 	return map_queues_cpsch(dqm);
1351 }
1352 
1353 static int destroy_queue_cpsch(struct device_queue_manager *dqm,
1354 				struct qcm_process_device *qpd,
1355 				struct queue *q)
1356 {
1357 	int retval;
1358 	struct mqd_manager *mqd_mgr;
1359 
1360 	retval = 0;
1361 
1362 	/* remove queue from list to prevent rescheduling after preemption */
1363 	dqm_lock(dqm);
1364 
1365 	if (qpd->is_debug) {
1366 		/*
1367 		 * error, currently we do not allow to destroy a queue
1368 		 * of a currently debugged process
1369 		 */
1370 		retval = -EBUSY;
1371 		goto failed_try_destroy_debugged_queue;
1372 
1373 	}
1374 
1375 	mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1376 			q->properties.type)];
1377 
1378 	deallocate_doorbell(qpd, q);
1379 
1380 	if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1381 		dqm->sdma_queue_count--;
1382 		deallocate_sdma_queue(dqm, q);
1383 	} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1384 		dqm->xgmi_sdma_queue_count--;
1385 		deallocate_sdma_queue(dqm, q);
1386 	}
1387 
1388 	list_del(&q->list);
1389 	qpd->queue_count--;
1390 	if (q->properties.is_active) {
1391 		dqm->queue_count--;
1392 		retval = execute_queues_cpsch(dqm,
1393 				KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES, 0);
1394 		if (retval == -ETIME)
1395 			qpd->reset_wavefronts = true;
1396 	}
1397 
1398 	/*
1399 	 * Unconditionally decrement this counter, regardless of the queue's
1400 	 * type
1401 	 */
1402 	dqm->total_queue_count--;
1403 	pr_debug("Total of %d queues are accountable so far\n",
1404 			dqm->total_queue_count);
1405 
1406 	dqm_unlock(dqm);
1407 
1408 	/* Do free_mqd after dqm_unlock(dqm) to avoid circular locking */
1409 	mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
1410 
1411 	return retval;
1412 
1413 failed_try_destroy_debugged_queue:
1414 
1415 	dqm_unlock(dqm);
1416 	return retval;
1417 }
1418 
1419 /*
1420  * Low bits must be 0000/FFFF as required by HW, high bits must be 0 to
1421  * stay in user mode.
1422  */
1423 #define APE1_FIXED_BITS_MASK 0xFFFF80000000FFFFULL
1424 /* APE1 limit is inclusive and 64K aligned. */
1425 #define APE1_LIMIT_ALIGNMENT 0xFFFF
1426 
1427 static bool set_cache_memory_policy(struct device_queue_manager *dqm,
1428 				   struct qcm_process_device *qpd,
1429 				   enum cache_policy default_policy,
1430 				   enum cache_policy alternate_policy,
1431 				   void __user *alternate_aperture_base,
1432 				   uint64_t alternate_aperture_size)
1433 {
1434 	bool retval = true;
1435 
1436 	if (!dqm->asic_ops.set_cache_memory_policy)
1437 		return retval;
1438 
1439 	dqm_lock(dqm);
1440 
1441 	if (alternate_aperture_size == 0) {
1442 		/* base > limit disables APE1 */
1443 		qpd->sh_mem_ape1_base = 1;
1444 		qpd->sh_mem_ape1_limit = 0;
1445 	} else {
1446 		/*
1447 		 * In FSA64, APE1_Base[63:0] = { 16{SH_MEM_APE1_BASE[31]},
1448 		 *			SH_MEM_APE1_BASE[31:0], 0x0000 }
1449 		 * APE1_Limit[63:0] = { 16{SH_MEM_APE1_LIMIT[31]},
1450 		 *			SH_MEM_APE1_LIMIT[31:0], 0xFFFF }
1451 		 * Verify that the base and size parameters can be
1452 		 * represented in this format and convert them.
1453 		 * Additionally restrict APE1 to user-mode addresses.
1454 		 */
1455 
1456 		uint64_t base = (uintptr_t)alternate_aperture_base;
1457 		uint64_t limit = base + alternate_aperture_size - 1;
1458 
1459 		if (limit <= base || (base & APE1_FIXED_BITS_MASK) != 0 ||
1460 		   (limit & APE1_FIXED_BITS_MASK) != APE1_LIMIT_ALIGNMENT) {
1461 			retval = false;
1462 			goto out;
1463 		}
1464 
1465 		qpd->sh_mem_ape1_base = base >> 16;
1466 		qpd->sh_mem_ape1_limit = limit >> 16;
1467 	}
1468 
1469 	retval = dqm->asic_ops.set_cache_memory_policy(
1470 			dqm,
1471 			qpd,
1472 			default_policy,
1473 			alternate_policy,
1474 			alternate_aperture_base,
1475 			alternate_aperture_size);
1476 
1477 	if ((dqm->sched_policy == KFD_SCHED_POLICY_NO_HWS) && (qpd->vmid != 0))
1478 		program_sh_mem_settings(dqm, qpd);
1479 
1480 	pr_debug("sh_mem_config: 0x%x, ape1_base: 0x%x, ape1_limit: 0x%x\n",
1481 		qpd->sh_mem_config, qpd->sh_mem_ape1_base,
1482 		qpd->sh_mem_ape1_limit);
1483 
1484 out:
1485 	dqm_unlock(dqm);
1486 	return retval;
1487 }
1488 
1489 static int set_trap_handler(struct device_queue_manager *dqm,
1490 				struct qcm_process_device *qpd,
1491 				uint64_t tba_addr,
1492 				uint64_t tma_addr)
1493 {
1494 	uint64_t *tma;
1495 
1496 	if (dqm->dev->cwsr_enabled) {
1497 		/* Jump from CWSR trap handler to user trap */
1498 		tma = (uint64_t *)(qpd->cwsr_kaddr + KFD_CWSR_TMA_OFFSET);
1499 		tma[0] = tba_addr;
1500 		tma[1] = tma_addr;
1501 	} else {
1502 		qpd->tba_addr = tba_addr;
1503 		qpd->tma_addr = tma_addr;
1504 	}
1505 
1506 	return 0;
1507 }
1508 
1509 static int process_termination_nocpsch(struct device_queue_manager *dqm,
1510 		struct qcm_process_device *qpd)
1511 {
1512 	struct queue *q, *next;
1513 	struct device_process_node *cur, *next_dpn;
1514 	int retval = 0;
1515 	bool found = false;
1516 
1517 	dqm_lock(dqm);
1518 
1519 	/* Clear all user mode queues */
1520 	list_for_each_entry_safe(q, next, &qpd->queues_list, list) {
1521 		int ret;
1522 
1523 		ret = destroy_queue_nocpsch_locked(dqm, qpd, q);
1524 		if (ret)
1525 			retval = ret;
1526 	}
1527 
1528 	/* Unregister process */
1529 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
1530 		if (qpd == cur->qpd) {
1531 			list_del(&cur->list);
1532 			kfree(cur);
1533 			dqm->processes_count--;
1534 			found = true;
1535 			break;
1536 		}
1537 	}
1538 
1539 	dqm_unlock(dqm);
1540 
1541 	/* Outside the DQM lock because under the DQM lock we can't do
1542 	 * reclaim or take other locks that others hold while reclaiming.
1543 	 */
1544 	if (found)
1545 		kfd_dec_compute_active(dqm->dev);
1546 
1547 	return retval;
1548 }
1549 
1550 static int get_wave_state(struct device_queue_manager *dqm,
1551 			  struct queue *q,
1552 			  void __user *ctl_stack,
1553 			  u32 *ctl_stack_used_size,
1554 			  u32 *save_area_used_size)
1555 {
1556 	struct mqd_manager *mqd_mgr;
1557 	int r;
1558 
1559 	dqm_lock(dqm);
1560 
1561 	if (q->properties.type != KFD_QUEUE_TYPE_COMPUTE ||
1562 	    q->properties.is_active || !q->device->cwsr_enabled) {
1563 		r = -EINVAL;
1564 		goto dqm_unlock;
1565 	}
1566 
1567 	mqd_mgr = dqm->mqd_mgrs[KFD_MQD_TYPE_COMPUTE];
1568 
1569 	if (!mqd_mgr->get_wave_state) {
1570 		r = -EINVAL;
1571 		goto dqm_unlock;
1572 	}
1573 
1574 	r = mqd_mgr->get_wave_state(mqd_mgr, q->mqd, ctl_stack,
1575 			ctl_stack_used_size, save_area_used_size);
1576 
1577 dqm_unlock:
1578 	dqm_unlock(dqm);
1579 	return r;
1580 }
1581 
1582 static int process_termination_cpsch(struct device_queue_manager *dqm,
1583 		struct qcm_process_device *qpd)
1584 {
1585 	int retval;
1586 	struct queue *q, *next;
1587 	struct kernel_queue *kq, *kq_next;
1588 	struct mqd_manager *mqd_mgr;
1589 	struct device_process_node *cur, *next_dpn;
1590 	enum kfd_unmap_queues_filter filter =
1591 		KFD_UNMAP_QUEUES_FILTER_DYNAMIC_QUEUES;
1592 	bool found = false;
1593 
1594 	retval = 0;
1595 
1596 	dqm_lock(dqm);
1597 
1598 	/* Clean all kernel queues */
1599 	list_for_each_entry_safe(kq, kq_next, &qpd->priv_queue_list, list) {
1600 		list_del(&kq->list);
1601 		dqm->queue_count--;
1602 		qpd->is_debug = false;
1603 		dqm->total_queue_count--;
1604 		filter = KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES;
1605 	}
1606 
1607 	/* Clear all user mode queues */
1608 	list_for_each_entry(q, &qpd->queues_list, list) {
1609 		if (q->properties.type == KFD_QUEUE_TYPE_SDMA) {
1610 			dqm->sdma_queue_count--;
1611 			deallocate_sdma_queue(dqm, q);
1612 		} else if (q->properties.type == KFD_QUEUE_TYPE_SDMA_XGMI) {
1613 			dqm->xgmi_sdma_queue_count--;
1614 			deallocate_sdma_queue(dqm, q);
1615 		}
1616 
1617 		if (q->properties.is_active)
1618 			dqm->queue_count--;
1619 
1620 		dqm->total_queue_count--;
1621 	}
1622 
1623 	/* Unregister process */
1624 	list_for_each_entry_safe(cur, next_dpn, &dqm->queues, list) {
1625 		if (qpd == cur->qpd) {
1626 			list_del(&cur->list);
1627 			kfree(cur);
1628 			dqm->processes_count--;
1629 			found = true;
1630 			break;
1631 		}
1632 	}
1633 
1634 	retval = execute_queues_cpsch(dqm, filter, 0);
1635 	if ((!dqm->is_hws_hang) && (retval || qpd->reset_wavefronts)) {
1636 		pr_warn("Resetting wave fronts (cpsch) on dev %p\n", dqm->dev);
1637 		dbgdev_wave_reset_wavefronts(dqm->dev, qpd->pqm->process);
1638 		qpd->reset_wavefronts = false;
1639 	}
1640 
1641 	dqm_unlock(dqm);
1642 
1643 	/* Outside the DQM lock because under the DQM lock we can't do
1644 	 * reclaim or take other locks that others hold while reclaiming.
1645 	 */
1646 	if (found)
1647 		kfd_dec_compute_active(dqm->dev);
1648 
1649 	/* Lastly, free mqd resources.
1650 	 * Do free_mqd() after dqm_unlock to avoid circular locking.
1651 	 */
1652 	list_for_each_entry_safe(q, next, &qpd->queues_list, list) {
1653 		mqd_mgr = dqm->mqd_mgrs[get_mqd_type_from_queue_type(
1654 				q->properties.type)];
1655 		list_del(&q->list);
1656 		qpd->queue_count--;
1657 		mqd_mgr->free_mqd(mqd_mgr, q->mqd, q->mqd_mem_obj);
1658 	}
1659 
1660 	return retval;
1661 }
1662 
1663 static int init_mqd_managers(struct device_queue_manager *dqm)
1664 {
1665 	int i, j;
1666 	struct mqd_manager *mqd_mgr;
1667 
1668 	for (i = 0; i < KFD_MQD_TYPE_MAX; i++) {
1669 		mqd_mgr = dqm->asic_ops.mqd_manager_init(i, dqm->dev);
1670 		if (!mqd_mgr) {
1671 			pr_err("mqd manager [%d] initialization failed\n", i);
1672 			goto out_free;
1673 		}
1674 		dqm->mqd_mgrs[i] = mqd_mgr;
1675 	}
1676 
1677 	return 0;
1678 
1679 out_free:
1680 	for (j = 0; j < i; j++) {
1681 		kfree(dqm->mqd_mgrs[j]);
1682 		dqm->mqd_mgrs[j] = NULL;
1683 	}
1684 
1685 	return -ENOMEM;
1686 }
1687 
1688 /* Allocate one hiq mqd (HWS) and all SDMA mqd in a continuous trunk*/
1689 static int allocate_hiq_sdma_mqd(struct device_queue_manager *dqm)
1690 {
1691 	int retval;
1692 	struct kfd_dev *dev = dqm->dev;
1693 	struct kfd_mem_obj *mem_obj = &dqm->hiq_sdma_mqd;
1694 	uint32_t size = dqm->mqd_mgrs[KFD_MQD_TYPE_SDMA]->mqd_size *
1695 		(dev->device_info->num_sdma_engines +
1696 		dev->device_info->num_xgmi_sdma_engines) *
1697 		dev->device_info->num_sdma_queues_per_engine +
1698 		dqm->mqd_mgrs[KFD_MQD_TYPE_HIQ]->mqd_size;
1699 
1700 	retval = amdgpu_amdkfd_alloc_gtt_mem(dev->kgd, size,
1701 		&(mem_obj->gtt_mem), &(mem_obj->gpu_addr),
1702 		(void *)&(mem_obj->cpu_ptr), true);
1703 
1704 	return retval;
1705 }
1706 
1707 struct device_queue_manager *device_queue_manager_init(struct kfd_dev *dev)
1708 {
1709 	struct device_queue_manager *dqm;
1710 
1711 	pr_debug("Loading device queue manager\n");
1712 
1713 	dqm = kzalloc(sizeof(*dqm), GFP_KERNEL);
1714 	if (!dqm)
1715 		return NULL;
1716 
1717 	switch (dev->device_info->asic_family) {
1718 	/* HWS is not available on Hawaii. */
1719 	case CHIP_HAWAII:
1720 	/* HWS depends on CWSR for timely dequeue. CWSR is not
1721 	 * available on Tonga.
1722 	 *
1723 	 * FIXME: This argument also applies to Kaveri.
1724 	 */
1725 	case CHIP_TONGA:
1726 		dqm->sched_policy = KFD_SCHED_POLICY_NO_HWS;
1727 		break;
1728 	default:
1729 		dqm->sched_policy = sched_policy;
1730 		break;
1731 	}
1732 
1733 	dqm->dev = dev;
1734 	switch (dqm->sched_policy) {
1735 	case KFD_SCHED_POLICY_HWS:
1736 	case KFD_SCHED_POLICY_HWS_NO_OVERSUBSCRIPTION:
1737 		/* initialize dqm for cp scheduling */
1738 		dqm->ops.create_queue = create_queue_cpsch;
1739 		dqm->ops.initialize = initialize_cpsch;
1740 		dqm->ops.start = start_cpsch;
1741 		dqm->ops.stop = stop_cpsch;
1742 		dqm->ops.destroy_queue = destroy_queue_cpsch;
1743 		dqm->ops.update_queue = update_queue;
1744 		dqm->ops.register_process = register_process;
1745 		dqm->ops.unregister_process = unregister_process;
1746 		dqm->ops.uninitialize = uninitialize;
1747 		dqm->ops.create_kernel_queue = create_kernel_queue_cpsch;
1748 		dqm->ops.destroy_kernel_queue = destroy_kernel_queue_cpsch;
1749 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
1750 		dqm->ops.set_trap_handler = set_trap_handler;
1751 		dqm->ops.process_termination = process_termination_cpsch;
1752 		dqm->ops.evict_process_queues = evict_process_queues_cpsch;
1753 		dqm->ops.restore_process_queues = restore_process_queues_cpsch;
1754 		dqm->ops.get_wave_state = get_wave_state;
1755 		break;
1756 	case KFD_SCHED_POLICY_NO_HWS:
1757 		/* initialize dqm for no cp scheduling */
1758 		dqm->ops.start = start_nocpsch;
1759 		dqm->ops.stop = stop_nocpsch;
1760 		dqm->ops.create_queue = create_queue_nocpsch;
1761 		dqm->ops.destroy_queue = destroy_queue_nocpsch;
1762 		dqm->ops.update_queue = update_queue;
1763 		dqm->ops.register_process = register_process;
1764 		dqm->ops.unregister_process = unregister_process;
1765 		dqm->ops.initialize = initialize_nocpsch;
1766 		dqm->ops.uninitialize = uninitialize;
1767 		dqm->ops.set_cache_memory_policy = set_cache_memory_policy;
1768 		dqm->ops.set_trap_handler = set_trap_handler;
1769 		dqm->ops.process_termination = process_termination_nocpsch;
1770 		dqm->ops.evict_process_queues = evict_process_queues_nocpsch;
1771 		dqm->ops.restore_process_queues =
1772 			restore_process_queues_nocpsch;
1773 		dqm->ops.get_wave_state = get_wave_state;
1774 		break;
1775 	default:
1776 		pr_err("Invalid scheduling policy %d\n", dqm->sched_policy);
1777 		goto out_free;
1778 	}
1779 
1780 	switch (dev->device_info->asic_family) {
1781 	case CHIP_CARRIZO:
1782 		device_queue_manager_init_vi(&dqm->asic_ops);
1783 		break;
1784 
1785 	case CHIP_KAVERI:
1786 		device_queue_manager_init_cik(&dqm->asic_ops);
1787 		break;
1788 
1789 	case CHIP_HAWAII:
1790 		device_queue_manager_init_cik_hawaii(&dqm->asic_ops);
1791 		break;
1792 
1793 	case CHIP_TONGA:
1794 	case CHIP_FIJI:
1795 	case CHIP_POLARIS10:
1796 	case CHIP_POLARIS11:
1797 	case CHIP_POLARIS12:
1798 	case CHIP_VEGAM:
1799 		device_queue_manager_init_vi_tonga(&dqm->asic_ops);
1800 		break;
1801 
1802 	case CHIP_VEGA10:
1803 	case CHIP_VEGA12:
1804 	case CHIP_VEGA20:
1805 	case CHIP_RAVEN:
1806 	case CHIP_RENOIR:
1807 	case CHIP_ARCTURUS:
1808 		device_queue_manager_init_v9(&dqm->asic_ops);
1809 		break;
1810 	case CHIP_NAVI10:
1811 	case CHIP_NAVI12:
1812 	case CHIP_NAVI14:
1813 		device_queue_manager_init_v10_navi10(&dqm->asic_ops);
1814 		break;
1815 	default:
1816 		WARN(1, "Unexpected ASIC family %u",
1817 		     dev->device_info->asic_family);
1818 		goto out_free;
1819 	}
1820 
1821 	if (init_mqd_managers(dqm))
1822 		goto out_free;
1823 
1824 	if (allocate_hiq_sdma_mqd(dqm)) {
1825 		pr_err("Failed to allocate hiq sdma mqd trunk buffer\n");
1826 		goto out_free;
1827 	}
1828 
1829 	if (!dqm->ops.initialize(dqm))
1830 		return dqm;
1831 
1832 out_free:
1833 	kfree(dqm);
1834 	return NULL;
1835 }
1836 
1837 static void deallocate_hiq_sdma_mqd(struct kfd_dev *dev,
1838 				    struct kfd_mem_obj *mqd)
1839 {
1840 	WARN(!mqd, "No hiq sdma mqd trunk to free");
1841 
1842 	amdgpu_amdkfd_free_gtt_mem(dev->kgd, mqd->gtt_mem);
1843 }
1844 
1845 void device_queue_manager_uninit(struct device_queue_manager *dqm)
1846 {
1847 	dqm->ops.uninitialize(dqm);
1848 	deallocate_hiq_sdma_mqd(dqm->dev, &dqm->hiq_sdma_mqd);
1849 	kfree(dqm);
1850 }
1851 
1852 int kfd_process_vm_fault(struct device_queue_manager *dqm,
1853 			 unsigned int pasid)
1854 {
1855 	struct kfd_process_device *pdd;
1856 	struct kfd_process *p = kfd_lookup_process_by_pasid(pasid);
1857 	int ret = 0;
1858 
1859 	if (!p)
1860 		return -EINVAL;
1861 	pdd = kfd_get_process_device_data(dqm->dev, p);
1862 	if (pdd)
1863 		ret = dqm->ops.evict_process_queues(dqm, &pdd->qpd);
1864 	kfd_unref_process(p);
1865 
1866 	return ret;
1867 }
1868 
1869 static void kfd_process_hw_exception(struct work_struct *work)
1870 {
1871 	struct device_queue_manager *dqm = container_of(work,
1872 			struct device_queue_manager, hw_exception_work);
1873 	amdgpu_amdkfd_gpu_reset(dqm->dev->kgd);
1874 }
1875 
1876 #if defined(CONFIG_DEBUG_FS)
1877 
1878 static void seq_reg_dump(struct seq_file *m,
1879 			 uint32_t (*dump)[2], uint32_t n_regs)
1880 {
1881 	uint32_t i, count;
1882 
1883 	for (i = 0, count = 0; i < n_regs; i++) {
1884 		if (count == 0 ||
1885 		    dump[i-1][0] + sizeof(uint32_t) != dump[i][0]) {
1886 			seq_printf(m, "%s    %08x: %08x",
1887 				   i ? "\n" : "",
1888 				   dump[i][0], dump[i][1]);
1889 			count = 7;
1890 		} else {
1891 			seq_printf(m, " %08x", dump[i][1]);
1892 			count--;
1893 		}
1894 	}
1895 
1896 	seq_puts(m, "\n");
1897 }
1898 
1899 int dqm_debugfs_hqds(struct seq_file *m, void *data)
1900 {
1901 	struct device_queue_manager *dqm = data;
1902 	uint32_t (*dump)[2], n_regs;
1903 	int pipe, queue;
1904 	int r = 0;
1905 
1906 	r = dqm->dev->kfd2kgd->hqd_dump(dqm->dev->kgd,
1907 					KFD_CIK_HIQ_PIPE, KFD_CIK_HIQ_QUEUE,
1908 					&dump, &n_regs);
1909 	if (!r) {
1910 		seq_printf(m, "  HIQ on MEC %d Pipe %d Queue %d\n",
1911 			   KFD_CIK_HIQ_PIPE/get_pipes_per_mec(dqm)+1,
1912 			   KFD_CIK_HIQ_PIPE%get_pipes_per_mec(dqm),
1913 			   KFD_CIK_HIQ_QUEUE);
1914 		seq_reg_dump(m, dump, n_regs);
1915 
1916 		kfree(dump);
1917 	}
1918 
1919 	for (pipe = 0; pipe < get_pipes_per_mec(dqm); pipe++) {
1920 		int pipe_offset = pipe * get_queues_per_pipe(dqm);
1921 
1922 		for (queue = 0; queue < get_queues_per_pipe(dqm); queue++) {
1923 			if (!test_bit(pipe_offset + queue,
1924 				      dqm->dev->shared_resources.queue_bitmap))
1925 				continue;
1926 
1927 			r = dqm->dev->kfd2kgd->hqd_dump(
1928 				dqm->dev->kgd, pipe, queue, &dump, &n_regs);
1929 			if (r)
1930 				break;
1931 
1932 			seq_printf(m, "  CP Pipe %d, Queue %d\n",
1933 				  pipe, queue);
1934 			seq_reg_dump(m, dump, n_regs);
1935 
1936 			kfree(dump);
1937 		}
1938 	}
1939 
1940 	for (pipe = 0; pipe < get_num_sdma_engines(dqm) +
1941 			get_num_xgmi_sdma_engines(dqm); pipe++) {
1942 		for (queue = 0;
1943 		     queue < dqm->dev->device_info->num_sdma_queues_per_engine;
1944 		     queue++) {
1945 			r = dqm->dev->kfd2kgd->hqd_sdma_dump(
1946 				dqm->dev->kgd, pipe, queue, &dump, &n_regs);
1947 			if (r)
1948 				break;
1949 
1950 			seq_printf(m, "  SDMA Engine %d, RLC %d\n",
1951 				  pipe, queue);
1952 			seq_reg_dump(m, dump, n_regs);
1953 
1954 			kfree(dump);
1955 		}
1956 	}
1957 
1958 	return r;
1959 }
1960 
1961 int dqm_debugfs_execute_queues(struct device_queue_manager *dqm)
1962 {
1963 	int r = 0;
1964 
1965 	dqm_lock(dqm);
1966 	dqm->active_runlist = true;
1967 	r = execute_queues_cpsch(dqm, KFD_UNMAP_QUEUES_FILTER_ALL_QUEUES, 0);
1968 	dqm_unlock(dqm);
1969 
1970 	return r;
1971 }
1972 
1973 #endif
1974