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