xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_userq.c (revision 422b5233b607476ac7176bfa2a101b9a103d7653)
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 	uint64_t index;
712 	int priority;
713 	u32 qid;
714 	int r;
715 
716 	priority =
717 		(args->in.flags & AMDGPU_USERQ_CREATE_FLAGS_QUEUE_PRIORITY_MASK)
718 		>> AMDGPU_USERQ_CREATE_FLAGS_QUEUE_PRIORITY_SHIFT;
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 		r = -EINVAL;
732 		goto err_pm_runtime;
733 	}
734 
735 	queue = kzalloc_obj(struct amdgpu_usermode_queue);
736 	if (!queue) {
737 		r = -ENOMEM;
738 		goto err_pm_runtime;
739 	}
740 
741 	kref_init(&queue->refcount);
742 	INIT_LIST_HEAD(&queue->userq_va_list);
743 	queue->doorbell_handle = args->in.doorbell_handle;
744 	queue->queue_type = args->in.ip_type;
745 	queue->vm = &fpriv->vm;
746 	queue->priority = priority;
747 	queue->userq_mgr = uq_mgr;
748 	INIT_DELAYED_WORK(&queue->hang_detect_work,
749 			  amdgpu_userq_hang_detect_work);
750 
751 	mutex_init(&queue->fence_drv_lock);
752 	xa_init_flags(&queue->fence_drv_xa, XA_FLAGS_ALLOC);
753 	r = amdgpu_userq_fence_driver_alloc(adev, &queue->fence_drv);
754 	if (r)
755 		goto free_queue;
756 
757 	/* Make sure the queue can actually run with those virtual addresses. */
758 	r = amdgpu_bo_reserve(fpriv->vm.root.bo, false);
759 	if (r)
760 		goto free_fence_drv;
761 
762 	if (amdgpu_userq_input_va_validate(adev, queue, args->in.queue_va,
763 					   args->in.queue_size) ||
764 	    amdgpu_userq_input_va_validate(adev, queue, args->in.rptr_va,
765 					   AMDGPU_GPU_PAGE_SIZE) ||
766 	    amdgpu_userq_input_va_validate(adev, queue, args->in.wptr_va,
767 					   AMDGPU_GPU_PAGE_SIZE)) {
768 		r = -EINVAL;
769 		amdgpu_bo_unreserve(fpriv->vm.root.bo);
770 		goto clean_mapping;
771 	}
772 	amdgpu_bo_unreserve(fpriv->vm.root.bo);
773 
774 	/* Convert relative doorbell offset into absolute doorbell index */
775 	db_info.queue_type = queue->queue_type;
776 	db_info.doorbell_handle = queue->doorbell_handle;
777 	db_info.db_obj = &queue->db_obj;
778 	db_info.doorbell_offset = args->in.doorbell_offset;
779 	index = amdgpu_userq_get_doorbell_index(uq_mgr, &db_info, filp);
780 	if (index == (uint64_t)-EINVAL) {
781 		drm_file_err(uq_mgr->file, "Failed to get doorbell for queue\n");
782 		r = -EINVAL;
783 		goto clean_mapping;
784 	}
785 
786 	queue->doorbell_index = index;
787 	r = uq_funcs->mqd_create(queue, &args->in);
788 	if (r) {
789 		drm_file_err(uq_mgr->file, "Failed to create Queue\n");
790 		goto clean_mapping;
791 	}
792 
793 	/* Update VM owner at userq submit-time for page-fault attribution. */
794 	amdgpu_vm_set_task_info(&fpriv->vm);
795 
796 	r = xa_err(xa_store_irq(&adev->userq_doorbell_xa, index, queue,
797 				GFP_KERNEL));
798 	if (r)
799 		goto clean_mqd;
800 
801 	amdgpu_userq_ensure_ev_fence(&fpriv->userq_mgr, &fpriv->evf_mgr);
802 
803 	/* don't map the queue if scheduling is halted */
804 	if (!adev->userq_halt_for_enforce_isolation ||
805 	    ((queue->queue_type != AMDGPU_HW_IP_GFX) &&
806 	     (queue->queue_type != AMDGPU_HW_IP_COMPUTE))) {
807 		r = amdgpu_userq_map_helper(queue);
808 		if (r) {
809 			drm_file_err(uq_mgr->file, "Failed to map Queue\n");
810 			mutex_unlock(&uq_mgr->userq_mutex);
811 			goto clean_doorbell;
812 		}
813 	}
814 
815 	atomic_inc(&uq_mgr->userq_count[queue->queue_type]);
816 	mutex_unlock(&uq_mgr->userq_mutex);
817 
818 	r = xa_alloc(&uq_mgr->userq_xa, &qid, queue,
819 		     XA_LIMIT(1, AMDGPU_MAX_USERQ_COUNT),
820 		     GFP_KERNEL);
821 	if (r) {
822 		/*
823 		 * This drops the last reference which should take care of
824 		 * all cleanup.
825 		 */
826 		amdgpu_userq_put(queue);
827 		return r;
828 	}
829 
830 	amdgpu_debugfs_userq_init(filp, queue, qid);
831 	args->out.queue_id = qid;
832 	return 0;
833 
834 clean_doorbell:
835 	xa_erase_irq(&adev->userq_doorbell_xa, index);
836 clean_mqd:
837 	uq_funcs->mqd_destroy(queue);
838 clean_mapping:
839 	amdgpu_bo_reserve(fpriv->vm.root.bo, true);
840 	amdgpu_userq_buffer_vas_list_cleanup(adev, queue);
841 	amdgpu_bo_unreserve(fpriv->vm.root.bo);
842 	mutex_destroy(&queue->fence_drv_lock);
843 free_fence_drv:
844 	amdgpu_userq_fence_driver_free(queue);
845 free_queue:
846 	kfree(queue);
847 err_pm_runtime:
848 	pm_runtime_put_autosuspend(adev_to_drm(adev)->dev);
849 	return r;
850 }
851 
852 static int amdgpu_userq_input_args_validate(struct drm_device *dev,
853 					union drm_amdgpu_userq *args,
854 					struct drm_file *filp)
855 {
856 	struct amdgpu_device *adev = drm_to_adev(dev);
857 
858 	switch (args->in.op) {
859 	case AMDGPU_USERQ_OP_CREATE:
860 		if (args->in.flags & ~(AMDGPU_USERQ_CREATE_FLAGS_QUEUE_PRIORITY_MASK |
861 				       AMDGPU_USERQ_CREATE_FLAGS_QUEUE_SECURE))
862 			return -EINVAL;
863 		/* Usermode queues are only supported for GFX IP as of now */
864 		if (args->in.ip_type != AMDGPU_HW_IP_GFX &&
865 		    args->in.ip_type != AMDGPU_HW_IP_DMA &&
866 		    args->in.ip_type != AMDGPU_HW_IP_COMPUTE) {
867 			drm_file_err(filp, "Usermode queue doesn't support IP type %u\n",
868 				     args->in.ip_type);
869 			return -EINVAL;
870 		}
871 
872 		if ((args->in.flags & AMDGPU_USERQ_CREATE_FLAGS_QUEUE_SECURE) &&
873 		    (args->in.ip_type != AMDGPU_HW_IP_GFX) &&
874 		    (args->in.ip_type != AMDGPU_HW_IP_COMPUTE) &&
875 		    !amdgpu_is_tmz(adev)) {
876 			drm_file_err(filp, "Secure only supported on GFX/Compute queues\n");
877 			return -EINVAL;
878 		}
879 
880 		if (args->in.queue_va == AMDGPU_BO_INVALID_OFFSET ||
881 		    args->in.queue_va == 0 ||
882 		    args->in.queue_size == 0) {
883 			drm_file_err(filp, "invalidate userq queue va or size\n");
884 			return -EINVAL;
885 		}
886 
887 		if (!is_power_of_2(args->in.queue_size)) {
888 			drm_file_err(filp, "Queue size must be a power of 2\n");
889 			return -EINVAL;
890 		}
891 
892 		if (args->in.queue_size < AMDGPU_GPU_PAGE_SIZE) {
893 			drm_file_err(filp, "Queue size smaller than AMDGPU_GPU_PAGE_SIZE\n");
894 			return -EINVAL;
895 		}
896 
897 		if (!args->in.wptr_va || !args->in.rptr_va) {
898 			drm_file_err(filp, "invalidate userq queue rptr or wptr\n");
899 			return -EINVAL;
900 		}
901 		break;
902 	case AMDGPU_USERQ_OP_FREE:
903 		if (args->in.ip_type ||
904 		    args->in.doorbell_handle ||
905 		    args->in.doorbell_offset ||
906 		    args->in.flags ||
907 		    args->in.queue_va ||
908 		    args->in.queue_size ||
909 		    args->in.rptr_va ||
910 		    args->in.wptr_va ||
911 		    args->in.mqd ||
912 		    args->in.mqd_size)
913 			return -EINVAL;
914 		break;
915 	default:
916 		return -EINVAL;
917 	}
918 
919 	return 0;
920 }
921 
922 bool amdgpu_userq_enabled(struct drm_device *dev)
923 {
924 	struct amdgpu_device *adev = drm_to_adev(dev);
925 	int i;
926 
927 	for (i = 0; i < AMDGPU_HW_IP_NUM; i++) {
928 		if (adev->userq_funcs[i])
929 			return true;
930 	}
931 
932 	return false;
933 }
934 
935 int amdgpu_userq_ioctl(struct drm_device *dev, void *data,
936 		       struct drm_file *filp)
937 {
938 	union drm_amdgpu_userq *args = data;
939 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
940 	struct amdgpu_usermode_queue *queue;
941 	int r = 0;
942 
943 	if (!amdgpu_userq_enabled(dev))
944 		return -ENOTSUPP;
945 
946 	if (amdgpu_userq_input_args_validate(dev, args, filp) < 0)
947 		return -EINVAL;
948 
949 	switch (args->in.op) {
950 	case AMDGPU_USERQ_OP_CREATE:
951 		r = amdgpu_userq_create(filp, args);
952 		if (r)
953 			drm_file_err(filp, "Failed to create usermode queue\n");
954 		break;
955 
956 	case AMDGPU_USERQ_OP_FREE: {
957 		xa_lock(&fpriv->userq_mgr.userq_xa);
958 		queue = __xa_erase(&fpriv->userq_mgr.userq_xa, args->in.queue_id);
959 		xa_unlock(&fpriv->userq_mgr.userq_xa);
960 		if (!queue)
961 			return -ENOENT;
962 
963 		amdgpu_userq_put(queue);
964 		break;
965 	}
966 
967 	default:
968 		drm_dbg_driver(dev, "Invalid user queue op specified: %d\n", args->in.op);
969 		return -EINVAL;
970 	}
971 
972 	return r;
973 }
974 
975 static int
976 amdgpu_userq_restore_all(struct amdgpu_userq_mgr *uq_mgr)
977 {
978 	struct amdgpu_fpriv *fpriv = uq_mgr_to_fpriv(uq_mgr);
979 	struct amdgpu_vm *vm = &fpriv->vm;
980 	struct amdgpu_usermode_queue *queue;
981 	unsigned long queue_id;
982 	int ret = 0, r;
983 
984 
985 	if (amdgpu_bo_reserve(vm->root.bo, false))
986 		return false;
987 
988 	mutex_lock(&uq_mgr->userq_mutex);
989 	/* Resume all the queues for this process */
990 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
991 
992 		if (!amdgpu_userq_buffer_vas_mapped(queue)) {
993 			drm_file_err(uq_mgr->file,
994 				     "trying restore queue without va mapping\n");
995 			queue->state = AMDGPU_USERQ_STATE_INVALID_VA;
996 			continue;
997 		}
998 
999 		r = amdgpu_userq_restore_helper(queue);
1000 		if (r)
1001 			ret = r;
1002 
1003 	}
1004 	mutex_unlock(&uq_mgr->userq_mutex);
1005 	amdgpu_bo_unreserve(vm->root.bo);
1006 
1007 	if (ret)
1008 		drm_file_err(uq_mgr->file,
1009 			     "Failed to map all the queues, restore failed ret=%d\n", ret);
1010 	return ret;
1011 }
1012 
1013 static int amdgpu_userq_validate_vm(void *param, struct amdgpu_bo *bo)
1014 {
1015 	struct ttm_operation_ctx ctx = { false, false };
1016 
1017 	amdgpu_bo_placement_from_domain(bo, bo->allowed_domains);
1018 	return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1019 }
1020 
1021 /* Handle all BOs on the invalidated list, validate them and update the PTs */
1022 static int
1023 amdgpu_userq_bo_validate(struct amdgpu_device *adev, struct drm_exec *exec,
1024 			 struct amdgpu_vm *vm)
1025 {
1026 	struct ttm_operation_ctx ctx = { false, false };
1027 	struct amdgpu_bo_va *bo_va;
1028 	struct amdgpu_bo *bo;
1029 	int ret;
1030 
1031 	spin_lock(&vm->status_lock);
1032 	while (!list_empty(&vm->invalidated)) {
1033 		bo_va = list_first_entry(&vm->invalidated,
1034 					 struct amdgpu_bo_va,
1035 					 base.vm_status);
1036 		spin_unlock(&vm->status_lock);
1037 
1038 		bo = bo_va->base.bo;
1039 		ret = drm_exec_prepare_obj(exec, &bo->tbo.base, 2);
1040 		if (unlikely(ret))
1041 			return ret;
1042 
1043 		amdgpu_bo_placement_from_domain(bo, bo->allowed_domains);
1044 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1045 		if (ret)
1046 			return ret;
1047 
1048 		/* This moves the bo_va to the done list */
1049 		ret = amdgpu_vm_bo_update(adev, bo_va, false);
1050 		if (ret)
1051 			return ret;
1052 
1053 		spin_lock(&vm->status_lock);
1054 	}
1055 	spin_unlock(&vm->status_lock);
1056 
1057 	return 0;
1058 }
1059 
1060 /* Make sure the whole VM is ready to be used */
1061 static int
1062 amdgpu_userq_vm_validate(struct amdgpu_userq_mgr *uq_mgr)
1063 {
1064 	struct amdgpu_fpriv *fpriv = uq_mgr_to_fpriv(uq_mgr);
1065 	bool invalidated = false, new_addition = false;
1066 	struct ttm_operation_ctx ctx = { true, false };
1067 	struct amdgpu_device *adev = uq_mgr->adev;
1068 	struct amdgpu_hmm_range *range;
1069 	struct amdgpu_vm *vm = &fpriv->vm;
1070 	unsigned long key, tmp_key;
1071 	struct amdgpu_bo_va *bo_va;
1072 	struct amdgpu_bo *bo;
1073 	struct drm_exec exec;
1074 	struct xarray xa;
1075 	int ret;
1076 
1077 	xa_init(&xa);
1078 
1079 retry_lock:
1080 	drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0);
1081 	drm_exec_until_all_locked(&exec) {
1082 		ret = amdgpu_vm_lock_pd(vm, &exec, 1);
1083 		drm_exec_retry_on_contention(&exec);
1084 		if (unlikely(ret))
1085 			goto unlock_all;
1086 
1087 		ret = amdgpu_vm_lock_done_list(vm, &exec, 1);
1088 		drm_exec_retry_on_contention(&exec);
1089 		if (unlikely(ret))
1090 			goto unlock_all;
1091 
1092 		/* This validates PDs, PTs and per VM BOs */
1093 		ret = amdgpu_vm_validate(adev, vm, NULL,
1094 					 amdgpu_userq_validate_vm,
1095 					 NULL);
1096 		if (unlikely(ret))
1097 			goto unlock_all;
1098 
1099 		/* This locks and validates the remaining evicted BOs */
1100 		ret = amdgpu_userq_bo_validate(adev, &exec, vm);
1101 		drm_exec_retry_on_contention(&exec);
1102 		if (unlikely(ret))
1103 			goto unlock_all;
1104 	}
1105 
1106 	if (invalidated) {
1107 		xa_for_each(&xa, tmp_key, range) {
1108 			bo = range->bo;
1109 			amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
1110 			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1111 			if (ret)
1112 				goto unlock_all;
1113 
1114 			amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, range);
1115 
1116 			amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT);
1117 			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1118 			if (ret)
1119 				goto unlock_all;
1120 		}
1121 		invalidated = false;
1122 	}
1123 
1124 	ret = amdgpu_vm_handle_moved(adev, vm, NULL);
1125 	if (ret)
1126 		goto unlock_all;
1127 
1128 	key = 0;
1129 	/* Validate User Ptr BOs */
1130 	list_for_each_entry(bo_va, &vm->done, base.vm_status) {
1131 		bo = bo_va->base.bo;
1132 		if (!bo)
1133 			continue;
1134 
1135 		if (!amdgpu_ttm_tt_is_userptr(bo->tbo.ttm))
1136 			continue;
1137 
1138 		range = xa_load(&xa, key);
1139 		if (range && range->bo != bo) {
1140 			xa_erase(&xa, key);
1141 			amdgpu_hmm_range_free(range);
1142 			range = NULL;
1143 		}
1144 
1145 		if (!range) {
1146 			range = amdgpu_hmm_range_alloc(bo);
1147 			if (!range) {
1148 				ret = -ENOMEM;
1149 				goto unlock_all;
1150 			}
1151 
1152 			xa_store(&xa, key, range, GFP_KERNEL);
1153 			new_addition = true;
1154 		}
1155 		key++;
1156 	}
1157 
1158 	if (new_addition) {
1159 		drm_exec_fini(&exec);
1160 		xa_for_each(&xa, tmp_key, range) {
1161 			if (!range)
1162 				continue;
1163 			bo = range->bo;
1164 			ret = amdgpu_ttm_tt_get_user_pages(bo, range);
1165 			if (ret)
1166 				goto free_ranges;
1167 		}
1168 
1169 		invalidated = true;
1170 		new_addition = false;
1171 		goto retry_lock;
1172 	}
1173 
1174 	ret = amdgpu_vm_update_pdes(adev, vm, false);
1175 	if (ret)
1176 		goto unlock_all;
1177 
1178 	/*
1179 	 * We need to wait for all VM updates to finish before restarting the
1180 	 * queues. Using the done list like that is now ok since everything is
1181 	 * locked in place.
1182 	 */
1183 	list_for_each_entry(bo_va, &vm->done, base.vm_status)
1184 		dma_fence_wait(bo_va->last_pt_update, false);
1185 	dma_fence_wait(vm->last_update, false);
1186 
1187 	ret = amdgpu_evf_mgr_rearm(&fpriv->evf_mgr, &exec);
1188 	if (ret)
1189 		drm_file_err(uq_mgr->file, "Failed to replace eviction fence\n");
1190 
1191 unlock_all:
1192 	drm_exec_fini(&exec);
1193 free_ranges:
1194 	xa_for_each(&xa, tmp_key, range) {
1195 		if (!range)
1196 			continue;
1197 		bo = range->bo;
1198 		amdgpu_hmm_range_free(range);
1199 	}
1200 	xa_destroy(&xa);
1201 	return ret;
1202 }
1203 
1204 static void amdgpu_userq_restore_worker(struct work_struct *work)
1205 {
1206 	struct amdgpu_userq_mgr *uq_mgr = work_to_uq_mgr(work, resume_work.work);
1207 	struct amdgpu_fpriv *fpriv = uq_mgr_to_fpriv(uq_mgr);
1208 	struct dma_fence *ev_fence;
1209 	int ret;
1210 
1211 	ev_fence = amdgpu_evf_mgr_get_fence(&fpriv->evf_mgr);
1212 	if (!dma_fence_is_signaled(ev_fence))
1213 		goto put_fence;
1214 
1215 	ret = amdgpu_userq_vm_validate(uq_mgr);
1216 	if (ret) {
1217 		drm_file_err(uq_mgr->file, "Failed to validate BOs to restore ret=%d\n", ret);
1218 		goto put_fence;
1219 	}
1220 
1221 	amdgpu_userq_restore_all(uq_mgr);
1222 
1223 put_fence:
1224 	dma_fence_put(ev_fence);
1225 }
1226 
1227 static int
1228 amdgpu_userq_evict_all(struct amdgpu_userq_mgr *uq_mgr)
1229 {
1230 	struct amdgpu_usermode_queue *queue;
1231 	unsigned long queue_id;
1232 	int ret = 0, r;
1233 
1234 	/* Try to unmap all the queues in this process ctx */
1235 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
1236 		r = amdgpu_userq_preempt_helper(queue);
1237 		if (r)
1238 			ret = r;
1239 	}
1240 
1241 	if (ret) {
1242 		drm_file_err(uq_mgr->file,
1243 			     "Couldn't unmap all the queues, eviction failed ret=%d\n", ret);
1244 		amdgpu_reset_domain_schedule(uq_mgr->adev->reset_domain,
1245 					     &uq_mgr->reset_work);
1246 		flush_work(&uq_mgr->reset_work);
1247 	}
1248 	return ret;
1249 }
1250 
1251 static void
1252 amdgpu_userq_wait_for_signal(struct amdgpu_userq_mgr *uq_mgr)
1253 {
1254 	struct amdgpu_usermode_queue *queue;
1255 	unsigned long queue_id;
1256 
1257 	xa_for_each(&uq_mgr->userq_xa, queue_id, queue) {
1258 		struct dma_fence *f = queue->last_fence;
1259 
1260 		if (!f)
1261 			continue;
1262 
1263 		dma_fence_wait(f, false);
1264 	}
1265 }
1266 
1267 void
1268 amdgpu_userq_evict(struct amdgpu_userq_mgr *uq_mgr)
1269 {
1270 	/* Wait for any pending userqueue fence work to finish */
1271 	amdgpu_userq_wait_for_signal(uq_mgr);
1272 	amdgpu_userq_evict_all(uq_mgr);
1273 }
1274 
1275 int amdgpu_userq_mgr_init(struct amdgpu_userq_mgr *userq_mgr, struct drm_file *file_priv,
1276 			  struct amdgpu_device *adev)
1277 {
1278 	mutex_init(&userq_mgr->userq_mutex);
1279 	xa_init_flags(&userq_mgr->userq_xa, XA_FLAGS_ALLOC);
1280 	userq_mgr->adev = adev;
1281 	userq_mgr->file = file_priv;
1282 
1283 	INIT_DELAYED_WORK(&userq_mgr->resume_work, amdgpu_userq_restore_worker);
1284 	INIT_WORK(&userq_mgr->reset_work, amdgpu_userq_mgr_reset_work);
1285 	return 0;
1286 }
1287 
1288 void amdgpu_userq_mgr_cancel_reset_work(struct amdgpu_device *adev)
1289 {
1290 	struct xarray *xa = &adev->userq_doorbell_xa;
1291 	struct amdgpu_usermode_queue *queue;
1292 	unsigned long flags, queue_id;
1293 
1294 	xa_lock_irqsave(xa, flags);
1295 	xa_for_each(xa, queue_id, queue) {
1296 		cancel_delayed_work(&queue->hang_detect_work);
1297 		cancel_work(&queue->userq_mgr->reset_work);
1298 	}
1299 	xa_unlock_irqrestore(xa, flags);
1300 }
1301 
1302 void amdgpu_userq_mgr_cancel_resume(struct amdgpu_userq_mgr *userq_mgr)
1303 {
1304 	cancel_delayed_work_sync(&userq_mgr->resume_work);
1305 }
1306 
1307 void amdgpu_userq_mgr_fini(struct amdgpu_userq_mgr *userq_mgr)
1308 {
1309 	struct amdgpu_usermode_queue *queue;
1310 	unsigned long queue_id = 0;
1311 
1312 	for (;;) {
1313 		xa_lock(&userq_mgr->userq_xa);
1314 		queue = xa_find(&userq_mgr->userq_xa, &queue_id, ULONG_MAX,
1315 				XA_PRESENT);
1316 		if (queue)
1317 			__xa_erase(&userq_mgr->userq_xa, queue_id);
1318 		xa_unlock(&userq_mgr->userq_xa);
1319 
1320 		if (!queue)
1321 			break;
1322 
1323 		amdgpu_userq_put(queue);
1324 	}
1325 
1326 	xa_destroy(&userq_mgr->userq_xa);
1327 
1328 	/*
1329 	 * Drain any in-flight reset_work. By this point all queues are freed
1330 	 * and userq_count is 0, so if reset_work starts now it exits early.
1331 	 * We still need to wait in case it was already executing gpu_recover.
1332 	 */
1333 	cancel_work_sync(&userq_mgr->reset_work);
1334 
1335 	mutex_destroy(&userq_mgr->userq_mutex);
1336 }
1337 
1338 int amdgpu_userq_suspend(struct amdgpu_device *adev)
1339 {
1340 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1341 	struct amdgpu_usermode_queue *queue;
1342 	struct amdgpu_userq_mgr *uqm;
1343 	unsigned long queue_id;
1344 	int r;
1345 
1346 	if (!ip_mask)
1347 		return 0;
1348 
1349 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1350 		uqm = queue->userq_mgr;
1351 		cancel_delayed_work_sync(&uqm->resume_work);
1352 		guard(mutex)(&uqm->userq_mutex);
1353 		if (adev->in_s0ix)
1354 			r = amdgpu_userq_preempt_helper(queue);
1355 		else
1356 			r = amdgpu_userq_unmap_helper(queue);
1357 		if (r)
1358 			return r;
1359 	}
1360 	return 0;
1361 }
1362 
1363 int amdgpu_userq_resume(struct amdgpu_device *adev)
1364 {
1365 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1366 	struct amdgpu_usermode_queue *queue;
1367 	struct amdgpu_userq_mgr *uqm;
1368 	unsigned long queue_id;
1369 	int r;
1370 
1371 	if (!ip_mask)
1372 		return 0;
1373 
1374 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1375 		uqm = queue->userq_mgr;
1376 		guard(mutex)(&uqm->userq_mutex);
1377 		if (adev->in_s0ix)
1378 			r = amdgpu_userq_restore_helper(queue);
1379 		else
1380 			r = amdgpu_userq_map_helper(queue);
1381 		if (r)
1382 			return r;
1383 	}
1384 
1385 	return 0;
1386 }
1387 
1388 int amdgpu_userq_stop_sched_for_enforce_isolation(struct amdgpu_device *adev,
1389 						  u32 idx)
1390 {
1391 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1392 	struct amdgpu_usermode_queue *queue;
1393 	struct amdgpu_userq_mgr *uqm;
1394 	unsigned long queue_id;
1395 	int ret = 0, r;
1396 
1397 	/* only need to stop gfx/compute */
1398 	if (!(ip_mask & ((1 << AMDGPU_HW_IP_GFX) | (1 << AMDGPU_HW_IP_COMPUTE))))
1399 		return 0;
1400 
1401 	if (adev->userq_halt_for_enforce_isolation)
1402 		dev_warn(adev->dev, "userq scheduling already stopped!\n");
1403 	adev->userq_halt_for_enforce_isolation = true;
1404 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1405 		uqm = queue->userq_mgr;
1406 		cancel_delayed_work_sync(&uqm->resume_work);
1407 		mutex_lock(&uqm->userq_mutex);
1408 		if (((queue->queue_type == AMDGPU_HW_IP_GFX) ||
1409 		     (queue->queue_type == AMDGPU_HW_IP_COMPUTE)) &&
1410 		    (queue->xcp_id == idx)) {
1411 			r = amdgpu_userq_preempt_helper(queue);
1412 			if (r)
1413 				ret = r;
1414 		}
1415 		mutex_unlock(&uqm->userq_mutex);
1416 	}
1417 
1418 	return ret;
1419 }
1420 
1421 int amdgpu_userq_start_sched_for_enforce_isolation(struct amdgpu_device *adev,
1422 						   u32 idx)
1423 {
1424 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1425 	struct amdgpu_usermode_queue *queue;
1426 	struct amdgpu_userq_mgr *uqm;
1427 	unsigned long queue_id;
1428 	int ret = 0, r;
1429 
1430 	/* only need to stop gfx/compute */
1431 	if (!(ip_mask & ((1 << AMDGPU_HW_IP_GFX) | (1 << AMDGPU_HW_IP_COMPUTE))))
1432 		return 0;
1433 
1434 	if (!adev->userq_halt_for_enforce_isolation)
1435 		dev_warn(adev->dev, "userq scheduling already started!\n");
1436 
1437 	adev->userq_halt_for_enforce_isolation = false;
1438 
1439 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1440 		uqm = queue->userq_mgr;
1441 		mutex_lock(&uqm->userq_mutex);
1442 		if (((queue->queue_type == AMDGPU_HW_IP_GFX) ||
1443 		     (queue->queue_type == AMDGPU_HW_IP_COMPUTE)) &&
1444 		    (queue->xcp_id == idx)) {
1445 			r = amdgpu_userq_restore_helper(queue);
1446 			if (r)
1447 				ret = r;
1448 		}
1449 		mutex_unlock(&uqm->userq_mutex);
1450 	}
1451 
1452 	return ret;
1453 }
1454 
1455 void amdgpu_userq_gem_va_unmap_validate(struct amdgpu_device *adev,
1456 					struct amdgpu_bo_va_mapping *mapping,
1457 					uint64_t saddr)
1458 {
1459 	u32 ip_mask = amdgpu_userq_get_supported_ip_mask(adev);
1460 	struct amdgpu_bo_va *bo_va = mapping->bo_va;
1461 	struct dma_resv *resv = bo_va->base.bo->tbo.base.resv;
1462 
1463 	if (!ip_mask)
1464 		return;
1465 
1466 	dev_warn_once(adev->dev, "now unmapping a vital queue va:%llx\n", saddr);
1467 	/**
1468 	 * The userq VA mapping reservation should include the eviction fence,
1469 	 * if the eviction fence can't signal successfully during unmapping,
1470 	 * then driver will warn to flag this improper unmap of the userq VA.
1471 	 * Note: The eviction fence may be attached to different BOs, and this
1472 	 * unmap is only for one kind of userq VAs, so at this point suppose
1473 	 * the eviction fence is always unsignaled.
1474 	 */
1475 	dma_resv_wait_timeout(resv, DMA_RESV_USAGE_BOOKKEEP,
1476 			      false, MAX_SCHEDULE_TIMEOUT);
1477 }
1478 
1479 void amdgpu_userq_pre_reset(struct amdgpu_device *adev)
1480 {
1481 	const struct amdgpu_userq_funcs *userq_funcs;
1482 	struct amdgpu_usermode_queue *queue;
1483 	unsigned long queue_id;
1484 
1485 	/* TODO: We probably need a new lock for the queue state */
1486 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1487 		if (queue->state != AMDGPU_USERQ_STATE_MAPPED)
1488 			continue;
1489 
1490 		userq_funcs = adev->userq_funcs[queue->queue_type];
1491 		userq_funcs->unmap(queue);
1492 		/* just mark all queues as hung at this point.
1493 		 * if unmap succeeds, we could map again
1494 		 * in amdgpu_userq_post_reset() if vram is not lost
1495 		 */
1496 		queue->state = AMDGPU_USERQ_STATE_HUNG;
1497 		amdgpu_userq_fence_driver_force_completion(queue);
1498 	}
1499 }
1500 
1501 int amdgpu_userq_post_reset(struct amdgpu_device *adev, bool vram_lost)
1502 {
1503 	/* if any queue state is AMDGPU_USERQ_STATE_UNMAPPED
1504 	 * at this point, we should be able to map it again
1505 	 * and continue if vram is not lost.
1506 	 */
1507 	struct amdgpu_usermode_queue *queue;
1508 	const struct amdgpu_userq_funcs *userq_funcs;
1509 	unsigned long queue_id;
1510 	int r = 0;
1511 
1512 	xa_for_each(&adev->userq_doorbell_xa, queue_id, queue) {
1513 		if (queue->state == AMDGPU_USERQ_STATE_HUNG && !vram_lost) {
1514 			userq_funcs = adev->userq_funcs[queue->queue_type];
1515 			/* Re-map queue */
1516 			r = userq_funcs->map(queue);
1517 			if (r) {
1518 				dev_err(adev->dev, "Failed to remap queue %ld\n", queue_id);
1519 				continue;
1520 			}
1521 			queue->state = AMDGPU_USERQ_STATE_MAPPED;
1522 		}
1523 	}
1524 
1525 	return r;
1526 }
1527