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