xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c (revision 570f7e331f5febb30f1384817463c7e42b65ca7d)
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 	/*
1074 	 * PRT/sparse mappings are kept off the vm_bo state lists, so
1075 	 * amdgpu_vm_handle_moved() does not touch them. Refresh their PTEs
1076 	 * explicitly here (as the CS path does) so sparse mappings survive a
1077 	 * VRAM-lost reset.
1078 	 */
1079 	ret = amdgpu_vm_bo_update(adev, fpriv->prt_va, false);
1080 	if (ret)
1081 		goto unlock_all;
1082 
1083 	key = 0;
1084 	/* Validate User Ptr BOs */
1085 	list_for_each_entry(bo_va, &vm->always_valid.idle, base.vm_status) {
1086 		bo = bo_va->base.bo;
1087 		if (!bo)
1088 			continue;
1089 
1090 		if (!amdgpu_ttm_tt_is_userptr(bo->tbo.ttm))
1091 			continue;
1092 
1093 		range = xa_load(&xa, key);
1094 		if (range && range->bo != bo) {
1095 			xa_erase(&xa, key);
1096 			amdgpu_hmm_range_free(range);
1097 			range = NULL;
1098 		}
1099 
1100 		if (!range) {
1101 			range = amdgpu_hmm_range_alloc(bo);
1102 			if (!range) {
1103 				ret = -ENOMEM;
1104 				goto unlock_all;
1105 			}
1106 
1107 			xa_store(&xa, key, range, GFP_KERNEL);
1108 			new_addition = true;
1109 		}
1110 		key++;
1111 	}
1112 
1113 	if (new_addition) {
1114 		drm_exec_fini(&exec);
1115 		xa_for_each(&xa, tmp_key, range) {
1116 			if (!range)
1117 				continue;
1118 			bo = range->bo;
1119 			ret = amdgpu_ttm_tt_get_user_pages(bo, range);
1120 			if (ret)
1121 				goto free_ranges;
1122 		}
1123 
1124 		invalidated = true;
1125 		new_addition = false;
1126 		goto retry_lock;
1127 	}
1128 
1129 	ret = amdgpu_vm_update_pdes(adev, vm, false);
1130 	if (ret)
1131 		goto unlock_all;
1132 
1133 	/*
1134 	 * We need to wait for all VM updates to finish before restarting the
1135 	 * queues. Using the idle list like that is now ok since everything is
1136 	 * locked in place.
1137 	 */
1138 	list_for_each_entry(bo_va, &vm->always_valid.idle, base.vm_status)
1139 		dma_fence_wait(bo_va->last_pt_update, false);
1140 	/*
1141 	 * The PRT bo_va is kept off the state lists, so its PTE update fence
1142 	 * lands in prt_va->last_pt_update rather than vm->last_update; wait on
1143 	 * it explicitly (as the CS path syncs it) before restarting queues.
1144 	 */
1145 	dma_fence_wait(fpriv->prt_va->last_pt_update, false);
1146 	dma_fence_wait(vm->last_update, false);
1147 
1148 	xa_for_each(&uq_mgr->userq_xa, tmp_key, queue) {
1149 		bo = queue->wptr_obj.obj;
1150 		if (!bo) {
1151 			ret = -EINVAL;
1152 			goto unlock_all;
1153 		}
1154 
1155 		ret = amdgpu_ttm_alloc_gart(&bo->tbo);
1156 		if (unlikely(ret)) {
1157 			drm_file_err(uq_mgr->file,
1158 				     "failed to bind wptr bo to gart on resume, qid=%lu ret=%d\n",
1159 				     tmp_key, ret);
1160 			goto unlock_all;
1161 		}
1162 
1163 		queue->wptr_obj.gpu_addr = amdgpu_bo_gpu_offset(bo);
1164 	}
1165 
1166 	ret = amdgpu_evf_mgr_rearm(&fpriv->evf_mgr, &exec);
1167 	if (ret) {
1168 		drm_file_err(uq_mgr->file, "Failed to replace eviction fence\n");
1169 		goto unlock_all;
1170 	}
1171 
1172 	ret = amdgpu_userq_restore_all(uq_mgr);
1173 
1174 unlock_all:
1175 	drm_exec_fini(&exec);
1176 free_ranges:
1177 	xa_for_each(&xa, tmp_key, range) {
1178 		if (!range)
1179 			continue;
1180 		bo = range->bo;
1181 		amdgpu_hmm_range_free(range);
1182 	}
1183 	xa_destroy(&xa);
1184 	return ret;
1185 }
1186 
1187 static void amdgpu_userq_restore_worker(struct work_struct *work)
1188 {
1189 	struct amdgpu_userq_mgr *uq_mgr = work_to_uq_mgr(work, resume_work.work);
1190 	struct amdgpu_fpriv *fpriv = uq_mgr_to_fpriv(uq_mgr);
1191 	struct dma_fence *ev_fence;
1192 	int ret;
1193 
1194 	ev_fence = amdgpu_evf_mgr_get_fence(&fpriv->evf_mgr);
1195 	if (!dma_fence_is_signaled(ev_fence))
1196 		goto put_fence;
1197 
1198 	ret = amdgpu_userq_vm_validate_and_restore_queue(uq_mgr);
1199 	if (ret) {
1200 		drm_file_err(uq_mgr->file, "Failed to validate BOs to restore ret=%d\n", ret);
1201 		goto put_fence;
1202 	}
1203 
1204 put_fence:
1205 	dma_fence_put(ev_fence);
1206 }
1207 
1208 void amdgpu_userq_process_reset_irq(struct amdgpu_device *adev,
1209 				    u32 pasid, u32 doorbell_offset)
1210 {
1211 	struct xarray *xa = &adev->userq_doorbell_xa;
1212 	struct amdgpu_usermode_queue *queue;
1213 	unsigned long flags, idx;
1214 
1215 	xa_lock_irqsave(xa, flags);
1216 	xa_for_each(xa, idx, queue) {
1217 		if (queue->vm && queue->vm->pasid == pasid &&
1218 		    queue->doorbell_offset == doorbell_offset) {
1219 			amdgpu_userq_start_hang_detect_work(queue);
1220 			break;
1221 		}
1222 	}
1223 	xa_unlock_irqrestore(xa, flags);
1224 }
1225 
1226 static int
1227 amdgpu_userq_evict_all(struct amdgpu_userq_mgr *uq_mgr)
1228 {
1229 	struct amdgpu_usermode_queue *queue;
1230 	unsigned long queue_id;
1231 	int ret = 0, r;
1232 
1233 	/* Try to unmap all the queues in this process ctx */
1234 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
1235 		r = amdgpu_userq_unmap_helper(queue);
1236 		if (r)
1237 			ret = r;
1238 	}
1239 
1240 	if (ret) {
1241 		drm_file_err(uq_mgr->file,
1242 			     "Couldn't unmap all the queues, eviction failed ret=%d\n", ret);
1243 		amdgpu_reset_domain_schedule(uq_mgr->adev->reset_domain,
1244 					     &uq_mgr->reset_work);
1245 		flush_work(&uq_mgr->reset_work);
1246 	}
1247 	return ret;
1248 }
1249 
1250 static void
1251 amdgpu_userq_wait_for_signal(struct amdgpu_userq_mgr *uq_mgr)
1252 {
1253 	struct amdgpu_usermode_queue *queue;
1254 	unsigned long queue_id;
1255 
1256 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
1257 		struct dma_fence *f = queue->last_fence;
1258 
1259 		if (!f)
1260 			continue;
1261 
1262 		dma_fence_wait(f, false);
1263 	}
1264 }
1265 
1266 void
1267 amdgpu_userq_evict(struct amdgpu_userq_mgr *uq_mgr)
1268 {
1269 	/* Wait for any pending userqueue fence work to finish */
1270 	amdgpu_userq_wait_for_signal(uq_mgr);
1271 	amdgpu_userq_evict_all(uq_mgr);
1272 }
1273 
1274 int amdgpu_userq_mgr_init(struct amdgpu_userq_mgr *userq_mgr, struct drm_file *file_priv,
1275 			  struct amdgpu_device *adev)
1276 {
1277 	mutex_init(&userq_mgr->userq_mutex);
1278 	xa_init_flags(&userq_mgr->userq_xa, XA_FLAGS_ALLOC);
1279 	userq_mgr->adev = adev;
1280 	userq_mgr->file = file_priv;
1281 	userq_mgr->proc_ctx_allocated = false;
1282 	mutex_init(&userq_mgr->proc_ctx_lock);
1283 
1284 	INIT_DELAYED_WORK(&userq_mgr->resume_work, amdgpu_userq_restore_worker);
1285 	INIT_WORK(&userq_mgr->reset_work, amdgpu_userq_mgr_reset_work);
1286 	return 0;
1287 }
1288 
1289 void amdgpu_userq_mgr_cancel_reset_work(struct amdgpu_device *adev)
1290 {
1291 	struct xarray *xa = &adev->userq_doorbell_xa;
1292 	struct amdgpu_usermode_queue *queue;
1293 	unsigned long flags, queue_id;
1294 
1295 	xa_lock_irqsave(xa, flags);
1296 	xa_for_each(xa, queue_id, queue) {
1297 		cancel_delayed_work(&queue->hang_detect_work);
1298 		cancel_work(&queue->userq_mgr->reset_work);
1299 	}
1300 	xa_unlock_irqrestore(xa, flags);
1301 }
1302 
1303 void amdgpu_userq_mgr_cancel_resume(struct amdgpu_userq_mgr *userq_mgr)
1304 {
1305 	cancel_delayed_work_sync(&userq_mgr->resume_work);
1306 }
1307 
1308 void amdgpu_userq_mgr_fini(struct amdgpu_userq_mgr *userq_mgr)
1309 {
1310 	struct amdgpu_mes *mes = &userq_mgr->adev->mes;
1311 	struct amdgpu_usermode_queue *queue;
1312 	unsigned long queue_id = 0;
1313 
1314 	for (;;) {
1315 		xa_lock(&userq_mgr->userq_xa);
1316 		queue = xa_find(&userq_mgr->userq_xa, &queue_id, ULONG_MAX,
1317 				XA_PRESENT);
1318 		if (queue)
1319 			__xa_erase(&userq_mgr->userq_xa, queue_id);
1320 		xa_unlock(&userq_mgr->userq_xa);
1321 
1322 		if (!queue)
1323 			break;
1324 
1325 		amdgpu_userq_put(queue);
1326 	}
1327 
1328 	xa_destroy(&userq_mgr->userq_xa);
1329 
1330 	/*
1331 	 * Drain any in-flight reset_work. By this point all queues are freed
1332 	 * and userq_count is 0, so if reset_work starts now it exits early.
1333 	 * We still need to wait in case it was already executing gpu_recover.
1334 	 */
1335 	cancel_work_sync(&userq_mgr->reset_work);
1336 
1337 	if (userq_mgr->proc_ctx_allocated) {
1338 		amdgpu_mes_free_proc_ctx_index(mes, userq_mgr->proc_ctx_array_index);
1339 		userq_mgr->proc_ctx_allocated = false;
1340 	}
1341 	amdgpu_bo_free_kernel(&userq_mgr->proc_ctx_obj.obj,
1342 			      &userq_mgr->proc_ctx_obj.gpu_addr,
1343 			      &userq_mgr->proc_ctx_obj.cpu_ptr);
1344 
1345 	mutex_destroy(&userq_mgr->proc_ctx_lock);
1346 	mutex_destroy(&userq_mgr->userq_mutex);
1347 }
1348 
1349 int amdgpu_userq_suspend(struct amdgpu_device *adev)
1350 {
1351 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1352 	struct amdgpu_usermode_queue *queue;
1353 	struct amdgpu_userq_mgr *uqm;
1354 	unsigned long queue_id;
1355 	int r;
1356 
1357 	if (!ip_mask)
1358 		return 0;
1359 
1360 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1361 		uqm = queue->userq_mgr;
1362 		cancel_delayed_work_sync(&uqm->resume_work);
1363 		guard(mutex)(&uqm->userq_mutex);
1364 		if (adev->in_s0ix)
1365 			r = amdgpu_userq_preempt_helper(queue);
1366 		else
1367 			r = amdgpu_userq_unmap_helper(queue);
1368 		if (r)
1369 			return r;
1370 	}
1371 	return 0;
1372 }
1373 
1374 int amdgpu_userq_resume(struct amdgpu_device *adev)
1375 {
1376 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1377 	struct amdgpu_usermode_queue *queue;
1378 	struct amdgpu_userq_mgr *uqm;
1379 	unsigned long queue_id;
1380 	int r;
1381 
1382 	if (!ip_mask)
1383 		return 0;
1384 
1385 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1386 		uqm = queue->userq_mgr;
1387 		guard(mutex)(&uqm->userq_mutex);
1388 		if (adev->in_s0ix)
1389 			r = amdgpu_userq_restore_helper(queue);
1390 		else
1391 			r = amdgpu_userq_map_helper(queue);
1392 		if (r)
1393 			return r;
1394 	}
1395 
1396 	return 0;
1397 }
1398 
1399 int amdgpu_userq_stop_sched_for_enforce_isolation(struct amdgpu_device *adev,
1400 						  u32 idx)
1401 {
1402 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1403 	struct amdgpu_usermode_queue *queue;
1404 	struct amdgpu_userq_mgr *uqm;
1405 	unsigned long queue_id;
1406 	int ret = 0, r;
1407 
1408 	/* only need to stop gfx/compute */
1409 	if (!(ip_mask & ((1 << AMDGPU_HW_IP_GFX) | (1 << AMDGPU_HW_IP_COMPUTE))))
1410 		return 0;
1411 
1412 	if (adev->userq_halt_for_enforce_isolation)
1413 		dev_warn(adev->dev, "userq scheduling already stopped!\n");
1414 	adev->userq_halt_for_enforce_isolation = true;
1415 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1416 		uqm = queue->userq_mgr;
1417 		cancel_delayed_work_sync(&uqm->resume_work);
1418 		mutex_lock(&uqm->userq_mutex);
1419 		if (((queue->queue_type == AMDGPU_HW_IP_GFX) ||
1420 		     (queue->queue_type == AMDGPU_HW_IP_COMPUTE)) &&
1421 		    (queue->xcp_id == idx)) {
1422 			r = amdgpu_userq_preempt_helper(queue);
1423 			if (r)
1424 				ret = r;
1425 		}
1426 		mutex_unlock(&uqm->userq_mutex);
1427 	}
1428 
1429 	return ret;
1430 }
1431 
1432 int amdgpu_userq_start_sched_for_enforce_isolation(struct amdgpu_device *adev,
1433 						   u32 idx)
1434 {
1435 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1436 	struct amdgpu_usermode_queue *queue;
1437 	struct amdgpu_userq_mgr *uqm;
1438 	unsigned long queue_id;
1439 	int ret = 0, r;
1440 
1441 	/* only need to stop gfx/compute */
1442 	if (!(ip_mask & ((1 << AMDGPU_HW_IP_GFX) | (1 << AMDGPU_HW_IP_COMPUTE))))
1443 		return 0;
1444 
1445 	if (!adev->userq_halt_for_enforce_isolation)
1446 		dev_warn(adev->dev, "userq scheduling already started!\n");
1447 
1448 	adev->userq_halt_for_enforce_isolation = false;
1449 
1450 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1451 		uqm = queue->userq_mgr;
1452 		mutex_lock(&uqm->userq_mutex);
1453 		if (((queue->queue_type == AMDGPU_HW_IP_GFX) ||
1454 		     (queue->queue_type == AMDGPU_HW_IP_COMPUTE)) &&
1455 		    (queue->xcp_id == idx)) {
1456 			r = amdgpu_userq_restore_helper(queue);
1457 			if (r)
1458 				ret = r;
1459 		}
1460 		mutex_unlock(&uqm->userq_mutex);
1461 	}
1462 
1463 	return ret;
1464 }
1465 
1466 void amdgpu_userq_gem_va_unmap_validate(struct amdgpu_device *adev,
1467 					struct amdgpu_bo_va_mapping *mapping)
1468 {
1469 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1470 	struct amdgpu_bo_va *bo_va = mapping->bo_va;
1471 	struct dma_resv *resv = bo_va->base.bo->tbo.base.resv;
1472 
1473 	if (!ip_mask)
1474 		return;
1475 
1476 	/**
1477 	 * The userq VA mapping reservation should include the eviction fence.
1478 	 * Note: The eviction fence may be attached to different BOs and this
1479 	 * unmap is only for one kind of userq VAs, so at this point suppose
1480 	 * the eviction fence is always unsignaled.
1481 	 */
1482 	dma_resv_wait_timeout(resv, DMA_RESV_USAGE_BOOKKEEP,
1483 			      false, MAX_SCHEDULE_TIMEOUT);
1484 }
1485 
1486 void amdgpu_userq_pre_reset(struct amdgpu_device *adev)
1487 {
1488 	const struct amdgpu_userq_funcs *userq_funcs;
1489 	struct amdgpu_usermode_queue *queue;
1490 	unsigned long queue_id;
1491 
1492 	/* TODO: We probably need a new lock for the queue state */
1493 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1494 		if (queue->state == AMDGPU_USERQ_STATE_MAPPED) {
1495 			trace_amdgpu_userq_state_start(queue);
1496 			userq_funcs = adev->userq_funcs[queue->queue_type];
1497 			userq_funcs->unmap(queue);
1498 			/* just mark all queues as hung at this point.
1499 			 * if unmap succeeds, we could map again
1500 			 * in amdgpu_userq_post_reset() if vram is not lost
1501 			 */
1502 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_HUNG);
1503 			queue->state = AMDGPU_USERQ_STATE_HUNG;
1504 		}
1505 		/* Force-complete any pending fence regardless of queue state so
1506 		 * that eviction/suspend and queue teardown waiters don't block
1507 		 * forever on a fence that will never signal after the reset.
1508 		 */
1509 		amdgpu_userq_fence_driver_force_completion(queue);
1510 	}
1511 }
1512 
1513 int amdgpu_userq_post_reset(struct amdgpu_device *adev, bool vram_lost)
1514 {
1515 	/* if any queue state is AMDGPU_USERQ_STATE_UNMAPPED
1516 	 * at this point, we should be able to map it again
1517 	 * and continue if vram is not lost.
1518 	 */
1519 	struct amdgpu_usermode_queue *queue;
1520 	const struct amdgpu_userq_funcs *userq_funcs;
1521 	unsigned long queue_id;
1522 	int r = 0;
1523 
1524 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1525 		if (queue->state == AMDGPU_USERQ_STATE_HUNG && !vram_lost) {
1526 			trace_amdgpu_userq_state_start(queue);
1527 
1528 			userq_funcs = adev->userq_funcs[queue->queue_type];
1529 			/* Re-map queue */
1530 			r = userq_funcs->map(queue);
1531 			if (r) {
1532 				dev_err(adev->dev, "Failed to remap queue %ld\n", queue_id);
1533 				continue;
1534 			}
1535 			trace_amdgpu_userq_state_changed(queue, AMDGPU_USERQ_STATE_MAPPED);
1536 			queue->state = AMDGPU_USERQ_STATE_MAPPED;
1537 		}
1538 	}
1539 
1540 	return r;
1541 }
1542