xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c (revision 7f7d7ea1fa515157162d0d21245925551ed103a1)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright 2023 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 <drm/drm_auth.h>
26 #include <drm/drm_exec.h>
27 #include <linux/pm_runtime.h>
28 #include <linux/overflow.h>
29 #include <drm/drm_drv.h>
30 
31 #include "amdgpu.h"
32 #include "amdgpu_reset.h"
33 #include "amdgpu_vm.h"
34 #include "amdgpu_userq.h"
35 #include "amdgpu_hmm.h"
36 #include "amdgpu_userq_fence.h"
37 #include "amdgpu_trace.h"
38 
39 u32 amdgpu_userq_get_supported_ip_mask(struct amdgpu_device *adev)
40 {
41 	int i;
42 	u32 userq_ip_mask = 0;
43 
44 	for (i = 0; i < AMDGPU_HW_IP_NUM; i++) {
45 		if (adev->userq_funcs[i])
46 			userq_ip_mask |= (1 << i);
47 	}
48 
49 	return userq_ip_mask;
50 }
51 
52 static bool amdgpu_userq_is_reset_type_supported(struct amdgpu_device *adev,
53 				enum amdgpu_ring_type ring_type, int reset_type)
54 {
55 
56 	if (ring_type < 0 || ring_type >= AMDGPU_RING_TYPE_MAX)
57 		return false;
58 
59 	switch (ring_type) {
60 	case AMDGPU_RING_TYPE_GFX:
61 		if (adev->gfx.gfx_supported_reset & reset_type)
62 			return true;
63 		break;
64 	case AMDGPU_RING_TYPE_COMPUTE:
65 		if (adev->gfx.compute_supported_reset & reset_type)
66 			return true;
67 		break;
68 	case AMDGPU_RING_TYPE_SDMA:
69 		if (adev->sdma.supported_reset & reset_type)
70 			return true;
71 		break;
72 	case AMDGPU_RING_TYPE_VCN_DEC:
73 	case AMDGPU_RING_TYPE_VCN_ENC:
74 		if (adev->vcn.supported_reset & reset_type)
75 			return true;
76 		break;
77 	case AMDGPU_RING_TYPE_VCN_JPEG:
78 		if (adev->jpeg.supported_reset & reset_type)
79 			return true;
80 		break;
81 	default:
82 		break;
83 	}
84 	return false;
85 }
86 
87 static void amdgpu_userq_mgr_reset_work(struct work_struct *work)
88 {
89 	struct amdgpu_userq_mgr *uq_mgr =
90 		container_of(work, struct amdgpu_userq_mgr,
91 			     reset_work);
92 	struct amdgpu_device *adev = uq_mgr->adev;
93 	struct amdgpu_reset_context reset_context;
94 
95 	if (unlikely(adev->debug_disable_gpu_ring_reset)) {
96 		dev_err(adev->dev, "userq reset disabled by debug mask\n");
97 		return;
98 	}
99 
100 	/*
101 	 * If GPU recovery feature is disabled system-wide,
102 	 * skip all reset detection logic
103 	 */
104 	if (!amdgpu_gpu_recovery)
105 		return;
106 
107 	memset(&reset_context, 0, sizeof(reset_context));
108 
109 	reset_context.method = AMD_RESET_METHOD_NONE;
110 	reset_context.reset_req_dev = adev;
111 	reset_context.src = AMDGPU_RESET_SRC_USERQ;
112 	set_bit(AMDGPU_NEED_FULL_RESET, &reset_context.flags);
113 	/*set_bit(AMDGPU_SKIP_COREDUMP, &reset_context.flags);*/
114 
115 	amdgpu_device_gpu_recover(adev, NULL, &reset_context);
116 }
117 
118 static void amdgpu_userq_hang_detect_work(struct work_struct *work)
119 {
120 	struct amdgpu_usermode_queue *queue =
121 		container_of(work, struct amdgpu_usermode_queue,
122 			     hang_detect_work.work);
123 	struct amdgpu_userq_mgr *uq_mgr = queue->userq_mgr;
124 	struct amdgpu_device *adev = uq_mgr->adev;
125 	const struct amdgpu_userq_funcs *userq_funcs =
126 		adev->userq_funcs[queue->queue_type];
127 	struct drm_wedge_task_info *info = NULL;
128 	struct amdgpu_task_info *ti = NULL;
129 	bool gpu_reset = false;
130 
131 	if (unlikely(adev->debug_disable_gpu_ring_reset)) {
132 		dev_err(adev->dev, "userq reset disabled by debug mask\n");
133 		return;
134 	}
135 
136 	/*
137 	 * If GPU recovery feature is disabled system-wide,
138 	 * skip all reset detection logic
139 	 */
140 	if (!amdgpu_gpu_recovery)
141 		return;
142 
143 	if (queue->vm && queue->vm->pasid) {
144 		ti = amdgpu_vm_get_task_info_pasid(adev, queue->vm->pasid);
145 		if (ti) {
146 			amdgpu_vm_print_task_info(adev, ti);
147 			info = &ti->task;
148 		}
149 	}
150 
151 	if (amdgpu_userq_is_reset_type_supported(adev, queue->queue_type,
152 						 AMDGPU_RESET_TYPE_PER_QUEUE)) {
153 		int r;
154 
155 		if (queue->queue_type == AMDGPU_HW_IP_COMPUTE)
156 			r = amdgpu_gfx_reset_mes_compute(adev, NULL, NULL,
157 							 queue, NULL, NULL);
158 		else
159 			r = userq_funcs->reset(queue);
160 		if (r) {
161 			gpu_reset = true;
162 		} else {
163 			atomic_inc(&adev->gpu_reset_counter);
164 			amdgpu_userq_fence_driver_force_completion(queue);
165 			drm_dev_wedged_event(adev_to_drm(adev), DRM_WEDGE_RECOVERY_NONE, info);
166 		}
167 	} else {
168 		gpu_reset = true;
169 	}
170 	amdgpu_vm_put_task_info(ti);
171 
172 	/*
173 	 * Don't schedule the work here! Scheduling or queue work from one reset
174 	 * handler to another is illegal if you don't take extra precautions!
175 	 */
176 	if (gpu_reset)
177 		amdgpu_userq_mgr_reset_work(&queue->userq_mgr->reset_work);
178 }
179 
180 /*
181  * Start hang detection for a user queue fence. A delayed work will be scheduled
182  * to reset the queues when the fence doesn't signal in time.
183  */
184 void amdgpu_userq_start_hang_detect_work(struct amdgpu_usermode_queue *queue)
185 {
186 	struct amdgpu_device *adev;
187 	unsigned long timeout_ms;
188 
189 	adev = queue->userq_mgr->adev;
190 	/* Determine timeout based on queue type */
191 	switch (queue->queue_type) {
192 	case AMDGPU_RING_TYPE_GFX:
193 		timeout_ms = adev->gfx_timeout;
194 		break;
195 	case AMDGPU_RING_TYPE_COMPUTE:
196 		timeout_ms = adev->compute_timeout;
197 		break;
198 	case AMDGPU_RING_TYPE_SDMA:
199 		timeout_ms = adev->sdma_timeout;
200 		break;
201 	default:
202 		timeout_ms = adev->gfx_timeout;
203 		break;
204 	}
205 
206 	queue_delayed_work(adev->reset_domain->wq, &queue->hang_detect_work,
207 			   msecs_to_jiffies(timeout_ms));
208 }
209 
210 void amdgpu_userq_process_fence_irq(struct amdgpu_device *adev, u32 doorbell)
211 {
212 	struct xarray *xa = &adev->userq_doorbell_xa;
213 	struct amdgpu_usermode_queue *queue;
214 	unsigned long flags;
215 	int r;
216 
217 	xa_lock_irqsave(xa, flags);
218 	queue = xa_load(xa, doorbell);
219 	if (queue) {
220 		r = amdgpu_userq_fence_driver_process(queue->fence_drv);
221 		/*
222 		 * We are in interrupt context here, this *can't* wait for
223 		 * reset work to finish.
224 		 */
225 		if (r >= 0)
226 			cancel_delayed_work(&queue->hang_detect_work);
227 
228 		/* Restart the timer when there are still fences pending */
229 		if (r == 1)
230 			amdgpu_userq_start_hang_detect_work(queue);
231 	}
232 	xa_unlock_irqrestore(xa, flags);
233 }
234 
235 int amdgpu_userq_input_va_validate(struct amdgpu_device *adev,
236 				   struct amdgpu_usermode_queue *queue,
237 				   u64 addr, u64 expected_size,
238 				   u64 *va_out)
239 {
240 	struct amdgpu_bo_va_mapping *va_map;
241 	struct amdgpu_vm *vm = queue->vm;
242 	u64 start_addr;
243 	u64 end_addr;
244 	u64 start_page;
245 
246 	/* Caller must hold vm->root.bo reservation */
247 	dma_resv_assert_held(queue->vm->root.bo->tbo.base.resv);
248 
249 	if (!expected_size)
250 		return -EINVAL;
251 
252 	start_addr = addr & AMDGPU_GMC_HOLE_MASK;
253 	if (check_add_overflow(start_addr, expected_size - 1, &end_addr))
254 		return -EINVAL;
255 
256 	start_page = start_addr >> AMDGPU_GPU_PAGE_SHIFT;
257 
258 	va_map = amdgpu_vm_bo_lookup_mapping(vm, start_page);
259 	if (!va_map)
260 		return -EINVAL;
261 
262 	/* Lookup guarantees start_page is mapped; ensure full span is covered. */
263 	if ((end_addr >> AMDGPU_GPU_PAGE_SHIFT) <= va_map->last) {
264 		va_map->bo_va->userq_va_mapped = true;
265 		*va_out = start_page;
266 		return 0;
267 	}
268 
269 	return -EINVAL;
270 }
271 
272 static bool amdgpu_userq_buffer_va_mapped(struct amdgpu_vm *vm, u64 addr)
273 {
274 	struct amdgpu_bo_va_mapping *mapping;
275 	bool r;
276 
277 	dma_resv_assert_held(vm->root.bo->tbo.base.resv);
278 
279 	mapping = amdgpu_vm_bo_lookup_mapping(vm, addr);
280 	if (!IS_ERR_OR_NULL(mapping) && mapping->bo_va->userq_va_mapped)
281 		r = true;
282 	else
283 		r = false;
284 
285 	return r;
286 }
287 
288 static bool amdgpu_userq_buffer_vas_mapped(struct amdgpu_usermode_queue *queue)
289 {
290 	int i, r = 0;
291 
292 	for (i = 0; i < ARRAY_SIZE(queue->userq_vas.va_array); i++) {
293 		if (!queue->userq_vas.va_array[i])
294 			continue;
295 		r += amdgpu_userq_buffer_va_mapped(queue->vm,
296 						   queue->userq_vas.va_array[i]);
297 		dev_dbg(queue->userq_mgr->adev->dev,
298 			"validate the userq mapping:%p va:%llx r:%d\n",
299 			queue, queue->userq_vas.va_array[i], r);
300 	}
301 
302 	if (r != 0)
303 		return true;
304 
305 	return false;
306 }
307 
308 
309 
310 static int amdgpu_userq_preempt_helper(struct amdgpu_usermode_queue *queue)
311 {
312 	struct amdgpu_userq_mgr *uq_mgr = queue->userq_mgr;
313 	struct amdgpu_device *adev = uq_mgr->adev;
314 	const struct amdgpu_userq_funcs *userq_funcs =
315 		adev->userq_funcs[queue->queue_type];
316 	int r;
317 
318 	if (queue->state == AMDGPU_USERQ_STATE_MAPPED) {
319 		trace_amdgpu_userq_state_start(queue);
320 
321 		r = userq_funcs->preempt(queue);
322 		if (r) {
323 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_HUNG);
324 			queue->state = AMDGPU_USERQ_STATE_HUNG;
325 			return r;
326 		} else {
327 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_PREEMPTED);
328 			queue->state = AMDGPU_USERQ_STATE_PREEMPTED;
329 		}
330 	}
331 	return 0;
332 }
333 
334 static int amdgpu_userq_restore_helper(struct amdgpu_usermode_queue *queue)
335 {
336 	struct amdgpu_userq_mgr *uq_mgr = queue->userq_mgr;
337 	struct amdgpu_device *adev = uq_mgr->adev;
338 	const struct amdgpu_userq_funcs *userq_funcs =
339 		adev->userq_funcs[queue->queue_type];
340 	int r = 0;
341 
342 	if (queue->state == AMDGPU_USERQ_STATE_PREEMPTED) {
343 		trace_amdgpu_userq_state_start(queue);
344 
345 		r = userq_funcs->restore(queue);
346 		if (r) {
347 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_HUNG);
348 			queue->state = AMDGPU_USERQ_STATE_HUNG;
349 		} else {
350 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_MAPPED);
351 			queue->state = AMDGPU_USERQ_STATE_MAPPED;
352 		}
353 	}
354 
355 	return r;
356 }
357 
358 static int amdgpu_userq_unmap_helper(struct amdgpu_usermode_queue *queue)
359 {
360 	struct amdgpu_userq_mgr *uq_mgr = queue->userq_mgr;
361 	struct amdgpu_device *adev = uq_mgr->adev;
362 	const struct amdgpu_userq_funcs *userq_funcs =
363 		adev->userq_funcs[queue->queue_type];
364 	int r;
365 
366 	if ((queue->state == AMDGPU_USERQ_STATE_MAPPED) ||
367 	    (queue->state == AMDGPU_USERQ_STATE_PREEMPTED)) {
368 		trace_amdgpu_userq_state_start(queue);
369 
370 		r = userq_funcs->unmap(queue);
371 		if (r) {
372 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_HUNG);
373 			queue->state = AMDGPU_USERQ_STATE_HUNG;
374 			return r;
375 		} else {
376 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_UNMAPPED);
377 			queue->state = AMDGPU_USERQ_STATE_UNMAPPED;
378 		}
379 	}
380 
381 	return 0;
382 }
383 
384 static int amdgpu_userq_map_helper(struct amdgpu_usermode_queue *queue)
385 {
386 	struct amdgpu_userq_mgr *uq_mgr = queue->userq_mgr;
387 	struct amdgpu_device *adev = uq_mgr->adev;
388 	const struct amdgpu_userq_funcs *userq_funcs =
389 		adev->userq_funcs[queue->queue_type];
390 	int r;
391 
392 	if (queue->state == AMDGPU_USERQ_STATE_UNMAPPED) {
393 		trace_amdgpu_userq_state_start(queue);
394 
395 		r = userq_funcs->map(queue);
396 		if (r) {
397 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_HUNG);
398 			queue->state = AMDGPU_USERQ_STATE_HUNG;
399 			return r;
400 		} else {
401 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_MAPPED);
402 			queue->state = AMDGPU_USERQ_STATE_MAPPED;
403 		}
404 	}
405 
406 	return 0;
407 }
408 
409 static void amdgpu_userq_wait_for_last_fence(struct amdgpu_usermode_queue *queue)
410 {
411 	struct dma_fence *f = queue->last_fence;
412 
413 	if (!f)
414 		return;
415 
416 	dma_fence_wait(f, false);
417 }
418 
419 static void amdgpu_userq_cleanup(struct amdgpu_usermode_queue *queue)
420 {
421 	struct amdgpu_userq_mgr *uq_mgr = queue->userq_mgr;
422 	struct amdgpu_device *adev = uq_mgr->adev;
423 
424 	/* Wait for mode-1 reset to complete */
425 	down_read(&adev->reset_domain->sem);
426 
427 	/* Use interrupt-safe locking since IRQ handlers may access these XArrays */
428 	xa_erase_irq(&adev->userq_doorbell_xa, queue->doorbell_index);
429 	amdgpu_userq_fence_driver_free(queue);
430 	queue->fence_drv = NULL;
431 
432 	up_read(&adev->reset_domain->sem);
433 }
434 
435 /**
436  * amdgpu_userq_ensure_ev_fence - ensure a valid, unsignaled eviction fence exists
437  * @uq_mgr: the usermode queue manager for this process
438  * @evf_mgr: the eviction fence manager to check and rearm
439  *
440  * Ensures that a valid and not yet signaled eviction fence is attached to the
441  * usermode queue before any queue operations proceed. If it is signalled, then
442  * rearm a new eviction fence.
443  */
444 void
445 amdgpu_userq_ensure_ev_fence(struct amdgpu_userq_mgr *uq_mgr,
446 			     struct amdgpu_eviction_fence_mgr *evf_mgr)
447 {
448 	struct dma_fence *ev_fence;
449 
450 retry:
451 	/* Flush any pending resume work to create ev_fence */
452 	flush_delayed_work(&uq_mgr->resume_work);
453 
454 	mutex_lock(&uq_mgr->userq_mutex);
455 	ev_fence = amdgpu_evf_mgr_get_fence(evf_mgr);
456 	if (dma_fence_is_signaled(ev_fence)) {
457 		dma_fence_put(ev_fence);
458 		mutex_unlock(&uq_mgr->userq_mutex);
459 		/*
460 		 * Looks like there was no pending resume work,
461 		 * add one now to create a valid eviction fence
462 		 */
463 		schedule_delayed_work(&uq_mgr->resume_work, 0);
464 		goto retry;
465 	}
466 	dma_fence_put(ev_fence);
467 }
468 
469 
470 
471 static int
472 amdgpu_userq_get_doorbell_index(struct amdgpu_userq_mgr *uq_mgr,
473 				struct amdgpu_db_info *db_info,
474 				struct drm_file *filp,
475 				u64 *index)
476 {
477 	u64 doorbell_index;
478 	struct drm_gem_object *gobj;
479 	struct amdgpu_userq_obj *db_obj = db_info->db_obj;
480 	int r, db_size;
481 
482 	gobj = drm_gem_object_lookup(filp, db_info->doorbell_handle);
483 	if (gobj == NULL) {
484 		drm_file_err(uq_mgr->file, "Can't find GEM object for doorbell\n");
485 		return -EINVAL;
486 	}
487 
488 	db_obj->obj = amdgpu_bo_ref(gem_to_amdgpu_bo(gobj));
489 	drm_gem_object_put(gobj);
490 
491 	r = amdgpu_bo_reserve(db_obj->obj, true);
492 	if (r) {
493 		drm_file_err(uq_mgr->file, "[Usermode queues] Failed to pin doorbell object\n");
494 		goto unref_bo;
495 	}
496 
497 	/* Pin the BO before generating the index, unpin in queue destroy */
498 	r = amdgpu_bo_pin(db_obj->obj, AMDGPU_GEM_DOMAIN_DOORBELL);
499 	if (r) {
500 		drm_file_err(uq_mgr->file, "[Usermode queues] Failed to pin doorbell object\n");
501 		goto unresv_bo;
502 	}
503 
504 	switch (db_info->queue_type) {
505 	case AMDGPU_HW_IP_GFX:
506 	case AMDGPU_HW_IP_COMPUTE:
507 	case AMDGPU_HW_IP_DMA:
508 		db_size = sizeof(u64);
509 		break;
510 	default:
511 		drm_file_err(uq_mgr->file, "[Usermode queues] IP %d not support\n",
512 			     db_info->queue_type);
513 		r = -EINVAL;
514 		goto unpin_bo;
515 	}
516 
517 	/* Validate doorbell_offset is within the doorbell BO */
518 	if ((u64)db_info->doorbell_offset * db_size + db_size >
519 	    amdgpu_bo_size(db_obj->obj)) {
520 		r = -EINVAL;
521 		goto unpin_bo;
522 	}
523 
524 	doorbell_index = amdgpu_doorbell_index_on_bar(uq_mgr->adev, db_obj->obj,
525 						      db_info->doorbell_offset, db_size);
526 	drm_dbg_driver(adev_to_drm(uq_mgr->adev),
527 		       "[Usermode queues] doorbell index=%lld\n", doorbell_index);
528 	amdgpu_bo_unreserve(db_obj->obj);
529 	*index = doorbell_index;
530 	return 0;
531 
532 unpin_bo:
533 	amdgpu_bo_unpin(db_obj->obj);
534 unresv_bo:
535 	amdgpu_bo_unreserve(db_obj->obj);
536 unref_bo:
537 	amdgpu_bo_unref(&db_obj->obj);
538 	return r;
539 }
540 
541 static int
542 amdgpu_userq_destroy(struct amdgpu_userq_mgr *uq_mgr, struct amdgpu_usermode_queue *queue)
543 {
544 	struct amdgpu_device *adev = uq_mgr->adev;
545 	const struct amdgpu_userq_funcs *uq_funcs = adev->userq_funcs[queue->queue_type];
546 	int r = 0;
547 
548 	trace_amdgpu_userq_destroy_start(queue);
549 
550 	cancel_delayed_work_sync(&uq_mgr->resume_work);
551 
552 	/* Cancel any pending hang detection work and cleanup */
553 	cancel_delayed_work_sync(&queue->hang_detect_work);
554 
555 	mutex_lock(&uq_mgr->userq_mutex);
556 	amdgpu_userq_wait_for_last_fence(queue);
557 
558 #if defined(CONFIG_DEBUG_FS)
559 	debugfs_remove_recursive(queue->debugfs_queue);
560 #endif
561 	r = amdgpu_userq_unmap_helper(queue);
562 	atomic_dec(&uq_mgr->userq_count[queue->queue_type]);
563 	amdgpu_userq_cleanup(queue);
564 	mutex_unlock(&uq_mgr->userq_mutex);
565 
566 	/*
567 	 * A failed unmap means MES could not remove the hung queue and is now
568 	 * unresponsive.  Recover the GPU here so the wedged MES does not fail
569 	 * the next, unrelated queue submission and trigger a reset attributed
570 	 * to an innocent workload.
571 	 */
572 	if (r)
573 		queue_work(adev->reset_domain->wq, &uq_mgr->reset_work);
574 
575 	cancel_delayed_work_sync(&queue->hang_detect_work);
576 	uq_funcs->mqd_destroy(queue);
577 	queue->userq_mgr = NULL;
578 
579 	amdgpu_bo_reserve(queue->db_obj.obj, true);
580 	amdgpu_bo_unpin(queue->db_obj.obj);
581 	amdgpu_bo_unreserve(queue->db_obj.obj);
582 	amdgpu_bo_unref(&queue->db_obj.obj);
583 
584 	trace_amdgpu_userq_destroy_end(queue, r);
585 	kfree(queue);
586 
587 	pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
588 
589 	return r;
590 }
591 
592 static void amdgpu_userq_kref_destroy(struct kref *kref)
593 {
594 	int r;
595 	struct amdgpu_usermode_queue *queue =
596 		container_of(kref, struct amdgpu_usermode_queue, refcount);
597 	struct amdgpu_userq_mgr *uq_mgr = queue->userq_mgr;
598 
599 	r = amdgpu_userq_destroy(uq_mgr, queue);
600 	if (r)
601 		drm_file_err(uq_mgr->file, "Failed to destroy usermode queue %d\n", r);
602 }
603 
604 struct amdgpu_usermode_queue *amdgpu_userq_get(struct amdgpu_userq_mgr *uq_mgr, u32 qid)
605 {
606 	struct amdgpu_usermode_queue *queue;
607 
608 	xa_lock(&uq_mgr->userq_xa);
609 	queue = xa_load(&uq_mgr->userq_xa, qid);
610 	if (queue)
611 		kref_get(&queue->refcount);
612 	xa_unlock(&uq_mgr->userq_xa);
613 
614 	return queue;
615 }
616 
617 void amdgpu_userq_put(struct amdgpu_usermode_queue *queue)
618 {
619 	if (queue)
620 		kref_put(&queue->refcount, amdgpu_userq_kref_destroy);
621 }
622 
623 static int amdgpu_userq_priority_permit(struct drm_file *filp,
624 					int priority)
625 {
626 	if (priority < AMDGPU_USERQ_CREATE_FLAGS_QUEUE_PRIORITY_HIGH)
627 		return 0;
628 
629 	if (capable(CAP_SYS_NICE))
630 		return 0;
631 
632 	if (drm_is_current_master(filp))
633 		return 0;
634 
635 	return -EACCES;
636 }
637 
638 static int
639 amdgpu_userq_create(struct drm_file *filp, union drm_amdgpu_userq *args)
640 {
641 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
642 	struct amdgpu_userq_mgr *uq_mgr = &fpriv->userq_mgr;
643 	struct amdgpu_device *adev = uq_mgr->adev;
644 	const struct amdgpu_userq_funcs *uq_funcs;
645 	struct amdgpu_usermode_queue *queue;
646 	struct amdgpu_db_info db_info;
647 	uint64_t index;
648 	int priority;
649 	u32 qid;
650 	int r;
651 
652 	priority =
653 		(args->in.flags & AMDGPU_USERQ_CREATE_FLAGS_QUEUE_PRIORITY_MASK)
654 		>> AMDGPU_USERQ_CREATE_FLAGS_QUEUE_PRIORITY_SHIFT;
655 	r = amdgpu_userq_priority_permit(filp, priority);
656 	if (r)
657 		return r;
658 
659 	r = pm_runtime_resume_and_get(adev_to_drm(adev)->dev);
660 	if (r < 0) {
661 		drm_file_err(uq_mgr->file, "pm_runtime_resume_and_get() failed for userqueue create\n");
662 		return r;
663 	}
664 
665 	uq_funcs = adev->userq_funcs[args->in.ip_type];
666 	if (!uq_funcs) {
667 		r = -EINVAL;
668 		goto err_pm_runtime;
669 	}
670 
671 	queue = kzalloc_obj(struct amdgpu_usermode_queue);
672 	if (!queue) {
673 		r = -ENOMEM;
674 		goto err_pm_runtime;
675 	}
676 
677 	kref_init(&queue->refcount);
678 	queue->doorbell_handle = args->in.doorbell_handle;
679 	queue->queue_type = args->in.ip_type;
680 	queue->vm = &fpriv->vm;
681 	queue->priority = priority;
682 	queue->xcp_id = (fpriv->xcp_id != AMDGPU_XCP_NO_PARTITION) ?
683 				fpriv->xcp_id : 0;
684 	queue->userq_mgr = uq_mgr;
685 	INIT_DELAYED_WORK(&queue->hang_detect_work,
686 			  amdgpu_userq_hang_detect_work);
687 
688 	r = amdgpu_userq_fence_driver_alloc(adev, &queue->fence_drv);
689 	if (r)
690 		goto free_queue;
691 
692 	xa_init_flags(&queue->fence_drv_xa, XA_FLAGS_ALLOC);
693 	mutex_init(&queue->fence_drv_lock);
694 	/* Make sure the queue can actually run with those virtual addresses. */
695 	r = amdgpu_bo_reserve(fpriv->vm.root.bo, false);
696 	if (r)
697 		goto free_fence_drv;
698 
699 	if (amdgpu_userq_input_va_validate(adev, queue, args->in.queue_va,
700 					   args->in.queue_size,
701 					   &queue->userq_vas.va.queue_rb) ||
702 	    amdgpu_userq_input_va_validate(adev, queue, args->in.rptr_va,
703 					   AMDGPU_GPU_PAGE_SIZE,
704 					   &queue->userq_vas.va.rptr) ||
705 	    amdgpu_userq_input_va_validate(adev, queue, args->in.wptr_va,
706 					   AMDGPU_GPU_PAGE_SIZE,
707 					   &queue->userq_vas.va.wptr)) {
708 		r = -EINVAL;
709 		amdgpu_bo_unreserve(fpriv->vm.root.bo);
710 		goto free_fence_drv;
711 	}
712 	amdgpu_bo_unreserve(fpriv->vm.root.bo);
713 
714 	/* Convert relative doorbell offset into absolute doorbell index */
715 	db_info.queue_type = queue->queue_type;
716 	db_info.doorbell_handle = queue->doorbell_handle;
717 	db_info.db_obj = &queue->db_obj;
718 	db_info.doorbell_offset = args->in.doorbell_offset;
719 	r = amdgpu_userq_get_doorbell_index(uq_mgr, &db_info, filp, &index);
720 	if (r) {
721 		drm_file_err(uq_mgr->file, "Failed to get doorbell for queue\n");
722 		goto free_fence_drv;
723 	}
724 
725 	queue->doorbell_index = index;
726 	queue->doorbell_offset = (u32)args->in.doorbell_offset;
727 	trace_amdgpu_userq_create_start(queue);
728 	r = uq_funcs->mqd_create(queue, &args->in);
729 	if (r) {
730 		drm_file_err(uq_mgr->file, "Failed to create Queue\n");
731 		goto clean_doorbell_bo;
732 	}
733 
734 	/* Update VM owner at userq submit-time for page-fault attribution. */
735 	amdgpu_vm_set_task_info(&fpriv->vm);
736 
737 	r = xa_insert_irq(&adev->userq_doorbell_xa, index, queue,
738 			  GFP_KERNEL);
739 	if (r)
740 		goto clean_mqd;
741 
742 	amdgpu_userq_ensure_ev_fence(&fpriv->userq_mgr, &fpriv->evf_mgr);
743 
744 	/* don't map the queue if scheduling is halted */
745 	if (!adev->userq_halt_for_enforce_isolation ||
746 	    ((queue->queue_type != AMDGPU_HW_IP_GFX) &&
747 	     (queue->queue_type != AMDGPU_HW_IP_COMPUTE))) {
748 		/* Serialize the map against an in-progress GPU reset (MES is
749 		 * unresponsive during recovery), matching amdgpu_userq_cleanup().
750 		 */
751 		down_read(&adev->reset_domain->sem);
752 		r = amdgpu_userq_map_helper(queue);
753 		up_read(&adev->reset_domain->sem);
754 		if (r) {
755 			drm_file_err(uq_mgr->file, "Failed to map Queue\n");
756 			trace_amdgpu_userq_create_end(queue, r);
757 			mutex_unlock(&uq_mgr->userq_mutex);
758 			goto erase_doorbell;
759 		}
760 	}
761 
762 	atomic_inc(&uq_mgr->userq_count[queue->queue_type]);
763 	mutex_unlock(&uq_mgr->userq_mutex);
764 
765 	r = xa_alloc(&uq_mgr->userq_xa, &qid, queue,
766 		     XA_LIMIT(1, AMDGPU_MAX_USERQ_COUNT),
767 		     GFP_KERNEL);
768 	if (r) {
769 		/*
770 		 * This drops the last reference which should take care of
771 		 * all cleanup.
772 		 */
773 		trace_amdgpu_userq_create_end(queue, r);
774 		amdgpu_userq_put(queue);
775 		return r;
776 	}
777 
778 	amdgpu_debugfs_userq_init(filp, queue, qid);
779 	trace_amdgpu_userq_create_end(queue, 0);
780 	args->out.queue_id = qid;
781 	return 0;
782 
783 erase_doorbell:
784 	xa_erase_irq(&adev->userq_doorbell_xa, index);
785 clean_mqd:
786 	uq_funcs->mqd_destroy(queue);
787 clean_doorbell_bo:
788 	amdgpu_bo_reserve(queue->db_obj.obj, true);
789 	amdgpu_bo_unpin(queue->db_obj.obj);
790 	amdgpu_bo_unreserve(queue->db_obj.obj);
791 	amdgpu_bo_unref(&queue->db_obj.obj);
792 free_fence_drv:
793 	amdgpu_userq_fence_driver_free(queue);
794 free_queue:
795 	trace_amdgpu_userq_create_end(queue, r);
796 	kfree(queue);
797 err_pm_runtime:
798 	pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
799 	return r;
800 }
801 
802 static int amdgpu_userq_input_args_validate(struct drm_device *dev,
803 					union drm_amdgpu_userq *args,
804 					struct drm_file *filp)
805 {
806 	struct amdgpu_device *adev = drm_to_adev(dev);
807 
808 	switch (args->in.op) {
809 	case AMDGPU_USERQ_OP_CREATE:
810 		if (args->in.flags & ~(AMDGPU_USERQ_CREATE_FLAGS_QUEUE_PRIORITY_MASK |
811 				       AMDGPU_USERQ_CREATE_FLAGS_QUEUE_SECURE))
812 			return -EINVAL;
813 		/* Usermode queues are only supported for GFX IP as of now */
814 		if (args->in.ip_type != AMDGPU_HW_IP_GFX &&
815 		    args->in.ip_type != AMDGPU_HW_IP_DMA &&
816 		    args->in.ip_type != AMDGPU_HW_IP_COMPUTE) {
817 			drm_file_err(filp, "Usermode queue doesn't support IP type %u\n",
818 				     args->in.ip_type);
819 			return -EINVAL;
820 		}
821 
822 		if ((args->in.flags & AMDGPU_USERQ_CREATE_FLAGS_QUEUE_SECURE) &&
823 		    (args->in.ip_type != AMDGPU_HW_IP_GFX) &&
824 		    (args->in.ip_type != AMDGPU_HW_IP_COMPUTE) &&
825 		    !amdgpu_is_tmz(adev)) {
826 			drm_file_err(filp, "Secure only supported on GFX/Compute queues\n");
827 			return -EINVAL;
828 		}
829 
830 		if (args->in.queue_va == AMDGPU_BO_INVALID_OFFSET ||
831 		    args->in.queue_va == 0 ||
832 		    args->in.queue_size == 0) {
833 			drm_file_err(filp, "invalidate userq queue va or size\n");
834 			return -EINVAL;
835 		}
836 
837 		if (!is_power_of_2(args->in.queue_size)) {
838 			drm_file_err(filp, "Queue size must be a power of 2\n");
839 			return -EINVAL;
840 		}
841 
842 		if (args->in.queue_size < AMDGPU_GPU_PAGE_SIZE) {
843 			drm_file_err(filp, "Queue size smaller than AMDGPU_GPU_PAGE_SIZE\n");
844 			return -EINVAL;
845 		}
846 
847 		if (!args->in.wptr_va || !args->in.rptr_va) {
848 			drm_file_err(filp, "invalidate userq queue rptr or wptr\n");
849 			return -EINVAL;
850 		}
851 		break;
852 	case AMDGPU_USERQ_OP_FREE:
853 		if (args->in.ip_type ||
854 		    args->in.doorbell_handle ||
855 		    args->in.doorbell_offset ||
856 		    args->in.flags ||
857 		    args->in.queue_va ||
858 		    args->in.queue_size ||
859 		    args->in.rptr_va ||
860 		    args->in.wptr_va ||
861 		    args->in.mqd ||
862 		    args->in.mqd_size)
863 			return -EINVAL;
864 		break;
865 	default:
866 		return -EINVAL;
867 	}
868 
869 	return 0;
870 }
871 
872 bool amdgpu_userq_enabled(struct drm_device *dev)
873 {
874 	struct amdgpu_device *adev = drm_to_adev(dev);
875 	int i;
876 
877 	for (i = 0; i < AMDGPU_HW_IP_NUM; i++) {
878 		if (adev->userq_funcs[i])
879 			return true;
880 	}
881 
882 	return false;
883 }
884 
885 int amdgpu_userq_ioctl(struct drm_device *dev, void *data,
886 		       struct drm_file *filp)
887 {
888 	union drm_amdgpu_userq *args = data;
889 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
890 	struct amdgpu_usermode_queue *queue;
891 	int r = 0;
892 
893 	if (!amdgpu_userq_enabled(dev))
894 		return -ENOTSUPP;
895 
896 	if (amdgpu_userq_input_args_validate(dev, args, filp) < 0)
897 		return -EINVAL;
898 
899 	switch (args->in.op) {
900 	case AMDGPU_USERQ_OP_CREATE:
901 		r = amdgpu_userq_create(filp, args);
902 		if (r)
903 			drm_file_err(filp, "Failed to create usermode queue\n");
904 		break;
905 
906 	case AMDGPU_USERQ_OP_FREE: {
907 		xa_lock(&fpriv->userq_mgr.userq_xa);
908 		queue = __xa_erase(&fpriv->userq_mgr.userq_xa, args->in.queue_id);
909 		xa_unlock(&fpriv->userq_mgr.userq_xa);
910 		if (!queue)
911 			return -ENOENT;
912 
913 		amdgpu_userq_put(queue);
914 		break;
915 	}
916 
917 	default:
918 		drm_dbg_driver(dev, "Invalid user queue op specified: %d\n", args->in.op);
919 		return -EINVAL;
920 	}
921 
922 	return r;
923 }
924 
925 static int
926 amdgpu_userq_restore_all(struct amdgpu_userq_mgr *uq_mgr)
927 {
928 	struct amdgpu_usermode_queue *queue;
929 	unsigned long queue_id;
930 	int ret = 0, r;
931 
932 	mutex_lock(&uq_mgr->userq_mutex);
933 	/* Resume all the queues for this process */
934 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
935 
936 		if (!amdgpu_userq_buffer_vas_mapped(queue)) {
937 			drm_file_err(uq_mgr->file,
938 				     "trying restore queue without va mapping\n");
939 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_INVALID_VA);
940 			queue->state = AMDGPU_USERQ_STATE_INVALID_VA;
941 			continue;
942 		}
943 
944 		r = amdgpu_userq_map_helper(queue);
945 		if (r)
946 			ret = r;
947 	}
948 	mutex_unlock(&uq_mgr->userq_mutex);
949 
950 	if (ret)
951 		drm_file_err(uq_mgr->file,
952 			     "Failed to map all the queues, restore failed ret=%d\n", ret);
953 	return ret;
954 }
955 
956 static int amdgpu_userq_validate_vm(void *param, struct amdgpu_bo *bo)
957 {
958 	struct ttm_operation_ctx ctx = { false, false };
959 
960 	amdgpu_bo_placement_from_domain(bo, bo->allowed_domains);
961 	return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
962 }
963 
964 /* Handle all BOs on the invalidated list, validate them and update the PTs */
965 static int
966 amdgpu_userq_bo_validate(struct amdgpu_device *adev, struct drm_exec *exec,
967 			 struct amdgpu_vm *vm)
968 {
969 	struct ttm_operation_ctx ctx = { false, false };
970 	struct amdgpu_bo_va *bo_va;
971 	struct amdgpu_bo *bo;
972 	int ret;
973 
974 	spin_lock(&vm->individual_lock);
975 	while (!list_empty(&vm->always_valid.evicted)) {
976 		bo_va = list_first_entry(&vm->always_valid.evicted,
977 					 struct amdgpu_bo_va,
978 					 base.vm_status);
979 		spin_unlock(&vm->individual_lock);
980 
981 		bo = bo_va->base.bo;
982 		ret = drm_exec_prepare_obj(exec, &bo->tbo.base,
983 					   TTM_NUM_MOVE_FENCES + 1);
984 		if (unlikely(ret))
985 			return ret;
986 
987 		amdgpu_bo_placement_from_domain(bo, bo->allowed_domains);
988 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
989 		if (ret)
990 			return ret;
991 
992 		/* This moves the bo_va to the idle list */
993 		ret = amdgpu_vm_bo_update(adev, bo_va, false);
994 		if (ret)
995 			return ret;
996 
997 		spin_lock(&vm->individual_lock);
998 	}
999 	spin_unlock(&vm->individual_lock);
1000 
1001 	return 0;
1002 }
1003 
1004 /* Make sure the whole VM is ready to be used */
1005 static int
1006 amdgpu_userq_vm_validate_and_restore_queue(struct amdgpu_userq_mgr *uq_mgr)
1007 {
1008 	struct amdgpu_fpriv *fpriv = uq_mgr_to_fpriv(uq_mgr);
1009 	bool invalidated = false, new_addition = false;
1010 	struct ttm_operation_ctx ctx = { true, false };
1011 	struct amdgpu_device *adev = uq_mgr->adev;
1012 	struct amdgpu_hmm_range *range;
1013 	struct amdgpu_vm *vm = &fpriv->vm;
1014 	unsigned long key, tmp_key;
1015 	struct amdgpu_bo_va *bo_va;
1016 	struct amdgpu_usermode_queue *queue;
1017 	struct amdgpu_bo *bo;
1018 	struct drm_exec exec;
1019 	struct xarray xa;
1020 	int ret;
1021 
1022 	xa_init(&xa);
1023 
1024 retry_lock:
1025 	drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);
1026 	drm_exec_until_all_locked(&exec) {
1027 		ret = amdgpu_vm_lock_pd(vm, &exec, 1);
1028 		drm_exec_retry_on_contention(&exec);
1029 		if (unlikely(ret))
1030 			goto unlock_all;
1031 
1032 		ret = amdgpu_vm_lock_individual(vm, &exec, TTM_NUM_MOVE_FENCES + 1);
1033 		drm_exec_retry_on_contention(&exec);
1034 		if (unlikely(ret))
1035 			goto unlock_all;
1036 
1037 		/* This validates PDs, PTs and per VM BOs */
1038 		ret = amdgpu_vm_validate(adev, vm, NULL,
1039 					 amdgpu_userq_validate_vm,
1040 					 NULL);
1041 		if (unlikely(ret))
1042 			goto unlock_all;
1043 
1044 		/* This locks and validates the remaining evicted BOs */
1045 		ret = amdgpu_userq_bo_validate(adev, &exec, vm);
1046 		drm_exec_retry_on_contention(&exec);
1047 		if (unlikely(ret))
1048 			goto unlock_all;
1049 	}
1050 
1051 	if (invalidated) {
1052 		xa_for_each(&xa, tmp_key, range) {
1053 			bo = range->bo;
1054 			amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
1055 			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1056 			if (ret)
1057 				goto unlock_all;
1058 
1059 			amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, range);
1060 
1061 			amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
1062 			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1063 			if (ret)
1064 				goto unlock_all;
1065 		}
1066 		invalidated = false;
1067 	}
1068 
1069 	ret = amdgpu_vm_handle_moved(adev, vm, NULL);
1070 	if (ret)
1071 		goto unlock_all;
1072 
1073 	key = 0;
1074 	/* Validate User Ptr BOs */
1075 	list_for_each_entry(bo_va, &vm->always_valid.idle, base.vm_status) {
1076 		bo = bo_va->base.bo;
1077 		if (!bo)
1078 			continue;
1079 
1080 		if (!amdgpu_ttm_tt_is_userptr(bo->tbo.ttm))
1081 			continue;
1082 
1083 		range = xa_load(&xa, key);
1084 		if (range && range->bo != bo) {
1085 			xa_erase(&xa, key);
1086 			amdgpu_hmm_range_free(range);
1087 			range = NULL;
1088 		}
1089 
1090 		if (!range) {
1091 			range = amdgpu_hmm_range_alloc(bo);
1092 			if (!range) {
1093 				ret = -ENOMEM;
1094 				goto unlock_all;
1095 			}
1096 
1097 			xa_store(&xa, key, range, GFP_KERNEL);
1098 			new_addition = true;
1099 		}
1100 		key++;
1101 	}
1102 
1103 	if (new_addition) {
1104 		drm_exec_fini(&exec);
1105 		xa_for_each(&xa, tmp_key, range) {
1106 			if (!range)
1107 				continue;
1108 			bo = range->bo;
1109 			ret = amdgpu_ttm_tt_get_user_pages(bo, range);
1110 			if (ret)
1111 				goto free_ranges;
1112 		}
1113 
1114 		invalidated = true;
1115 		new_addition = false;
1116 		goto retry_lock;
1117 	}
1118 
1119 	ret = amdgpu_vm_update_pdes(adev, vm, false);
1120 	if (ret)
1121 		goto unlock_all;
1122 
1123 	/*
1124 	 * We need to wait for all VM updates to finish before restarting the
1125 	 * queues. Using the idle list like that is now ok since everything is
1126 	 * locked in place.
1127 	 */
1128 	list_for_each_entry(bo_va, &vm->always_valid.idle, base.vm_status)
1129 		dma_fence_wait(bo_va->last_pt_update, false);
1130 	dma_fence_wait(vm->last_update, false);
1131 
1132 	xa_for_each(&uq_mgr->userq_xa, tmp_key, queue) {
1133 		bo = queue->wptr_obj.obj;
1134 		if (!bo) {
1135 			ret = -EINVAL;
1136 			goto unlock_all;
1137 		}
1138 
1139 		ret = amdgpu_ttm_alloc_gart(&bo->tbo);
1140 		if (unlikely(ret)) {
1141 			drm_file_err(uq_mgr->file,
1142 				     "failed to bind wptr bo to gart on resume, qid=%lu ret=%d\n",
1143 				     tmp_key, ret);
1144 			goto unlock_all;
1145 		}
1146 
1147 		queue->wptr_obj.gpu_addr = amdgpu_bo_gpu_offset(bo);
1148 	}
1149 
1150 	ret = amdgpu_evf_mgr_rearm(&fpriv->evf_mgr, &exec);
1151 	if (ret) {
1152 		drm_file_err(uq_mgr->file, "Failed to replace eviction fence\n");
1153 		goto unlock_all;
1154 	}
1155 
1156 	ret = amdgpu_userq_restore_all(uq_mgr);
1157 
1158 unlock_all:
1159 	drm_exec_fini(&exec);
1160 free_ranges:
1161 	xa_for_each(&xa, tmp_key, range) {
1162 		if (!range)
1163 			continue;
1164 		bo = range->bo;
1165 		amdgpu_hmm_range_free(range);
1166 	}
1167 	xa_destroy(&xa);
1168 	return ret;
1169 }
1170 
1171 static void amdgpu_userq_restore_worker(struct work_struct *work)
1172 {
1173 	struct amdgpu_userq_mgr *uq_mgr = work_to_uq_mgr(work, resume_work.work);
1174 	struct amdgpu_fpriv *fpriv = uq_mgr_to_fpriv(uq_mgr);
1175 	struct dma_fence *ev_fence;
1176 	int ret;
1177 
1178 	ev_fence = amdgpu_evf_mgr_get_fence(&fpriv->evf_mgr);
1179 	if (!dma_fence_is_signaled(ev_fence))
1180 		goto put_fence;
1181 
1182 	ret = amdgpu_userq_vm_validate_and_restore_queue(uq_mgr);
1183 	if (ret) {
1184 		drm_file_err(uq_mgr->file, "Failed to validate BOs to restore ret=%d\n", ret);
1185 		goto put_fence;
1186 	}
1187 
1188 put_fence:
1189 	dma_fence_put(ev_fence);
1190 }
1191 
1192 void amdgpu_userq_process_reset_irq(struct amdgpu_device *adev,
1193 				    u32 pasid, u32 doorbell_offset)
1194 {
1195 	struct xarray *xa = &adev->userq_doorbell_xa;
1196 	struct amdgpu_usermode_queue *queue;
1197 	unsigned long flags, idx;
1198 
1199 	xa_lock_irqsave(xa, flags);
1200 	xa_for_each(xa, idx, queue) {
1201 		if (queue->vm && queue->vm->pasid == pasid &&
1202 		    queue->doorbell_offset == doorbell_offset) {
1203 			amdgpu_userq_start_hang_detect_work(queue);
1204 			break;
1205 		}
1206 	}
1207 	xa_unlock_irqrestore(xa, flags);
1208 }
1209 
1210 static int
1211 amdgpu_userq_evict_all(struct amdgpu_userq_mgr *uq_mgr)
1212 {
1213 	struct amdgpu_usermode_queue *queue;
1214 	unsigned long queue_id;
1215 	int ret = 0, r;
1216 
1217 	/* Try to unmap all the queues in this process ctx */
1218 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
1219 		r = amdgpu_userq_unmap_helper(queue);
1220 		if (r)
1221 			ret = r;
1222 	}
1223 
1224 	if (ret) {
1225 		drm_file_err(uq_mgr->file,
1226 			     "Couldn't unmap all the queues, eviction failed ret=%d\n", ret);
1227 		amdgpu_reset_domain_schedule(uq_mgr->adev->reset_domain,
1228 					     &uq_mgr->reset_work);
1229 		flush_work(&uq_mgr->reset_work);
1230 	}
1231 	return ret;
1232 }
1233 
1234 static void
1235 amdgpu_userq_wait_for_signal(struct amdgpu_userq_mgr *uq_mgr)
1236 {
1237 	struct amdgpu_usermode_queue *queue;
1238 	unsigned long queue_id;
1239 
1240 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
1241 		struct dma_fence *f = queue->last_fence;
1242 
1243 		if (!f)
1244 			continue;
1245 
1246 		dma_fence_wait(f, false);
1247 	}
1248 }
1249 
1250 void
1251 amdgpu_userq_evict(struct amdgpu_userq_mgr *uq_mgr)
1252 {
1253 	/* Wait for any pending userqueue fence work to finish */
1254 	amdgpu_userq_wait_for_signal(uq_mgr);
1255 	amdgpu_userq_evict_all(uq_mgr);
1256 }
1257 
1258 int amdgpu_userq_mgr_init(struct amdgpu_userq_mgr *userq_mgr, struct drm_file *file_priv,
1259 			  struct amdgpu_device *adev)
1260 {
1261 	mutex_init(&userq_mgr->userq_mutex);
1262 	xa_init_flags(&userq_mgr->userq_xa, XA_FLAGS_ALLOC);
1263 	userq_mgr->adev = adev;
1264 	userq_mgr->file = file_priv;
1265 	mutex_init(&userq_mgr->proc_ctx_lock);
1266 
1267 	INIT_DELAYED_WORK(&userq_mgr->resume_work, amdgpu_userq_restore_worker);
1268 	INIT_WORK(&userq_mgr->reset_work, amdgpu_userq_mgr_reset_work);
1269 	return 0;
1270 }
1271 
1272 void amdgpu_userq_mgr_cancel_reset_work(struct amdgpu_device *adev)
1273 {
1274 	struct xarray *xa = &adev->userq_doorbell_xa;
1275 	struct amdgpu_usermode_queue *queue;
1276 	unsigned long flags, queue_id;
1277 
1278 	xa_lock_irqsave(xa, flags);
1279 	xa_for_each(xa, queue_id, queue) {
1280 		cancel_delayed_work(&queue->hang_detect_work);
1281 		cancel_work(&queue->userq_mgr->reset_work);
1282 	}
1283 	xa_unlock_irqrestore(xa, flags);
1284 }
1285 
1286 void amdgpu_userq_mgr_cancel_resume(struct amdgpu_userq_mgr *userq_mgr)
1287 {
1288 	cancel_delayed_work_sync(&userq_mgr->resume_work);
1289 }
1290 
1291 void amdgpu_userq_mgr_fini(struct amdgpu_userq_mgr *userq_mgr)
1292 {
1293 	struct amdgpu_usermode_queue *queue;
1294 	unsigned long queue_id = 0;
1295 
1296 	for (;;) {
1297 		xa_lock(&userq_mgr->userq_xa);
1298 		queue = xa_find(&userq_mgr->userq_xa, &queue_id, ULONG_MAX,
1299 				XA_PRESENT);
1300 		if (queue)
1301 			__xa_erase(&userq_mgr->userq_xa, queue_id);
1302 		xa_unlock(&userq_mgr->userq_xa);
1303 
1304 		if (!queue)
1305 			break;
1306 
1307 		amdgpu_userq_put(queue);
1308 	}
1309 
1310 	xa_destroy(&userq_mgr->userq_xa);
1311 
1312 	/*
1313 	 * Drain any in-flight reset_work. By this point all queues are freed
1314 	 * and userq_count is 0, so if reset_work starts now it exits early.
1315 	 * We still need to wait in case it was already executing gpu_recover.
1316 	 */
1317 	cancel_work_sync(&userq_mgr->reset_work);
1318 
1319 	amdgpu_bo_free_kernel(&userq_mgr->proc_ctx_obj.obj,
1320 			      &userq_mgr->proc_ctx_obj.gpu_addr,
1321 			      &userq_mgr->proc_ctx_obj.cpu_ptr);
1322 
1323 	mutex_destroy(&userq_mgr->proc_ctx_lock);
1324 	mutex_destroy(&userq_mgr->userq_mutex);
1325 }
1326 
1327 int amdgpu_userq_suspend(struct amdgpu_device *adev)
1328 {
1329 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1330 	struct amdgpu_usermode_queue *queue;
1331 	struct amdgpu_userq_mgr *uqm;
1332 	unsigned long queue_id;
1333 	int r;
1334 
1335 	if (!ip_mask)
1336 		return 0;
1337 
1338 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1339 		uqm = queue->userq_mgr;
1340 		cancel_delayed_work_sync(&uqm->resume_work);
1341 		guard(mutex)(&uqm->userq_mutex);
1342 		if (adev->in_s0ix)
1343 			r = amdgpu_userq_preempt_helper(queue);
1344 		else
1345 			r = amdgpu_userq_unmap_helper(queue);
1346 		if (r)
1347 			return r;
1348 	}
1349 	return 0;
1350 }
1351 
1352 int amdgpu_userq_resume(struct amdgpu_device *adev)
1353 {
1354 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1355 	struct amdgpu_usermode_queue *queue;
1356 	struct amdgpu_userq_mgr *uqm;
1357 	unsigned long queue_id;
1358 	int r;
1359 
1360 	if (!ip_mask)
1361 		return 0;
1362 
1363 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1364 		uqm = queue->userq_mgr;
1365 		guard(mutex)(&uqm->userq_mutex);
1366 		if (adev->in_s0ix)
1367 			r = amdgpu_userq_restore_helper(queue);
1368 		else
1369 			r = amdgpu_userq_map_helper(queue);
1370 		if (r)
1371 			return r;
1372 	}
1373 
1374 	return 0;
1375 }
1376 
1377 int amdgpu_userq_stop_sched_for_enforce_isolation(struct amdgpu_device *adev,
1378 						  u32 idx)
1379 {
1380 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1381 	struct amdgpu_usermode_queue *queue;
1382 	struct amdgpu_userq_mgr *uqm;
1383 	unsigned long queue_id;
1384 	int ret = 0, r;
1385 
1386 	/* only need to stop gfx/compute */
1387 	if (!(ip_mask & ((1 << AMDGPU_HW_IP_GFX) | (1 << AMDGPU_HW_IP_COMPUTE))))
1388 		return 0;
1389 
1390 	if (adev->userq_halt_for_enforce_isolation)
1391 		dev_warn(adev->dev, "userq scheduling already stopped!\n");
1392 	adev->userq_halt_for_enforce_isolation = true;
1393 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1394 		uqm = queue->userq_mgr;
1395 		cancel_delayed_work_sync(&uqm->resume_work);
1396 		mutex_lock(&uqm->userq_mutex);
1397 		if (((queue->queue_type == AMDGPU_HW_IP_GFX) ||
1398 		     (queue->queue_type == AMDGPU_HW_IP_COMPUTE)) &&
1399 		    (queue->xcp_id == idx)) {
1400 			r = amdgpu_userq_preempt_helper(queue);
1401 			if (r)
1402 				ret = r;
1403 		}
1404 		mutex_unlock(&uqm->userq_mutex);
1405 	}
1406 
1407 	return ret;
1408 }
1409 
1410 int amdgpu_userq_start_sched_for_enforce_isolation(struct amdgpu_device *adev,
1411 						   u32 idx)
1412 {
1413 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1414 	struct amdgpu_usermode_queue *queue;
1415 	struct amdgpu_userq_mgr *uqm;
1416 	unsigned long queue_id;
1417 	int ret = 0, r;
1418 
1419 	/* only need to stop gfx/compute */
1420 	if (!(ip_mask & ((1 << AMDGPU_HW_IP_GFX) | (1 << AMDGPU_HW_IP_COMPUTE))))
1421 		return 0;
1422 
1423 	if (!adev->userq_halt_for_enforce_isolation)
1424 		dev_warn(adev->dev, "userq scheduling already started!\n");
1425 
1426 	adev->userq_halt_for_enforce_isolation = false;
1427 
1428 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1429 		uqm = queue->userq_mgr;
1430 		mutex_lock(&uqm->userq_mutex);
1431 		if (((queue->queue_type == AMDGPU_HW_IP_GFX) ||
1432 		     (queue->queue_type == AMDGPU_HW_IP_COMPUTE)) &&
1433 		    (queue->xcp_id == idx)) {
1434 			r = amdgpu_userq_restore_helper(queue);
1435 			if (r)
1436 				ret = r;
1437 		}
1438 		mutex_unlock(&uqm->userq_mutex);
1439 	}
1440 
1441 	return ret;
1442 }
1443 
1444 void amdgpu_userq_gem_va_unmap_validate(struct amdgpu_device *adev,
1445 					struct amdgpu_bo_va_mapping *mapping)
1446 {
1447 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1448 	struct amdgpu_bo_va *bo_va = mapping->bo_va;
1449 	struct dma_resv *resv = bo_va->base.bo->tbo.base.resv;
1450 
1451 	if (!ip_mask)
1452 		return;
1453 
1454 	/**
1455 	 * The userq VA mapping reservation should include the eviction fence.
1456 	 * Note: The eviction fence may be attached to different BOs and this
1457 	 * unmap is only for one kind of userq VAs, so at this point suppose
1458 	 * the eviction fence is always unsignaled.
1459 	 */
1460 	dma_resv_wait_timeout(resv, DMA_RESV_USAGE_BOOKKEEP,
1461 			      false, MAX_SCHEDULE_TIMEOUT);
1462 }
1463 
1464 void amdgpu_userq_pre_reset(struct amdgpu_device *adev)
1465 {
1466 	const struct amdgpu_userq_funcs *userq_funcs;
1467 	struct amdgpu_usermode_queue *queue;
1468 	unsigned long queue_id;
1469 
1470 	/* TODO: We probably need a new lock for the queue state */
1471 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1472 		if (queue->state == AMDGPU_USERQ_STATE_MAPPED) {
1473 			trace_amdgpu_userq_state_start(queue);
1474 			userq_funcs = adev->userq_funcs[queue->queue_type];
1475 			userq_funcs->unmap(queue);
1476 			/* just mark all queues as hung at this point.
1477 			 * if unmap succeeds, we could map again
1478 			 * in amdgpu_userq_post_reset() if vram is not lost
1479 			 */
1480 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_HUNG);
1481 			queue->state = AMDGPU_USERQ_STATE_HUNG;
1482 		}
1483 		/* Force-complete any pending fence regardless of queue state so
1484 		 * that eviction/suspend and queue teardown waiters don't block
1485 		 * forever on a fence that will never signal after the reset.
1486 		 */
1487 		amdgpu_userq_fence_driver_force_completion(queue);
1488 	}
1489 }
1490 
1491 int amdgpu_userq_post_reset(struct amdgpu_device *adev, bool vram_lost)
1492 {
1493 	/* if any queue state is AMDGPU_USERQ_STATE_UNMAPPED
1494 	 * at this point, we should be able to map it again
1495 	 * and continue if vram is not lost.
1496 	 */
1497 	struct amdgpu_usermode_queue *queue;
1498 	const struct amdgpu_userq_funcs *userq_funcs;
1499 	unsigned long queue_id;
1500 	int r = 0;
1501 
1502 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1503 		if (queue->state == AMDGPU_USERQ_STATE_HUNG && !vram_lost) {
1504 			trace_amdgpu_userq_state_start(queue);
1505 
1506 			userq_funcs = adev->userq_funcs[queue->queue_type];
1507 			/* Re-map queue */
1508 			r = userq_funcs->map(queue);
1509 			if (r) {
1510 				dev_err(adev->dev, "Failed to remap queue %ld\n", queue_id);
1511 				continue;
1512 			}
1513 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_MAPPED);
1514 			queue->state = AMDGPU_USERQ_STATE_MAPPED;
1515 		}
1516 	}
1517 
1518 	return r;
1519 }
1520