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