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