xref: /linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c (revision d639d9fa162aadec1ae9980c4dcf6e50bd2f8290)
1 /*
2  * Copyright 2015 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * Authors: monk liu <monk.liu@amd.com>
23  */
24 
25 #include <drm/drm_auth.h>
26 #include <drm/drm_drv.h>
27 #include "amdgpu.h"
28 #include "amdgpu_sched.h"
29 #include "amdgpu_ras.h"
30 #include <linux/nospec.h>
31 
32 #define to_amdgpu_ctx_entity(e)	\
33 	container_of((e), struct amdgpu_ctx_entity, entity)
34 
35 const unsigned int amdgpu_ctx_num_entities[AMDGPU_HW_IP_NUM] = {
36 	[AMDGPU_HW_IP_GFX]	=	1,
37 	[AMDGPU_HW_IP_COMPUTE]	=	4,
38 	[AMDGPU_HW_IP_DMA]	=	2,
39 	[AMDGPU_HW_IP_UVD]	=	1,
40 	[AMDGPU_HW_IP_VCE]	=	1,
41 	[AMDGPU_HW_IP_UVD_ENC]	=	1,
42 	[AMDGPU_HW_IP_VCN_DEC]	=	1,
43 	[AMDGPU_HW_IP_VCN_ENC]	=	1,
44 	[AMDGPU_HW_IP_VCN_JPEG]	=	1,
45 	[AMDGPU_HW_IP_VPE]	=	1,
46 };
47 
48 bool amdgpu_ctx_priority_is_valid(int32_t ctx_prio)
49 {
50 	switch (ctx_prio) {
51 	case AMDGPU_CTX_PRIORITY_VERY_LOW:
52 	case AMDGPU_CTX_PRIORITY_LOW:
53 	case AMDGPU_CTX_PRIORITY_NORMAL:
54 	case AMDGPU_CTX_PRIORITY_HIGH:
55 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
56 		return true;
57 	default:
58 	case AMDGPU_CTX_PRIORITY_UNSET:
59 		/* UNSET priority is not valid and we don't carry that
60 		 * around, but set it to NORMAL in the only place this
61 		 * function is called, amdgpu_ctx_ioctl().
62 		 */
63 		return false;
64 	}
65 }
66 
67 static enum drm_sched_priority
68 amdgpu_ctx_to_drm_sched_prio(int32_t ctx_prio)
69 {
70 	switch (ctx_prio) {
71 	case AMDGPU_CTX_PRIORITY_UNSET:
72 		pr_warn_once("AMD-->DRM context priority value UNSET-->NORMAL");
73 		return DRM_SCHED_PRIORITY_NORMAL;
74 
75 	case AMDGPU_CTX_PRIORITY_VERY_LOW:
76 		return DRM_SCHED_PRIORITY_LOW;
77 
78 	case AMDGPU_CTX_PRIORITY_LOW:
79 		return DRM_SCHED_PRIORITY_LOW;
80 
81 	case AMDGPU_CTX_PRIORITY_NORMAL:
82 		return DRM_SCHED_PRIORITY_NORMAL;
83 
84 	case AMDGPU_CTX_PRIORITY_HIGH:
85 		return DRM_SCHED_PRIORITY_HIGH;
86 
87 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
88 		return DRM_SCHED_PRIORITY_HIGH;
89 
90 	/* This should not happen as we sanitized userspace provided priority
91 	 * already, WARN if this happens.
92 	 */
93 	default:
94 		WARN(1, "Invalid context priority %d\n", ctx_prio);
95 		return DRM_SCHED_PRIORITY_NORMAL;
96 	}
97 
98 }
99 
100 static int amdgpu_ctx_priority_permit(struct drm_file *filp,
101 				      int32_t priority)
102 {
103 	/* NORMAL and below are accessible by everyone */
104 	if (priority <= AMDGPU_CTX_PRIORITY_NORMAL)
105 		return 0;
106 
107 	if (capable(CAP_SYS_NICE))
108 		return 0;
109 
110 	if (drm_is_current_master(filp))
111 		return 0;
112 
113 	return -EACCES;
114 }
115 
116 static enum amdgpu_gfx_pipe_priority amdgpu_ctx_prio_to_gfx_pipe_prio(int32_t prio)
117 {
118 	switch (prio) {
119 	case AMDGPU_CTX_PRIORITY_HIGH:
120 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
121 		return AMDGPU_GFX_PIPE_PRIO_HIGH;
122 	default:
123 		return AMDGPU_GFX_PIPE_PRIO_NORMAL;
124 	}
125 }
126 
127 static enum amdgpu_ring_priority_level amdgpu_ctx_sched_prio_to_ring_prio(int32_t prio)
128 {
129 	switch (prio) {
130 	case AMDGPU_CTX_PRIORITY_HIGH:
131 		return AMDGPU_RING_PRIO_1;
132 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
133 		return AMDGPU_RING_PRIO_2;
134 	default:
135 		return AMDGPU_RING_PRIO_0;
136 	}
137 }
138 
139 static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip)
140 {
141 	struct amdgpu_device *adev = ctx->mgr->adev;
142 	unsigned int hw_prio;
143 	int32_t ctx_prio;
144 
145 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
146 			ctx->init_priority : ctx->override_priority;
147 
148 	switch (hw_ip) {
149 	case AMDGPU_HW_IP_GFX:
150 	case AMDGPU_HW_IP_COMPUTE:
151 		hw_prio = amdgpu_ctx_prio_to_gfx_pipe_prio(ctx_prio);
152 		break;
153 	case AMDGPU_HW_IP_VCE:
154 	case AMDGPU_HW_IP_VCN_ENC:
155 		hw_prio = amdgpu_ctx_sched_prio_to_ring_prio(ctx_prio);
156 		break;
157 	default:
158 		hw_prio = AMDGPU_RING_PRIO_DEFAULT;
159 		break;
160 	}
161 
162 	hw_ip = array_index_nospec(hw_ip, AMDGPU_HW_IP_NUM);
163 	if (adev->gpu_sched[hw_ip][hw_prio].num_scheds == 0)
164 		hw_prio = AMDGPU_RING_PRIO_DEFAULT;
165 
166 	return hw_prio;
167 }
168 
169 /* Calculate the time spend on the hw */
170 static ktime_t amdgpu_ctx_fence_time(struct dma_fence *fence)
171 {
172 	struct drm_sched_fence *s_fence;
173 
174 	if (!fence)
175 		return ns_to_ktime(0);
176 
177 	/* When the fence is not even scheduled it can't have spend time */
178 	s_fence = to_drm_sched_fence(fence);
179 	if (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->scheduled.flags))
180 		return ns_to_ktime(0);
181 
182 	/* When it is still running account how much already spend */
183 	if (!test_bit(DMA_FENCE_FLAG_TIMESTAMP_BIT, &s_fence->finished.flags))
184 		return ktime_sub(ktime_get(), s_fence->scheduled.timestamp);
185 
186 	return ktime_sub(s_fence->finished.timestamp,
187 			 s_fence->scheduled.timestamp);
188 }
189 
190 static ktime_t amdgpu_ctx_entity_time(struct amdgpu_ctx *ctx,
191 				      struct amdgpu_ctx_entity *centity)
192 {
193 	ktime_t res = ns_to_ktime(0);
194 	uint32_t i;
195 
196 	spin_lock(&ctx->ring_lock);
197 	for (i = 0; i < amdgpu_sched_jobs; i++) {
198 		res = ktime_add(res, amdgpu_ctx_fence_time(centity->fences[i]));
199 	}
200 	spin_unlock(&ctx->ring_lock);
201 	return res;
202 }
203 
204 static int amdgpu_ctx_init_entity(struct amdgpu_ctx *ctx, u32 hw_ip,
205 				  const u32 ring)
206 {
207 	struct drm_gpu_scheduler **scheds = NULL, *sched = NULL;
208 	struct amdgpu_device *adev = ctx->mgr->adev;
209 	struct amdgpu_ctx_entity *entity;
210 	enum drm_sched_priority drm_prio;
211 	unsigned int hw_prio, num_scheds;
212 	int32_t ctx_prio;
213 	int r;
214 
215 	entity = kzalloc_flex(*entity, fences, amdgpu_sched_jobs);
216 	if (!entity)
217 		return  -ENOMEM;
218 
219 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
220 			ctx->init_priority : ctx->override_priority;
221 	entity->hw_ip = hw_ip;
222 	entity->sequence = 1;
223 	hw_prio = amdgpu_ctx_get_hw_prio(ctx, hw_ip);
224 	drm_prio = amdgpu_ctx_to_drm_sched_prio(ctx_prio);
225 
226 	hw_ip = array_index_nospec(hw_ip, AMDGPU_HW_IP_NUM);
227 
228 	if (!(adev)->xcp_mgr) {
229 		scheds = adev->gpu_sched[hw_ip][hw_prio].sched;
230 		num_scheds = adev->gpu_sched[hw_ip][hw_prio].num_scheds;
231 	} else {
232 		struct amdgpu_fpriv *fpriv;
233 
234 		/* TODO: Stop using fpriv here, we only need the xcp_id. */
235 		fpriv = container_of(ctx->mgr, struct amdgpu_fpriv, ctx_mgr);
236 		r = amdgpu_xcp_select_scheds(adev, hw_ip, hw_prio, fpriv,
237 						&num_scheds, &scheds);
238 		if (r)
239 			goto error_free_entity;
240 	}
241 
242 	if (num_scheds == 0) {
243 		r = -EINVAL;
244 		goto error_free_entity;
245 	}
246 
247 	/* disable load balance if the hw engine retains context among dependent jobs */
248 	if (hw_ip == AMDGPU_HW_IP_VCN_ENC ||
249 	    hw_ip == AMDGPU_HW_IP_VCN_DEC ||
250 	    hw_ip == AMDGPU_HW_IP_UVD_ENC ||
251 	    hw_ip == AMDGPU_HW_IP_UVD) {
252 		sched = drm_sched_pick_best(scheds, num_scheds);
253 		scheds = &sched;
254 		num_scheds = 1;
255 	}
256 
257 	r = drm_sched_entity_init(&entity->entity, drm_prio, scheds, num_scheds,
258 				  NULL);
259 	if (r)
260 		goto error_free_entity;
261 
262 	/* It's not an error if we fail to install the new entity */
263 	if (cmpxchg(&ctx->entities[hw_ip][ring], NULL, entity))
264 		goto cleanup_entity;
265 
266 	return 0;
267 
268 cleanup_entity:
269 	drm_sched_entity_fini(&entity->entity);
270 
271 error_free_entity:
272 	kfree(entity);
273 
274 	return r;
275 }
276 
277 static ktime_t amdgpu_ctx_fini_entity(struct amdgpu_device *adev,
278 				  struct amdgpu_ctx_entity *entity)
279 {
280 	ktime_t res = ns_to_ktime(0);
281 	int i;
282 
283 	if (!entity)
284 		return res;
285 
286 	for (i = 0; i < amdgpu_sched_jobs; ++i) {
287 		res = ktime_add(res, amdgpu_ctx_fence_time(entity->fences[i]));
288 		dma_fence_put(entity->fences[i]);
289 	}
290 
291 	amdgpu_xcp_release_sched(adev, entity);
292 
293 	kfree(entity);
294 	return res;
295 }
296 
297 static int amdgpu_ctx_get_stable_pstate(struct amdgpu_ctx *ctx,
298 					u32 *stable_pstate)
299 {
300 	struct amdgpu_device *adev = ctx->mgr->adev;
301 	enum amd_dpm_forced_level current_level;
302 
303 	current_level = amdgpu_dpm_get_performance_level(adev);
304 
305 	switch (current_level) {
306 	case AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD:
307 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_STANDARD;
308 		break;
309 	case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK:
310 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_MIN_SCLK;
311 		break;
312 	case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK:
313 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_MIN_MCLK;
314 		break;
315 	case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK:
316 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_PEAK;
317 		break;
318 	default:
319 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_NONE;
320 		break;
321 	}
322 	return 0;
323 }
324 
325 static int amdgpu_ctx_init(struct amdgpu_ctx_mgr *mgr, int32_t priority,
326 			   struct drm_file *filp, struct amdgpu_ctx *ctx)
327 {
328 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
329 	u32 current_stable_pstate;
330 	int r;
331 
332 	r = amdgpu_ctx_priority_permit(filp, priority);
333 	if (r)
334 		return r;
335 
336 	memset(ctx, 0, sizeof(*ctx));
337 
338 	kref_init(&ctx->refcount);
339 	ctx->mgr = mgr;
340 	spin_lock_init(&ctx->ring_lock);
341 
342 	ctx->reset_counter = atomic_read(&mgr->adev->gpu_reset_counter);
343 	ctx->reset_counter_query = ctx->reset_counter;
344 	ctx->generation = amdgpu_vm_generation(mgr->adev, &fpriv->vm);
345 	ctx->init_priority = priority;
346 	ctx->override_priority = AMDGPU_CTX_PRIORITY_UNSET;
347 
348 	r = amdgpu_ctx_get_stable_pstate(ctx, &current_stable_pstate);
349 	if (r)
350 		return r;
351 
352 	if (mgr->adev->pm.stable_pstate_ctx)
353 		ctx->stable_pstate = mgr->adev->pm.stable_pstate_ctx->stable_pstate;
354 	else
355 		ctx->stable_pstate = current_stable_pstate;
356 
357 	return 0;
358 }
359 
360 static int amdgpu_ctx_set_stable_pstate(struct amdgpu_ctx *ctx,
361 					u32 stable_pstate)
362 {
363 	struct amdgpu_device *adev = ctx->mgr->adev;
364 	enum amd_dpm_forced_level level;
365 	u32 current_stable_pstate;
366 	int r;
367 
368 	mutex_lock(&adev->pm.stable_pstate_ctx_lock);
369 	if (adev->pm.stable_pstate_ctx && adev->pm.stable_pstate_ctx != ctx) {
370 		r = -EBUSY;
371 		goto done;
372 	}
373 
374 	r = amdgpu_ctx_get_stable_pstate(ctx, &current_stable_pstate);
375 	if (r || (stable_pstate == current_stable_pstate))
376 		goto done;
377 
378 	switch (stable_pstate) {
379 	case AMDGPU_CTX_STABLE_PSTATE_NONE:
380 		level = AMD_DPM_FORCED_LEVEL_AUTO;
381 		break;
382 	case AMDGPU_CTX_STABLE_PSTATE_STANDARD:
383 		level = AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD;
384 		break;
385 	case AMDGPU_CTX_STABLE_PSTATE_MIN_SCLK:
386 		level = AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK;
387 		break;
388 	case AMDGPU_CTX_STABLE_PSTATE_MIN_MCLK:
389 		level = AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK;
390 		break;
391 	case AMDGPU_CTX_STABLE_PSTATE_PEAK:
392 		level = AMD_DPM_FORCED_LEVEL_PROFILE_PEAK;
393 		break;
394 	default:
395 		r = -EINVAL;
396 		goto done;
397 	}
398 
399 	r = amdgpu_dpm_force_performance_level(adev, level);
400 
401 	if (level == AMD_DPM_FORCED_LEVEL_AUTO)
402 		adev->pm.stable_pstate_ctx = NULL;
403 	else
404 		adev->pm.stable_pstate_ctx = ctx;
405 done:
406 	mutex_unlock(&adev->pm.stable_pstate_ctx_lock);
407 
408 	return r;
409 }
410 
411 static void amdgpu_ctx_fini(struct kref *ref)
412 {
413 	struct amdgpu_ctx *ctx = container_of(ref, struct amdgpu_ctx, refcount);
414 	struct amdgpu_ctx_mgr *mgr = ctx->mgr;
415 	struct amdgpu_device *adev = mgr->adev;
416 	unsigned i, j, idx;
417 
418 	if (!adev)
419 		return;
420 
421 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
422 		for (j = 0; j < AMDGPU_MAX_ENTITY_NUM; ++j) {
423 			ktime_t spend;
424 
425 			spend = amdgpu_ctx_fini_entity(adev, ctx->entities[i][j]);
426 			atomic64_add(ktime_to_ns(spend), &mgr->time_spend[i]);
427 		}
428 	}
429 
430 	if (drm_dev_enter(adev_to_drm(adev), &idx)) {
431 		amdgpu_ctx_set_stable_pstate(ctx, ctx->stable_pstate);
432 		drm_dev_exit(idx);
433 	}
434 
435 	kfree(ctx);
436 }
437 
438 int amdgpu_ctx_get_entity(struct amdgpu_ctx *ctx, u32 hw_ip, u32 instance,
439 			  u32 ring, struct drm_sched_entity **entity)
440 {
441 	int r;
442 	struct drm_sched_entity *ctx_entity;
443 
444 	if (hw_ip >= AMDGPU_HW_IP_NUM) {
445 		drm_err(adev_to_drm(ctx->mgr->adev),
446 			"unknown HW IP type: %d\n", hw_ip);
447 		return -EINVAL;
448 	}
449 
450 	/* Right now all IPs have only one instance - multiple rings. */
451 	if (instance != 0) {
452 		drm_dbg(adev_to_drm(ctx->mgr->adev),
453 			"invalid ip instance: %d\n", instance);
454 		return -EINVAL;
455 	}
456 
457 	if (ring >= amdgpu_ctx_num_entities[hw_ip]) {
458 		drm_dbg(adev_to_drm(ctx->mgr->adev),
459 			"invalid ring: %d %d\n", hw_ip, ring);
460 		return -EINVAL;
461 	}
462 
463 	if (ctx->entities[hw_ip][ring] == NULL) {
464 		r = amdgpu_ctx_init_entity(ctx, hw_ip, ring);
465 		if (r)
466 			return r;
467 	}
468 
469 	ctx_entity = &ctx->entities[hw_ip][ring]->entity;
470 	r = drm_sched_entity_error(ctx_entity);
471 	if (r) {
472 		DRM_DEBUG("error entity %p\n", ctx_entity);
473 		return r;
474 	}
475 
476 	*entity = ctx_entity;
477 	return 0;
478 }
479 
480 static int amdgpu_ctx_alloc(struct amdgpu_device *adev,
481 			    struct amdgpu_fpriv *fpriv,
482 			    struct drm_file *filp,
483 			    int32_t priority,
484 			    uint32_t *id)
485 {
486 	struct amdgpu_ctx_mgr *mgr = &fpriv->ctx_mgr;
487 	struct amdgpu_ctx *ctx;
488 	int r;
489 
490 	ctx = kmalloc_obj(*ctx);
491 	if (!ctx)
492 		return -ENOMEM;
493 
494 	mutex_lock(&mgr->lock);
495 	r = idr_alloc(&mgr->ctx_handles, ctx, 1, AMDGPU_VM_MAX_NUM_CTX, GFP_KERNEL);
496 	if (r < 0) {
497 		mutex_unlock(&mgr->lock);
498 		kfree(ctx);
499 		return r;
500 	}
501 
502 	*id = (uint32_t)r;
503 	r = amdgpu_ctx_init(mgr, priority, filp, ctx);
504 	if (r) {
505 		idr_remove(&mgr->ctx_handles, *id);
506 		*id = 0;
507 		kfree(ctx);
508 	}
509 	mutex_unlock(&mgr->lock);
510 	return r;
511 }
512 
513 static void amdgpu_ctx_do_release(struct kref *ref)
514 {
515 	struct amdgpu_ctx *ctx;
516 	u32 i, j;
517 
518 	ctx = container_of(ref, struct amdgpu_ctx, refcount);
519 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
520 		for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
521 			if (!ctx->entities[i][j])
522 				continue;
523 
524 			drm_sched_entity_destroy(&ctx->entities[i][j]->entity);
525 		}
526 	}
527 
528 	amdgpu_ctx_fini(ref);
529 }
530 
531 static int amdgpu_ctx_free(struct amdgpu_fpriv *fpriv, uint32_t id)
532 {
533 	struct amdgpu_ctx_mgr *mgr = &fpriv->ctx_mgr;
534 	struct amdgpu_ctx *ctx;
535 
536 	mutex_lock(&mgr->lock);
537 	ctx = idr_remove(&mgr->ctx_handles, id);
538 	if (ctx)
539 		kref_put(&ctx->refcount, amdgpu_ctx_do_release);
540 	mutex_unlock(&mgr->lock);
541 	return ctx ? 0 : -EINVAL;
542 }
543 
544 static int amdgpu_ctx_query(struct amdgpu_device *adev,
545 			    struct amdgpu_fpriv *fpriv, uint32_t id,
546 			    union drm_amdgpu_ctx_out *out)
547 {
548 	struct amdgpu_ctx *ctx;
549 	struct amdgpu_ctx_mgr *mgr;
550 	unsigned reset_counter;
551 
552 	if (!fpriv)
553 		return -EINVAL;
554 
555 	mgr = &fpriv->ctx_mgr;
556 	mutex_lock(&mgr->lock);
557 	ctx = idr_find(&mgr->ctx_handles, id);
558 	if (!ctx) {
559 		mutex_unlock(&mgr->lock);
560 		return -EINVAL;
561 	}
562 
563 	/* TODO: these two are always zero */
564 	out->state.flags = 0x0;
565 	out->state.hangs = 0x0;
566 
567 	/* determine if a GPU reset has occured since the last call */
568 	reset_counter = atomic_read(&adev->gpu_reset_counter);
569 	/* TODO: this should ideally return NO, GUILTY, or INNOCENT. */
570 	if (ctx->reset_counter_query == reset_counter)
571 		out->state.reset_status = AMDGPU_CTX_NO_RESET;
572 	else
573 		out->state.reset_status = AMDGPU_CTX_UNKNOWN_RESET;
574 	ctx->reset_counter_query = reset_counter;
575 
576 	mutex_unlock(&mgr->lock);
577 	return 0;
578 }
579 
580 #define AMDGPU_RAS_COUNTE_DELAY_MS 3000
581 
582 static bool amdgpu_ctx_guilty(struct amdgpu_ctx *ctx)
583 {
584 	int i, j, r;
585 
586 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
587 		for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
588 			struct amdgpu_ctx_entity *ctx_entity;
589 
590 			ctx_entity = ctx->entities[i][j];
591 			if (!ctx_entity)
592 				continue;
593 
594 			r = drm_sched_entity_error(&ctx_entity->entity);
595 			if (r == -ETIME)
596 				return true;
597 		}
598 	}
599 
600 	return false;
601 }
602 
603 static int amdgpu_ctx_query2(struct amdgpu_device *adev,
604 			     struct amdgpu_fpriv *fpriv, uint32_t id,
605 			     union drm_amdgpu_ctx_out *out)
606 {
607 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
608 	struct amdgpu_ctx *ctx;
609 	struct amdgpu_ctx_mgr *mgr;
610 
611 	if (!fpriv)
612 		return -EINVAL;
613 
614 	mgr = &fpriv->ctx_mgr;
615 	mutex_lock(&mgr->lock);
616 	ctx = idr_find(&mgr->ctx_handles, id);
617 	if (!ctx) {
618 		mutex_unlock(&mgr->lock);
619 		return -EINVAL;
620 	}
621 
622 	out->state.flags = 0x0;
623 	out->state.hangs = 0x0;
624 
625 	if (ctx->reset_counter != atomic_read(&adev->gpu_reset_counter))
626 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RESET;
627 
628 	if (ctx->generation != amdgpu_vm_generation(adev, &fpriv->vm))
629 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_VRAMLOST;
630 
631 	if (amdgpu_ctx_guilty(ctx))
632 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_GUILTY;
633 
634 	if (amdgpu_in_reset(adev))
635 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RESET_IN_PROGRESS;
636 
637 	if (adev->ras_enabled && con) {
638 		/* Return the cached values in O(1),
639 		 * and schedule delayed work to cache
640 		 * new vaues.
641 		 */
642 		int ce_count, ue_count;
643 
644 		ce_count = atomic_read(&con->ras_ce_count);
645 		ue_count = atomic_read(&con->ras_ue_count);
646 
647 		if (ce_count != ctx->ras_counter_ce) {
648 			ctx->ras_counter_ce = ce_count;
649 			out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RAS_CE;
650 		}
651 
652 		if (ue_count != ctx->ras_counter_ue) {
653 			ctx->ras_counter_ue = ue_count;
654 			out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RAS_UE;
655 		}
656 
657 		schedule_delayed_work(&con->ras_counte_delay_work,
658 				      msecs_to_jiffies(AMDGPU_RAS_COUNTE_DELAY_MS));
659 	}
660 
661 	mutex_unlock(&mgr->lock);
662 	return 0;
663 }
664 
665 static int amdgpu_ctx_stable_pstate(struct amdgpu_device *adev,
666 				    struct amdgpu_fpriv *fpriv, uint32_t id,
667 				    bool set, u32 *stable_pstate)
668 {
669 	struct amdgpu_ctx *ctx;
670 	struct amdgpu_ctx_mgr *mgr;
671 	int r;
672 
673 	if (!fpriv)
674 		return -EINVAL;
675 
676 	mgr = &fpriv->ctx_mgr;
677 	mutex_lock(&mgr->lock);
678 	ctx = idr_find(&mgr->ctx_handles, id);
679 	if (!ctx) {
680 		mutex_unlock(&mgr->lock);
681 		return -EINVAL;
682 	}
683 
684 	if (set)
685 		r = amdgpu_ctx_set_stable_pstate(ctx, *stable_pstate);
686 	else
687 		r = amdgpu_ctx_get_stable_pstate(ctx, stable_pstate);
688 
689 	mutex_unlock(&mgr->lock);
690 	return r;
691 }
692 
693 int amdgpu_ctx_ioctl(struct drm_device *dev, void *data,
694 		     struct drm_file *filp)
695 {
696 	int r;
697 	uint32_t id, stable_pstate;
698 	int32_t priority;
699 
700 	union drm_amdgpu_ctx *args = data;
701 	struct amdgpu_device *adev = drm_to_adev(dev);
702 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
703 
704 	id = args->in.ctx_id;
705 	priority = args->in.priority;
706 
707 	/* For backwards compatibility, we need to accept ioctls with garbage
708 	 * in the priority field. Garbage values in the priority field, result
709 	 * in the priority being set to NORMAL.
710 	 */
711 	if (!amdgpu_ctx_priority_is_valid(priority))
712 		priority = AMDGPU_CTX_PRIORITY_NORMAL;
713 
714 	switch (args->in.op) {
715 	case AMDGPU_CTX_OP_ALLOC_CTX:
716 		if (args->in.flags)
717 			return -EINVAL;
718 		r = amdgpu_ctx_alloc(adev, fpriv, filp, priority, &id);
719 		args->out.alloc.ctx_id = id;
720 		break;
721 	case AMDGPU_CTX_OP_FREE_CTX:
722 		if (args->in.flags)
723 			return -EINVAL;
724 		r = amdgpu_ctx_free(fpriv, id);
725 		break;
726 	case AMDGPU_CTX_OP_QUERY_STATE:
727 		if (args->in.flags)
728 			return -EINVAL;
729 		r = amdgpu_ctx_query(adev, fpriv, id, &args->out);
730 		break;
731 	case AMDGPU_CTX_OP_QUERY_STATE2:
732 		if (args->in.flags)
733 			return -EINVAL;
734 		r = amdgpu_ctx_query2(adev, fpriv, id, &args->out);
735 		break;
736 	case AMDGPU_CTX_OP_GET_STABLE_PSTATE:
737 		if (args->in.flags)
738 			return -EINVAL;
739 		r = amdgpu_ctx_stable_pstate(adev, fpriv, id, false, &stable_pstate);
740 		if (!r)
741 			args->out.pstate.flags = stable_pstate;
742 		break;
743 	case AMDGPU_CTX_OP_SET_STABLE_PSTATE:
744 		if (args->in.flags & ~AMDGPU_CTX_STABLE_PSTATE_FLAGS_MASK)
745 			return -EINVAL;
746 		stable_pstate = args->in.flags & AMDGPU_CTX_STABLE_PSTATE_FLAGS_MASK;
747 		if (stable_pstate > AMDGPU_CTX_STABLE_PSTATE_PEAK)
748 			return -EINVAL;
749 		r = amdgpu_ctx_stable_pstate(adev, fpriv, id, true, &stable_pstate);
750 		break;
751 	default:
752 		return -EINVAL;
753 	}
754 
755 	return r;
756 }
757 
758 struct amdgpu_ctx *amdgpu_ctx_get(struct amdgpu_fpriv *fpriv, uint32_t id)
759 {
760 	struct amdgpu_ctx *ctx;
761 	struct amdgpu_ctx_mgr *mgr;
762 
763 	if (!fpriv)
764 		return NULL;
765 
766 	mgr = &fpriv->ctx_mgr;
767 
768 	mutex_lock(&mgr->lock);
769 	ctx = idr_find(&mgr->ctx_handles, id);
770 	if (ctx)
771 		kref_get(&ctx->refcount);
772 	mutex_unlock(&mgr->lock);
773 	return ctx;
774 }
775 
776 int amdgpu_ctx_put(struct amdgpu_ctx *ctx)
777 {
778 	if (ctx == NULL)
779 		return -EINVAL;
780 
781 	kref_put(&ctx->refcount, amdgpu_ctx_do_release);
782 	return 0;
783 }
784 
785 uint64_t amdgpu_ctx_add_fence(struct amdgpu_ctx *ctx,
786 			      struct drm_sched_entity *entity,
787 			      struct dma_fence *fence)
788 {
789 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
790 	uint64_t seq = centity->sequence;
791 	struct dma_fence *other = NULL;
792 	unsigned idx = 0;
793 
794 	idx = seq & (amdgpu_sched_jobs - 1);
795 	other = centity->fences[idx];
796 	WARN_ON(other && !dma_fence_is_signaled(other));
797 
798 	dma_fence_get(fence);
799 
800 	spin_lock(&ctx->ring_lock);
801 	centity->fences[idx] = fence;
802 	centity->sequence++;
803 	spin_unlock(&ctx->ring_lock);
804 
805 	atomic64_add(ktime_to_ns(amdgpu_ctx_fence_time(other)),
806 		     &ctx->mgr->time_spend[centity->hw_ip]);
807 
808 	dma_fence_put(other);
809 	return seq;
810 }
811 
812 struct dma_fence *amdgpu_ctx_get_fence(struct amdgpu_ctx *ctx,
813 				       struct drm_sched_entity *entity,
814 				       uint64_t seq)
815 {
816 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
817 	struct dma_fence *fence;
818 
819 	spin_lock(&ctx->ring_lock);
820 
821 	if (seq == ~0ull)
822 		seq = centity->sequence - 1;
823 
824 	if (seq >= centity->sequence) {
825 		spin_unlock(&ctx->ring_lock);
826 		return ERR_PTR(-EINVAL);
827 	}
828 
829 
830 	if (seq + amdgpu_sched_jobs < centity->sequence) {
831 		spin_unlock(&ctx->ring_lock);
832 		return NULL;
833 	}
834 
835 	fence = dma_fence_get(centity->fences[seq & (amdgpu_sched_jobs - 1)]);
836 	spin_unlock(&ctx->ring_lock);
837 
838 	return fence;
839 }
840 
841 static void amdgpu_ctx_set_entity_priority(struct amdgpu_ctx *ctx,
842 					   struct amdgpu_ctx_entity *aentity,
843 					   int hw_ip,
844 					   int32_t priority)
845 {
846 	struct amdgpu_device *adev = ctx->mgr->adev;
847 	unsigned int hw_prio;
848 	struct drm_gpu_scheduler **scheds = NULL;
849 	unsigned num_scheds;
850 
851 	/* set sw priority */
852 	drm_sched_entity_set_priority(&aentity->entity,
853 				      amdgpu_ctx_to_drm_sched_prio(priority));
854 
855 	/* set hw priority */
856 	if (hw_ip == AMDGPU_HW_IP_COMPUTE || hw_ip == AMDGPU_HW_IP_GFX) {
857 		hw_prio = amdgpu_ctx_get_hw_prio(ctx, hw_ip);
858 		hw_prio = array_index_nospec(hw_prio, AMDGPU_RING_PRIO_MAX);
859 		scheds = adev->gpu_sched[hw_ip][hw_prio].sched;
860 		num_scheds = adev->gpu_sched[hw_ip][hw_prio].num_scheds;
861 		drm_sched_entity_modify_sched(&aentity->entity, scheds,
862 					      num_scheds);
863 	}
864 }
865 
866 void amdgpu_ctx_priority_override(struct amdgpu_ctx *ctx,
867 				  int32_t priority)
868 {
869 	int32_t ctx_prio;
870 	unsigned i, j;
871 
872 	ctx->override_priority = priority;
873 
874 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
875 			ctx->init_priority : ctx->override_priority;
876 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
877 		for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
878 			if (!ctx->entities[i][j])
879 				continue;
880 
881 			amdgpu_ctx_set_entity_priority(ctx, ctx->entities[i][j],
882 						       i, ctx_prio);
883 		}
884 	}
885 }
886 
887 int amdgpu_ctx_wait_prev_fence(struct amdgpu_ctx *ctx,
888 			       struct drm_sched_entity *entity)
889 {
890 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
891 	struct dma_fence *other;
892 	unsigned idx;
893 	long r;
894 
895 	spin_lock(&ctx->ring_lock);
896 	idx = centity->sequence & (amdgpu_sched_jobs - 1);
897 	other = dma_fence_get(centity->fences[idx]);
898 	spin_unlock(&ctx->ring_lock);
899 
900 	if (!other)
901 		return 0;
902 
903 	r = dma_fence_wait(other, true);
904 	if (r < 0 && r != -ERESTARTSYS)
905 		drm_err(adev_to_drm(ctx->mgr->adev),
906 			"AMDGPU: Error waiting for fence in ctx %p\n", ctx);
907 
908 	dma_fence_put(other);
909 	return r;
910 }
911 
912 void amdgpu_ctx_mgr_init(struct amdgpu_ctx_mgr *mgr,
913 			 struct amdgpu_device *adev)
914 {
915 	unsigned int i;
916 
917 	mgr->adev = adev;
918 	mutex_init(&mgr->lock);
919 	idr_init_base(&mgr->ctx_handles, 1);
920 
921 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i)
922 		atomic64_set(&mgr->time_spend[i], 0);
923 }
924 
925 long amdgpu_ctx_mgr_entity_flush(struct amdgpu_ctx_mgr *mgr, long timeout)
926 {
927 	struct amdgpu_ctx *ctx;
928 	struct idr *idp;
929 	uint32_t id, i, j;
930 
931 	idp = &mgr->ctx_handles;
932 
933 	mutex_lock(&mgr->lock);
934 	idr_for_each_entry(idp, ctx, id) {
935 		for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
936 			for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
937 				struct drm_sched_entity *entity;
938 
939 				if (!ctx->entities[i][j])
940 					continue;
941 
942 				entity = &ctx->entities[i][j]->entity;
943 				timeout = drm_sched_entity_flush(entity, timeout);
944 			}
945 		}
946 	}
947 	mutex_unlock(&mgr->lock);
948 	return timeout;
949 }
950 
951 static void amdgpu_ctx_mgr_entity_fini(struct amdgpu_ctx_mgr *mgr)
952 {
953 	struct amdgpu_ctx *ctx;
954 	struct idr *idp;
955 	uint32_t id, i, j;
956 
957 	idp = &mgr->ctx_handles;
958 
959 	idr_for_each_entry(idp, ctx, id) {
960 		if (kref_read(&ctx->refcount) != 1) {
961 			drm_err(adev_to_drm(mgr->adev), "ctx %p is still alive\n", ctx);
962 			continue;
963 		}
964 
965 		for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
966 			for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
967 				struct drm_sched_entity *entity;
968 
969 				if (!ctx->entities[i][j])
970 					continue;
971 
972 				entity = &ctx->entities[i][j]->entity;
973 				drm_sched_entity_fini(entity);
974 			}
975 		}
976 		kref_put(&ctx->refcount, amdgpu_ctx_fini);
977 	}
978 }
979 
980 void amdgpu_ctx_mgr_fini(struct amdgpu_ctx_mgr *mgr)
981 {
982 	amdgpu_ctx_mgr_entity_fini(mgr);
983 	idr_destroy(&mgr->ctx_handles);
984 	mutex_destroy(&mgr->lock);
985 }
986 
987 void amdgpu_ctx_mgr_usage(struct amdgpu_ctx_mgr *mgr,
988 			  ktime_t usage[AMDGPU_HW_IP_NUM])
989 {
990 	struct amdgpu_ctx *ctx;
991 	unsigned int hw_ip, i;
992 	uint32_t id;
993 
994 	/*
995 	 * This is a little bit racy because it can be that a ctx or a fence are
996 	 * destroyed just in the moment we try to account them. But that is ok
997 	 * since exactly that case is explicitely allowed by the interface.
998 	 */
999 	mutex_lock(&mgr->lock);
1000 	for (hw_ip = 0; hw_ip < AMDGPU_HW_IP_NUM; ++hw_ip) {
1001 		uint64_t ns = atomic64_read(&mgr->time_spend[hw_ip]);
1002 
1003 		usage[hw_ip] = ns_to_ktime(ns);
1004 	}
1005 
1006 	idr_for_each_entry(&mgr->ctx_handles, ctx, id) {
1007 		for (hw_ip = 0; hw_ip < AMDGPU_HW_IP_NUM; ++hw_ip) {
1008 			for (i = 0; i < amdgpu_ctx_num_entities[hw_ip]; ++i) {
1009 				struct amdgpu_ctx_entity *centity;
1010 				ktime_t spend;
1011 
1012 				centity = ctx->entities[hw_ip][i];
1013 				if (!centity)
1014 					continue;
1015 				spend = amdgpu_ctx_entity_time(ctx, centity);
1016 				usage[hw_ip] = ktime_add(usage[hw_ip], spend);
1017 			}
1018 		}
1019 	}
1020 	mutex_unlock(&mgr->lock);
1021 }
1022