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