xref: /openbmc/linux/drivers/gpu/drm/amd/amdgpu/amdgpu_ctx.c (revision 1ec1944eb50c8de2d96de1188eec9f8b22d03366)
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 "amdgpu.h"
27 #include "amdgpu_sched.h"
28 #include "amdgpu_ras.h"
29 #include <linux/nospec.h>
30 
31 #define to_amdgpu_ctx_entity(e)	\
32 	container_of((e), struct amdgpu_ctx_entity, entity)
33 
34 const unsigned int amdgpu_ctx_num_entities[AMDGPU_HW_IP_NUM] = {
35 	[AMDGPU_HW_IP_GFX]	=	1,
36 	[AMDGPU_HW_IP_COMPUTE]	=	4,
37 	[AMDGPU_HW_IP_DMA]	=	2,
38 	[AMDGPU_HW_IP_UVD]	=	1,
39 	[AMDGPU_HW_IP_VCE]	=	1,
40 	[AMDGPU_HW_IP_UVD_ENC]	=	1,
41 	[AMDGPU_HW_IP_VCN_DEC]	=	1,
42 	[AMDGPU_HW_IP_VCN_ENC]	=	1,
43 	[AMDGPU_HW_IP_VCN_JPEG]	=	1,
44 };
45 
46 bool amdgpu_ctx_priority_is_valid(int32_t ctx_prio)
47 {
48 	switch (ctx_prio) {
49 	case AMDGPU_CTX_PRIORITY_UNSET:
50 	case AMDGPU_CTX_PRIORITY_VERY_LOW:
51 	case AMDGPU_CTX_PRIORITY_LOW:
52 	case AMDGPU_CTX_PRIORITY_NORMAL:
53 	case AMDGPU_CTX_PRIORITY_HIGH:
54 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
55 		return true;
56 	default:
57 		return false;
58 	}
59 }
60 
61 static enum drm_sched_priority
62 amdgpu_ctx_to_drm_sched_prio(int32_t ctx_prio)
63 {
64 	switch (ctx_prio) {
65 	case AMDGPU_CTX_PRIORITY_UNSET:
66 		return DRM_SCHED_PRIORITY_UNSET;
67 
68 	case AMDGPU_CTX_PRIORITY_VERY_LOW:
69 		return DRM_SCHED_PRIORITY_MIN;
70 
71 	case AMDGPU_CTX_PRIORITY_LOW:
72 		return DRM_SCHED_PRIORITY_MIN;
73 
74 	case AMDGPU_CTX_PRIORITY_NORMAL:
75 		return DRM_SCHED_PRIORITY_NORMAL;
76 
77 	case AMDGPU_CTX_PRIORITY_HIGH:
78 		return DRM_SCHED_PRIORITY_HIGH;
79 
80 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
81 		return DRM_SCHED_PRIORITY_HIGH;
82 
83 	/* This should not happen as we sanitized userspace provided priority
84 	 * already, WARN if this happens.
85 	 */
86 	default:
87 		WARN(1, "Invalid context priority %d\n", ctx_prio);
88 		return DRM_SCHED_PRIORITY_NORMAL;
89 	}
90 
91 }
92 
93 static int amdgpu_ctx_priority_permit(struct drm_file *filp,
94 				      int32_t priority)
95 {
96 	if (!amdgpu_ctx_priority_is_valid(priority))
97 		return -EINVAL;
98 
99 	/* NORMAL and below are accessible by everyone */
100 	if (priority <= AMDGPU_CTX_PRIORITY_NORMAL)
101 		return 0;
102 
103 	if (capable(CAP_SYS_NICE))
104 		return 0;
105 
106 	if (drm_is_current_master(filp))
107 		return 0;
108 
109 	return -EACCES;
110 }
111 
112 static enum amdgpu_gfx_pipe_priority amdgpu_ctx_prio_to_compute_prio(int32_t prio)
113 {
114 	switch (prio) {
115 	case AMDGPU_CTX_PRIORITY_HIGH:
116 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
117 		return AMDGPU_GFX_PIPE_PRIO_HIGH;
118 	default:
119 		return AMDGPU_GFX_PIPE_PRIO_NORMAL;
120 	}
121 }
122 
123 static enum amdgpu_ring_priority_level amdgpu_ctx_sched_prio_to_ring_prio(int32_t prio)
124 {
125 	switch (prio) {
126 	case AMDGPU_CTX_PRIORITY_HIGH:
127 		return AMDGPU_RING_PRIO_1;
128 	case AMDGPU_CTX_PRIORITY_VERY_HIGH:
129 		return AMDGPU_RING_PRIO_2;
130 	default:
131 		return AMDGPU_RING_PRIO_0;
132 	}
133 }
134 
135 static unsigned int amdgpu_ctx_get_hw_prio(struct amdgpu_ctx *ctx, u32 hw_ip)
136 {
137 	struct amdgpu_device *adev = ctx->adev;
138 	int32_t ctx_prio;
139 	unsigned int hw_prio;
140 
141 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
142 			ctx->init_priority : ctx->override_priority;
143 
144 	switch (hw_ip) {
145 	case AMDGPU_HW_IP_COMPUTE:
146 		hw_prio = amdgpu_ctx_prio_to_compute_prio(ctx_prio);
147 		break;
148 	case AMDGPU_HW_IP_VCE:
149 	case AMDGPU_HW_IP_VCN_ENC:
150 		hw_prio = amdgpu_ctx_sched_prio_to_ring_prio(ctx_prio);
151 		break;
152 	default:
153 		hw_prio = AMDGPU_RING_PRIO_DEFAULT;
154 		break;
155 	}
156 
157 	hw_ip = array_index_nospec(hw_ip, AMDGPU_HW_IP_NUM);
158 	if (adev->gpu_sched[hw_ip][hw_prio].num_scheds == 0)
159 		hw_prio = AMDGPU_RING_PRIO_DEFAULT;
160 
161 	return hw_prio;
162 }
163 
164 
165 static int amdgpu_ctx_init_entity(struct amdgpu_ctx *ctx, u32 hw_ip,
166 				  const u32 ring)
167 {
168 	struct amdgpu_device *adev = ctx->adev;
169 	struct amdgpu_ctx_entity *entity;
170 	struct drm_gpu_scheduler **scheds = NULL, *sched = NULL;
171 	unsigned num_scheds = 0;
172 	int32_t ctx_prio;
173 	unsigned int hw_prio;
174 	enum drm_sched_priority drm_prio;
175 	int r;
176 
177 	entity = kzalloc(struct_size(entity, fences, amdgpu_sched_jobs),
178 			 GFP_KERNEL);
179 	if (!entity)
180 		return  -ENOMEM;
181 
182 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
183 			ctx->init_priority : ctx->override_priority;
184 	entity->sequence = 1;
185 	hw_prio = amdgpu_ctx_get_hw_prio(ctx, hw_ip);
186 	drm_prio = amdgpu_ctx_to_drm_sched_prio(ctx_prio);
187 
188 	hw_ip = array_index_nospec(hw_ip, AMDGPU_HW_IP_NUM);
189 	scheds = adev->gpu_sched[hw_ip][hw_prio].sched;
190 	num_scheds = adev->gpu_sched[hw_ip][hw_prio].num_scheds;
191 
192 	/* disable load balance if the hw engine retains context among dependent jobs */
193 	if (hw_ip == AMDGPU_HW_IP_VCN_ENC ||
194 	    hw_ip == AMDGPU_HW_IP_VCN_DEC ||
195 	    hw_ip == AMDGPU_HW_IP_UVD_ENC ||
196 	    hw_ip == AMDGPU_HW_IP_UVD) {
197 		sched = drm_sched_pick_best(scheds, num_scheds);
198 		scheds = &sched;
199 		num_scheds = 1;
200 	}
201 
202 	r = drm_sched_entity_init(&entity->entity, drm_prio, scheds, num_scheds,
203 				  &ctx->guilty);
204 	if (r)
205 		goto error_free_entity;
206 
207 	ctx->entities[hw_ip][ring] = entity;
208 	return 0;
209 
210 error_free_entity:
211 	kfree(entity);
212 
213 	return r;
214 }
215 
216 static int amdgpu_ctx_init(struct amdgpu_device *adev,
217 			   int32_t priority,
218 			   struct drm_file *filp,
219 			   struct amdgpu_ctx *ctx)
220 {
221 	int r;
222 
223 	r = amdgpu_ctx_priority_permit(filp, priority);
224 	if (r)
225 		return r;
226 
227 	memset(ctx, 0, sizeof(*ctx));
228 
229 	ctx->adev = adev;
230 
231 	kref_init(&ctx->refcount);
232 	spin_lock_init(&ctx->ring_lock);
233 
234 	ctx->reset_counter = atomic_read(&adev->gpu_reset_counter);
235 	ctx->reset_counter_query = ctx->reset_counter;
236 	ctx->vram_lost_counter = atomic_read(&adev->vram_lost_counter);
237 	ctx->init_priority = priority;
238 	ctx->override_priority = AMDGPU_CTX_PRIORITY_UNSET;
239 	ctx->stable_pstate = AMDGPU_CTX_STABLE_PSTATE_NONE;
240 
241 	return 0;
242 }
243 
244 static void amdgpu_ctx_fini_entity(struct amdgpu_ctx_entity *entity)
245 {
246 
247 	int i;
248 
249 	if (!entity)
250 		return;
251 
252 	for (i = 0; i < amdgpu_sched_jobs; ++i)
253 		dma_fence_put(entity->fences[i]);
254 
255 	kfree(entity);
256 }
257 
258 static int amdgpu_ctx_get_stable_pstate(struct amdgpu_ctx *ctx,
259 					u32 *stable_pstate)
260 {
261 	struct amdgpu_device *adev = ctx->adev;
262 	enum amd_dpm_forced_level current_level;
263 
264 	if (!ctx)
265 		return -EINVAL;
266 
267 	current_level = amdgpu_dpm_get_performance_level(adev);
268 
269 	switch (current_level) {
270 	case AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD:
271 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_STANDARD;
272 		break;
273 	case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK:
274 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_MIN_SCLK;
275 		break;
276 	case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK:
277 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_MIN_MCLK;
278 		break;
279 	case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK:
280 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_PEAK;
281 		break;
282 	default:
283 		*stable_pstate = AMDGPU_CTX_STABLE_PSTATE_NONE;
284 		break;
285 	}
286 	return 0;
287 }
288 
289 static int amdgpu_ctx_set_stable_pstate(struct amdgpu_ctx *ctx,
290 					u32 stable_pstate)
291 {
292 	struct amdgpu_device *adev = ctx->adev;
293 	enum amd_dpm_forced_level level;
294 	int r;
295 
296 	if (!ctx)
297 		return -EINVAL;
298 
299 	mutex_lock(&adev->pm.stable_pstate_ctx_lock);
300 	if (adev->pm.stable_pstate_ctx && adev->pm.stable_pstate_ctx != ctx) {
301 		r = -EBUSY;
302 		goto done;
303 	}
304 
305 	switch (stable_pstate) {
306 	case AMDGPU_CTX_STABLE_PSTATE_NONE:
307 		level = AMD_DPM_FORCED_LEVEL_AUTO;
308 		break;
309 	case AMDGPU_CTX_STABLE_PSTATE_STANDARD:
310 		level = AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD;
311 		break;
312 	case AMDGPU_CTX_STABLE_PSTATE_MIN_SCLK:
313 		level = AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK;
314 		break;
315 	case AMDGPU_CTX_STABLE_PSTATE_MIN_MCLK:
316 		level = AMD_DPM_FORCED_LEVEL_PROFILE_MIN_MCLK;
317 		break;
318 	case AMDGPU_CTX_STABLE_PSTATE_PEAK:
319 		level = AMD_DPM_FORCED_LEVEL_PROFILE_PEAK;
320 		break;
321 	default:
322 		r = -EINVAL;
323 		goto done;
324 	}
325 
326 	r = amdgpu_dpm_force_performance_level(adev, level);
327 
328 	if (level == AMD_DPM_FORCED_LEVEL_AUTO)
329 		adev->pm.stable_pstate_ctx = NULL;
330 	else
331 		adev->pm.stable_pstate_ctx = ctx;
332 done:
333 	mutex_unlock(&adev->pm.stable_pstate_ctx_lock);
334 
335 	return r;
336 }
337 
338 static void amdgpu_ctx_fini(struct kref *ref)
339 {
340 	struct amdgpu_ctx *ctx = container_of(ref, struct amdgpu_ctx, refcount);
341 	struct amdgpu_device *adev = ctx->adev;
342 	unsigned i, j;
343 
344 	if (!adev)
345 		return;
346 
347 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
348 		for (j = 0; j < AMDGPU_MAX_ENTITY_NUM; ++j) {
349 			amdgpu_ctx_fini_entity(ctx->entities[i][j]);
350 			ctx->entities[i][j] = NULL;
351 		}
352 	}
353 	amdgpu_ctx_set_stable_pstate(ctx, AMDGPU_CTX_STABLE_PSTATE_NONE);
354 	kfree(ctx);
355 }
356 
357 int amdgpu_ctx_get_entity(struct amdgpu_ctx *ctx, u32 hw_ip, u32 instance,
358 			  u32 ring, struct drm_sched_entity **entity)
359 {
360 	int r;
361 
362 	if (hw_ip >= AMDGPU_HW_IP_NUM) {
363 		DRM_ERROR("unknown HW IP type: %d\n", hw_ip);
364 		return -EINVAL;
365 	}
366 
367 	/* Right now all IPs have only one instance - multiple rings. */
368 	if (instance != 0) {
369 		DRM_DEBUG("invalid ip instance: %d\n", instance);
370 		return -EINVAL;
371 	}
372 
373 	if (ring >= amdgpu_ctx_num_entities[hw_ip]) {
374 		DRM_DEBUG("invalid ring: %d %d\n", hw_ip, ring);
375 		return -EINVAL;
376 	}
377 
378 	if (ctx->entities[hw_ip][ring] == NULL) {
379 		r = amdgpu_ctx_init_entity(ctx, hw_ip, ring);
380 		if (r)
381 			return r;
382 	}
383 
384 	*entity = &ctx->entities[hw_ip][ring]->entity;
385 	return 0;
386 }
387 
388 static int amdgpu_ctx_alloc(struct amdgpu_device *adev,
389 			    struct amdgpu_fpriv *fpriv,
390 			    struct drm_file *filp,
391 			    int32_t priority,
392 			    uint32_t *id)
393 {
394 	struct amdgpu_ctx_mgr *mgr = &fpriv->ctx_mgr;
395 	struct amdgpu_ctx *ctx;
396 	int r;
397 
398 	ctx = kmalloc(sizeof(*ctx), GFP_KERNEL);
399 	if (!ctx)
400 		return -ENOMEM;
401 
402 	mutex_lock(&mgr->lock);
403 	r = idr_alloc(&mgr->ctx_handles, ctx, 1, AMDGPU_VM_MAX_NUM_CTX, GFP_KERNEL);
404 	if (r < 0) {
405 		mutex_unlock(&mgr->lock);
406 		kfree(ctx);
407 		return r;
408 	}
409 
410 	*id = (uint32_t)r;
411 	r = amdgpu_ctx_init(adev, priority, filp, ctx);
412 	if (r) {
413 		idr_remove(&mgr->ctx_handles, *id);
414 		*id = 0;
415 		kfree(ctx);
416 	}
417 	mutex_unlock(&mgr->lock);
418 	return r;
419 }
420 
421 static void amdgpu_ctx_do_release(struct kref *ref)
422 {
423 	struct amdgpu_ctx *ctx;
424 	u32 i, j;
425 
426 	ctx = container_of(ref, struct amdgpu_ctx, refcount);
427 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
428 		for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
429 			if (!ctx->entities[i][j])
430 				continue;
431 
432 			drm_sched_entity_destroy(&ctx->entities[i][j]->entity);
433 		}
434 	}
435 
436 	amdgpu_ctx_fini(ref);
437 }
438 
439 static int amdgpu_ctx_free(struct amdgpu_fpriv *fpriv, uint32_t id)
440 {
441 	struct amdgpu_ctx_mgr *mgr = &fpriv->ctx_mgr;
442 	struct amdgpu_ctx *ctx;
443 
444 	mutex_lock(&mgr->lock);
445 	ctx = idr_remove(&mgr->ctx_handles, id);
446 	if (ctx)
447 		kref_put(&ctx->refcount, amdgpu_ctx_do_release);
448 	mutex_unlock(&mgr->lock);
449 	return ctx ? 0 : -EINVAL;
450 }
451 
452 static int amdgpu_ctx_query(struct amdgpu_device *adev,
453 			    struct amdgpu_fpriv *fpriv, uint32_t id,
454 			    union drm_amdgpu_ctx_out *out)
455 {
456 	struct amdgpu_ctx *ctx;
457 	struct amdgpu_ctx_mgr *mgr;
458 	unsigned reset_counter;
459 
460 	if (!fpriv)
461 		return -EINVAL;
462 
463 	mgr = &fpriv->ctx_mgr;
464 	mutex_lock(&mgr->lock);
465 	ctx = idr_find(&mgr->ctx_handles, id);
466 	if (!ctx) {
467 		mutex_unlock(&mgr->lock);
468 		return -EINVAL;
469 	}
470 
471 	/* TODO: these two are always zero */
472 	out->state.flags = 0x0;
473 	out->state.hangs = 0x0;
474 
475 	/* determine if a GPU reset has occured since the last call */
476 	reset_counter = atomic_read(&adev->gpu_reset_counter);
477 	/* TODO: this should ideally return NO, GUILTY, or INNOCENT. */
478 	if (ctx->reset_counter_query == reset_counter)
479 		out->state.reset_status = AMDGPU_CTX_NO_RESET;
480 	else
481 		out->state.reset_status = AMDGPU_CTX_UNKNOWN_RESET;
482 	ctx->reset_counter_query = reset_counter;
483 
484 	mutex_unlock(&mgr->lock);
485 	return 0;
486 }
487 
488 #define AMDGPU_RAS_COUNTE_DELAY_MS 3000
489 
490 static int amdgpu_ctx_query2(struct amdgpu_device *adev,
491 			     struct amdgpu_fpriv *fpriv, uint32_t id,
492 			     union drm_amdgpu_ctx_out *out)
493 {
494 	struct amdgpu_ras *con = amdgpu_ras_get_context(adev);
495 	struct amdgpu_ctx *ctx;
496 	struct amdgpu_ctx_mgr *mgr;
497 
498 	if (!fpriv)
499 		return -EINVAL;
500 
501 	mgr = &fpriv->ctx_mgr;
502 	mutex_lock(&mgr->lock);
503 	ctx = idr_find(&mgr->ctx_handles, id);
504 	if (!ctx) {
505 		mutex_unlock(&mgr->lock);
506 		return -EINVAL;
507 	}
508 
509 	out->state.flags = 0x0;
510 	out->state.hangs = 0x0;
511 
512 	if (ctx->reset_counter != atomic_read(&adev->gpu_reset_counter))
513 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RESET;
514 
515 	if (ctx->vram_lost_counter != atomic_read(&adev->vram_lost_counter))
516 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_VRAMLOST;
517 
518 	if (atomic_read(&ctx->guilty))
519 		out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_GUILTY;
520 
521 	if (adev->ras_enabled && con) {
522 		/* Return the cached values in O(1),
523 		 * and schedule delayed work to cache
524 		 * new vaues.
525 		 */
526 		int ce_count, ue_count;
527 
528 		ce_count = atomic_read(&con->ras_ce_count);
529 		ue_count = atomic_read(&con->ras_ue_count);
530 
531 		if (ce_count != ctx->ras_counter_ce) {
532 			ctx->ras_counter_ce = ce_count;
533 			out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RAS_CE;
534 		}
535 
536 		if (ue_count != ctx->ras_counter_ue) {
537 			ctx->ras_counter_ue = ue_count;
538 			out->state.flags |= AMDGPU_CTX_QUERY2_FLAGS_RAS_UE;
539 		}
540 
541 		schedule_delayed_work(&con->ras_counte_delay_work,
542 				      msecs_to_jiffies(AMDGPU_RAS_COUNTE_DELAY_MS));
543 	}
544 
545 	mutex_unlock(&mgr->lock);
546 	return 0;
547 }
548 
549 
550 
551 static int amdgpu_ctx_stable_pstate(struct amdgpu_device *adev,
552 				    struct amdgpu_fpriv *fpriv, uint32_t id,
553 				    bool set, u32 *stable_pstate)
554 {
555 	struct amdgpu_ctx *ctx;
556 	struct amdgpu_ctx_mgr *mgr;
557 	int r;
558 
559 	if (!fpriv)
560 		return -EINVAL;
561 
562 	mgr = &fpriv->ctx_mgr;
563 	mutex_lock(&mgr->lock);
564 	ctx = idr_find(&mgr->ctx_handles, id);
565 	if (!ctx) {
566 		mutex_unlock(&mgr->lock);
567 		return -EINVAL;
568 	}
569 
570 	if (set)
571 		r = amdgpu_ctx_set_stable_pstate(ctx, *stable_pstate);
572 	else
573 		r = amdgpu_ctx_get_stable_pstate(ctx, stable_pstate);
574 
575 	mutex_unlock(&mgr->lock);
576 	return r;
577 }
578 
579 int amdgpu_ctx_ioctl(struct drm_device *dev, void *data,
580 		     struct drm_file *filp)
581 {
582 	int r;
583 	uint32_t id, stable_pstate;
584 	int32_t priority;
585 
586 	union drm_amdgpu_ctx *args = data;
587 	struct amdgpu_device *adev = drm_to_adev(dev);
588 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
589 
590 	id = args->in.ctx_id;
591 	priority = args->in.priority;
592 
593 	/* For backwards compatibility reasons, we need to accept
594 	 * ioctls with garbage in the priority field */
595 	if (!amdgpu_ctx_priority_is_valid(priority))
596 		priority = AMDGPU_CTX_PRIORITY_NORMAL;
597 
598 	switch (args->in.op) {
599 	case AMDGPU_CTX_OP_ALLOC_CTX:
600 		r = amdgpu_ctx_alloc(adev, fpriv, filp, priority, &id);
601 		args->out.alloc.ctx_id = id;
602 		break;
603 	case AMDGPU_CTX_OP_FREE_CTX:
604 		r = amdgpu_ctx_free(fpriv, id);
605 		break;
606 	case AMDGPU_CTX_OP_QUERY_STATE:
607 		r = amdgpu_ctx_query(adev, fpriv, id, &args->out);
608 		break;
609 	case AMDGPU_CTX_OP_QUERY_STATE2:
610 		r = amdgpu_ctx_query2(adev, fpriv, id, &args->out);
611 		break;
612 	case AMDGPU_CTX_OP_GET_STABLE_PSTATE:
613 		if (args->in.flags)
614 			return -EINVAL;
615 		r = amdgpu_ctx_stable_pstate(adev, fpriv, id, false, &stable_pstate);
616 		args->out.pstate.flags = stable_pstate;
617 		break;
618 	case AMDGPU_CTX_OP_SET_STABLE_PSTATE:
619 		if (args->in.flags & ~AMDGPU_CTX_STABLE_PSTATE_FLAGS_MASK)
620 			return -EINVAL;
621 		stable_pstate = args->in.flags & AMDGPU_CTX_STABLE_PSTATE_FLAGS_MASK;
622 		if (stable_pstate > AMDGPU_CTX_STABLE_PSTATE_PEAK)
623 			return -EINVAL;
624 		r = amdgpu_ctx_stable_pstate(adev, fpriv, id, true, &stable_pstate);
625 		break;
626 	default:
627 		return -EINVAL;
628 	}
629 
630 	return r;
631 }
632 
633 struct amdgpu_ctx *amdgpu_ctx_get(struct amdgpu_fpriv *fpriv, uint32_t id)
634 {
635 	struct amdgpu_ctx *ctx;
636 	struct amdgpu_ctx_mgr *mgr;
637 
638 	if (!fpriv)
639 		return NULL;
640 
641 	mgr = &fpriv->ctx_mgr;
642 
643 	mutex_lock(&mgr->lock);
644 	ctx = idr_find(&mgr->ctx_handles, id);
645 	if (ctx)
646 		kref_get(&ctx->refcount);
647 	mutex_unlock(&mgr->lock);
648 	return ctx;
649 }
650 
651 int amdgpu_ctx_put(struct amdgpu_ctx *ctx)
652 {
653 	if (ctx == NULL)
654 		return -EINVAL;
655 
656 	kref_put(&ctx->refcount, amdgpu_ctx_do_release);
657 	return 0;
658 }
659 
660 void amdgpu_ctx_add_fence(struct amdgpu_ctx *ctx,
661 			  struct drm_sched_entity *entity,
662 			  struct dma_fence *fence, uint64_t *handle)
663 {
664 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
665 	uint64_t seq = centity->sequence;
666 	struct dma_fence *other = NULL;
667 	unsigned idx = 0;
668 
669 	idx = seq & (amdgpu_sched_jobs - 1);
670 	other = centity->fences[idx];
671 	if (other)
672 		BUG_ON(!dma_fence_is_signaled(other));
673 
674 	dma_fence_get(fence);
675 
676 	spin_lock(&ctx->ring_lock);
677 	centity->fences[idx] = fence;
678 	centity->sequence++;
679 	spin_unlock(&ctx->ring_lock);
680 
681 	dma_fence_put(other);
682 	if (handle)
683 		*handle = seq;
684 }
685 
686 struct dma_fence *amdgpu_ctx_get_fence(struct amdgpu_ctx *ctx,
687 				       struct drm_sched_entity *entity,
688 				       uint64_t seq)
689 {
690 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
691 	struct dma_fence *fence;
692 
693 	spin_lock(&ctx->ring_lock);
694 
695 	if (seq == ~0ull)
696 		seq = centity->sequence - 1;
697 
698 	if (seq >= centity->sequence) {
699 		spin_unlock(&ctx->ring_lock);
700 		return ERR_PTR(-EINVAL);
701 	}
702 
703 
704 	if (seq + amdgpu_sched_jobs < centity->sequence) {
705 		spin_unlock(&ctx->ring_lock);
706 		return NULL;
707 	}
708 
709 	fence = dma_fence_get(centity->fences[seq & (amdgpu_sched_jobs - 1)]);
710 	spin_unlock(&ctx->ring_lock);
711 
712 	return fence;
713 }
714 
715 static void amdgpu_ctx_set_entity_priority(struct amdgpu_ctx *ctx,
716 					   struct amdgpu_ctx_entity *aentity,
717 					   int hw_ip,
718 					   int32_t priority)
719 {
720 	struct amdgpu_device *adev = ctx->adev;
721 	unsigned int hw_prio;
722 	struct drm_gpu_scheduler **scheds = NULL;
723 	unsigned num_scheds;
724 
725 	/* set sw priority */
726 	drm_sched_entity_set_priority(&aentity->entity,
727 				      amdgpu_ctx_to_drm_sched_prio(priority));
728 
729 	/* set hw priority */
730 	if (hw_ip == AMDGPU_HW_IP_COMPUTE) {
731 		hw_prio = amdgpu_ctx_get_hw_prio(ctx, hw_ip);
732 		hw_prio = array_index_nospec(hw_prio, AMDGPU_RING_PRIO_MAX);
733 		scheds = adev->gpu_sched[hw_ip][hw_prio].sched;
734 		num_scheds = adev->gpu_sched[hw_ip][hw_prio].num_scheds;
735 		drm_sched_entity_modify_sched(&aentity->entity, scheds,
736 					      num_scheds);
737 	}
738 }
739 
740 void amdgpu_ctx_priority_override(struct amdgpu_ctx *ctx,
741 				  int32_t priority)
742 {
743 	int32_t ctx_prio;
744 	unsigned i, j;
745 
746 	ctx->override_priority = priority;
747 
748 	ctx_prio = (ctx->override_priority == AMDGPU_CTX_PRIORITY_UNSET) ?
749 			ctx->init_priority : ctx->override_priority;
750 	for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
751 		for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
752 			if (!ctx->entities[i][j])
753 				continue;
754 
755 			amdgpu_ctx_set_entity_priority(ctx, ctx->entities[i][j],
756 						       i, ctx_prio);
757 		}
758 	}
759 }
760 
761 int amdgpu_ctx_wait_prev_fence(struct amdgpu_ctx *ctx,
762 			       struct drm_sched_entity *entity)
763 {
764 	struct amdgpu_ctx_entity *centity = to_amdgpu_ctx_entity(entity);
765 	struct dma_fence *other;
766 	unsigned idx;
767 	long r;
768 
769 	spin_lock(&ctx->ring_lock);
770 	idx = centity->sequence & (amdgpu_sched_jobs - 1);
771 	other = dma_fence_get(centity->fences[idx]);
772 	spin_unlock(&ctx->ring_lock);
773 
774 	if (!other)
775 		return 0;
776 
777 	r = dma_fence_wait(other, true);
778 	if (r < 0 && r != -ERESTARTSYS)
779 		DRM_ERROR("Error (%ld) waiting for fence!\n", r);
780 
781 	dma_fence_put(other);
782 	return r;
783 }
784 
785 void amdgpu_ctx_mgr_init(struct amdgpu_ctx_mgr *mgr)
786 {
787 	mutex_init(&mgr->lock);
788 	idr_init(&mgr->ctx_handles);
789 }
790 
791 long amdgpu_ctx_mgr_entity_flush(struct amdgpu_ctx_mgr *mgr, long timeout)
792 {
793 	struct amdgpu_ctx *ctx;
794 	struct idr *idp;
795 	uint32_t id, i, j;
796 
797 	idp = &mgr->ctx_handles;
798 
799 	mutex_lock(&mgr->lock);
800 	idr_for_each_entry(idp, ctx, id) {
801 		for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
802 			for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
803 				struct drm_sched_entity *entity;
804 
805 				if (!ctx->entities[i][j])
806 					continue;
807 
808 				entity = &ctx->entities[i][j]->entity;
809 				timeout = drm_sched_entity_flush(entity, timeout);
810 			}
811 		}
812 	}
813 	mutex_unlock(&mgr->lock);
814 	return timeout;
815 }
816 
817 void amdgpu_ctx_mgr_entity_fini(struct amdgpu_ctx_mgr *mgr)
818 {
819 	struct amdgpu_ctx *ctx;
820 	struct idr *idp;
821 	uint32_t id, i, j;
822 
823 	idp = &mgr->ctx_handles;
824 
825 	idr_for_each_entry(idp, ctx, id) {
826 		if (kref_read(&ctx->refcount) != 1) {
827 			DRM_ERROR("ctx %p is still alive\n", ctx);
828 			continue;
829 		}
830 
831 		for (i = 0; i < AMDGPU_HW_IP_NUM; ++i) {
832 			for (j = 0; j < amdgpu_ctx_num_entities[i]; ++j) {
833 				struct drm_sched_entity *entity;
834 
835 				if (!ctx->entities[i][j])
836 					continue;
837 
838 				entity = &ctx->entities[i][j]->entity;
839 				drm_sched_entity_fini(entity);
840 			}
841 		}
842 	}
843 }
844 
845 void amdgpu_ctx_mgr_fini(struct amdgpu_ctx_mgr *mgr)
846 {
847 	struct amdgpu_ctx *ctx;
848 	struct idr *idp;
849 	uint32_t id;
850 
851 	amdgpu_ctx_mgr_entity_fini(mgr);
852 
853 	idp = &mgr->ctx_handles;
854 
855 	idr_for_each_entry(idp, ctx, id) {
856 		if (kref_put(&ctx->refcount, amdgpu_ctx_fini) != 1)
857 			DRM_ERROR("ctx %p is still alive\n", ctx);
858 	}
859 
860 	idr_destroy(&mgr->ctx_handles);
861 	mutex_destroy(&mgr->lock);
862 }
863 
864 static void amdgpu_ctx_fence_time(struct amdgpu_ctx *ctx,
865 		struct amdgpu_ctx_entity *centity, ktime_t *total, ktime_t *max)
866 {
867 	ktime_t now, t1;
868 	uint32_t i;
869 
870 	*total = *max = 0;
871 
872 	now = ktime_get();
873 	for (i = 0; i < amdgpu_sched_jobs; i++) {
874 		struct dma_fence *fence;
875 		struct drm_sched_fence *s_fence;
876 
877 		spin_lock(&ctx->ring_lock);
878 		fence = dma_fence_get(centity->fences[i]);
879 		spin_unlock(&ctx->ring_lock);
880 		if (!fence)
881 			continue;
882 		s_fence = to_drm_sched_fence(fence);
883 		if (!dma_fence_is_signaled(&s_fence->scheduled)) {
884 			dma_fence_put(fence);
885 			continue;
886 		}
887 		t1 = s_fence->scheduled.timestamp;
888 		if (!ktime_before(t1, now)) {
889 			dma_fence_put(fence);
890 			continue;
891 		}
892 		if (dma_fence_is_signaled(&s_fence->finished) &&
893 			s_fence->finished.timestamp < now)
894 			*total += ktime_sub(s_fence->finished.timestamp, t1);
895 		else
896 			*total += ktime_sub(now, t1);
897 		t1 = ktime_sub(now, t1);
898 		dma_fence_put(fence);
899 		*max = max(t1, *max);
900 	}
901 }
902 
903 ktime_t amdgpu_ctx_mgr_fence_usage(struct amdgpu_ctx_mgr *mgr, uint32_t hwip,
904 		uint32_t idx, uint64_t *elapsed)
905 {
906 	struct idr *idp;
907 	struct amdgpu_ctx *ctx;
908 	uint32_t id;
909 	struct amdgpu_ctx_entity *centity;
910 	ktime_t total = 0, max = 0;
911 
912 	if (idx >= AMDGPU_MAX_ENTITY_NUM)
913 		return 0;
914 	idp = &mgr->ctx_handles;
915 	mutex_lock(&mgr->lock);
916 	idr_for_each_entry(idp, ctx, id) {
917 		ktime_t ttotal, tmax;
918 
919 		if (!ctx->entities[hwip][idx])
920 			continue;
921 
922 		centity = ctx->entities[hwip][idx];
923 		amdgpu_ctx_fence_time(ctx, centity, &ttotal, &tmax);
924 
925 		/* Harmonic mean approximation diverges for very small
926 		 * values. If ratio < 0.01% ignore
927 		 */
928 		if (AMDGPU_CTX_FENCE_USAGE_MIN_RATIO(tmax, ttotal))
929 			continue;
930 
931 		total = ktime_add(total, ttotal);
932 		max = ktime_after(tmax, max) ? tmax : max;
933 	}
934 
935 	mutex_unlock(&mgr->lock);
936 	if (elapsed)
937 		*elapsed = max;
938 
939 	return total;
940 }
941