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