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