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