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