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