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