1 /*
2  * Copyright 2013 Advanced Micro Devices, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sub license, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
16  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
17  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19  * USE OR OTHER DEALINGS IN THE SOFTWARE.
20  *
21  * The above copyright notice and this permission notice (including the
22  * next paragraph) shall be included in all copies or substantial portions
23  * of the Software.
24  *
25  * Authors: Christian König <[email protected]>
26  */
27 
28 #include <linux/firmware.h>
29 #include <linux/module.h>
30 
31 #include <drm/drm.h>
32 
33 #include "amdgpu.h"
34 #include "amdgpu_pm.h"
35 #include "amdgpu_vce.h"
36 #include "cikd.h"
37 
38 /* 1 second timeout */
39 #define VCE_IDLE_TIMEOUT	msecs_to_jiffies(1000)
40 
41 /* Firmware Names */
42 #ifdef CONFIG_DRM_AMDGPU_CIK
43 #define FIRMWARE_BONAIRE	"amdgpu/bonaire_vce.bin"
44 #define FIRMWARE_KABINI	"amdgpu/kabini_vce.bin"
45 #define FIRMWARE_KAVERI	"amdgpu/kaveri_vce.bin"
46 #define FIRMWARE_HAWAII	"amdgpu/hawaii_vce.bin"
47 #define FIRMWARE_MULLINS	"amdgpu/mullins_vce.bin"
48 #endif
49 #define FIRMWARE_TONGA		"amdgpu/tonga_vce.bin"
50 #define FIRMWARE_CARRIZO	"amdgpu/carrizo_vce.bin"
51 #define FIRMWARE_FIJI		"amdgpu/fiji_vce.bin"
52 #define FIRMWARE_STONEY		"amdgpu/stoney_vce.bin"
53 #define FIRMWARE_POLARIS10	"amdgpu/polaris10_vce.bin"
54 #define FIRMWARE_POLARIS11	"amdgpu/polaris11_vce.bin"
55 #define FIRMWARE_POLARIS12	"amdgpu/polaris12_vce.bin"
56 #define FIRMWARE_VEGAM		"amdgpu/vegam_vce.bin"
57 
58 #define FIRMWARE_VEGA10		"amdgpu/vega10_vce.bin"
59 #define FIRMWARE_VEGA12		"amdgpu/vega12_vce.bin"
60 #define FIRMWARE_VEGA20		"amdgpu/vega20_vce.bin"
61 
62 #ifdef CONFIG_DRM_AMDGPU_CIK
63 MODULE_FIRMWARE(FIRMWARE_BONAIRE);
64 MODULE_FIRMWARE(FIRMWARE_KABINI);
65 MODULE_FIRMWARE(FIRMWARE_KAVERI);
66 MODULE_FIRMWARE(FIRMWARE_HAWAII);
67 MODULE_FIRMWARE(FIRMWARE_MULLINS);
68 #endif
69 MODULE_FIRMWARE(FIRMWARE_TONGA);
70 MODULE_FIRMWARE(FIRMWARE_CARRIZO);
71 MODULE_FIRMWARE(FIRMWARE_FIJI);
72 MODULE_FIRMWARE(FIRMWARE_STONEY);
73 MODULE_FIRMWARE(FIRMWARE_POLARIS10);
74 MODULE_FIRMWARE(FIRMWARE_POLARIS11);
75 MODULE_FIRMWARE(FIRMWARE_POLARIS12);
76 MODULE_FIRMWARE(FIRMWARE_VEGAM);
77 
78 MODULE_FIRMWARE(FIRMWARE_VEGA10);
79 MODULE_FIRMWARE(FIRMWARE_VEGA12);
80 MODULE_FIRMWARE(FIRMWARE_VEGA20);
81 
82 static void amdgpu_vce_idle_work_handler(struct work_struct *work);
83 static int amdgpu_vce_get_create_msg(struct amdgpu_ring *ring, uint32_t handle,
84 				     struct amdgpu_bo *bo,
85 				     struct dma_fence **fence);
86 static int amdgpu_vce_get_destroy_msg(struct amdgpu_ring *ring, uint32_t handle,
87 				      bool direct, struct dma_fence **fence);
88 
89 /**
90  * amdgpu_vce_init - allocate memory, load vce firmware
91  *
92  * @adev: amdgpu_device pointer
93  *
94  * First step to get VCE online, allocate memory and load the firmware
95  */
96 int amdgpu_vce_sw_init(struct amdgpu_device *adev, unsigned long size)
97 {
98 	const char *fw_name;
99 	const struct common_firmware_header *hdr;
100 	unsigned ucode_version, version_major, version_minor, binary_id;
101 	int i, r;
102 
103 	switch (adev->asic_type) {
104 #ifdef CONFIG_DRM_AMDGPU_CIK
105 	case CHIP_BONAIRE:
106 		fw_name = FIRMWARE_BONAIRE;
107 		break;
108 	case CHIP_KAVERI:
109 		fw_name = FIRMWARE_KAVERI;
110 		break;
111 	case CHIP_KABINI:
112 		fw_name = FIRMWARE_KABINI;
113 		break;
114 	case CHIP_HAWAII:
115 		fw_name = FIRMWARE_HAWAII;
116 		break;
117 	case CHIP_MULLINS:
118 		fw_name = FIRMWARE_MULLINS;
119 		break;
120 #endif
121 	case CHIP_TONGA:
122 		fw_name = FIRMWARE_TONGA;
123 		break;
124 	case CHIP_CARRIZO:
125 		fw_name = FIRMWARE_CARRIZO;
126 		break;
127 	case CHIP_FIJI:
128 		fw_name = FIRMWARE_FIJI;
129 		break;
130 	case CHIP_STONEY:
131 		fw_name = FIRMWARE_STONEY;
132 		break;
133 	case CHIP_POLARIS10:
134 		fw_name = FIRMWARE_POLARIS10;
135 		break;
136 	case CHIP_POLARIS11:
137 		fw_name = FIRMWARE_POLARIS11;
138 		break;
139 	case CHIP_POLARIS12:
140 		fw_name = FIRMWARE_POLARIS12;
141 		break;
142 	case CHIP_VEGAM:
143 		fw_name = FIRMWARE_VEGAM;
144 		break;
145 	case CHIP_VEGA10:
146 		fw_name = FIRMWARE_VEGA10;
147 		break;
148 	case CHIP_VEGA12:
149 		fw_name = FIRMWARE_VEGA12;
150 		break;
151 	case CHIP_VEGA20:
152 		fw_name = FIRMWARE_VEGA20;
153 		break;
154 
155 	default:
156 		return -EINVAL;
157 	}
158 
159 	r = request_firmware(&adev->vce.fw, fw_name, adev->dev);
160 	if (r) {
161 		dev_err(adev->dev, "amdgpu_vce: Can't load firmware \"%s\"\n",
162 			fw_name);
163 		return r;
164 	}
165 
166 	r = amdgpu_ucode_validate(adev->vce.fw);
167 	if (r) {
168 		dev_err(adev->dev, "amdgpu_vce: Can't validate firmware \"%s\"\n",
169 			fw_name);
170 		release_firmware(adev->vce.fw);
171 		adev->vce.fw = NULL;
172 		return r;
173 	}
174 
175 	hdr = (const struct common_firmware_header *)adev->vce.fw->data;
176 
177 	ucode_version = le32_to_cpu(hdr->ucode_version);
178 	version_major = (ucode_version >> 20) & 0xfff;
179 	version_minor = (ucode_version >> 8) & 0xfff;
180 	binary_id = ucode_version & 0xff;
181 	DRM_INFO("Found VCE firmware Version: %hhd.%hhd Binary ID: %hhd\n",
182 		version_major, version_minor, binary_id);
183 	adev->vce.fw_version = ((version_major << 24) | (version_minor << 16) |
184 				(binary_id << 8));
185 
186 	r = amdgpu_bo_create_kernel(adev, size, PAGE_SIZE,
187 				    AMDGPU_GEM_DOMAIN_VRAM, &adev->vce.vcpu_bo,
188 				    &adev->vce.gpu_addr, &adev->vce.cpu_addr);
189 	if (r) {
190 		dev_err(adev->dev, "(%d) failed to allocate VCE bo\n", r);
191 		return r;
192 	}
193 
194 	for (i = 0; i < AMDGPU_MAX_VCE_HANDLES; ++i) {
195 		atomic_set(&adev->vce.handles[i], 0);
196 		adev->vce.filp[i] = NULL;
197 	}
198 
199 	INIT_DELAYED_WORK(&adev->vce.idle_work, amdgpu_vce_idle_work_handler);
200 	mutex_init(&adev->vce.idle_mutex);
201 
202 	return 0;
203 }
204 
205 /**
206  * amdgpu_vce_fini - free memory
207  *
208  * @adev: amdgpu_device pointer
209  *
210  * Last step on VCE teardown, free firmware memory
211  */
212 int amdgpu_vce_sw_fini(struct amdgpu_device *adev)
213 {
214 	unsigned i;
215 
216 	if (adev->vce.vcpu_bo == NULL)
217 		return 0;
218 
219 	drm_sched_entity_destroy(&adev->vce.entity);
220 
221 	amdgpu_bo_free_kernel(&adev->vce.vcpu_bo, &adev->vce.gpu_addr,
222 		(void **)&adev->vce.cpu_addr);
223 
224 	for (i = 0; i < adev->vce.num_rings; i++)
225 		amdgpu_ring_fini(&adev->vce.ring[i]);
226 
227 	release_firmware(adev->vce.fw);
228 	mutex_destroy(&adev->vce.idle_mutex);
229 
230 	return 0;
231 }
232 
233 /**
234  * amdgpu_vce_entity_init - init entity
235  *
236  * @adev: amdgpu_device pointer
237  *
238  */
239 int amdgpu_vce_entity_init(struct amdgpu_device *adev)
240 {
241 	struct amdgpu_ring *ring;
242 	struct drm_sched_rq *rq;
243 	int r;
244 
245 	ring = &adev->vce.ring[0];
246 	rq = &ring->sched.sched_rq[DRM_SCHED_PRIORITY_NORMAL];
247 	r = drm_sched_entity_init(&adev->vce.entity, &rq, 1, NULL);
248 	if (r != 0) {
249 		DRM_ERROR("Failed setting up VCE run queue.\n");
250 		return r;
251 	}
252 
253 	return 0;
254 }
255 
256 /**
257  * amdgpu_vce_suspend - unpin VCE fw memory
258  *
259  * @adev: amdgpu_device pointer
260  *
261  */
262 int amdgpu_vce_suspend(struct amdgpu_device *adev)
263 {
264 	int i;
265 
266 	cancel_delayed_work_sync(&adev->vce.idle_work);
267 
268 	if (adev->vce.vcpu_bo == NULL)
269 		return 0;
270 
271 	for (i = 0; i < AMDGPU_MAX_VCE_HANDLES; ++i)
272 		if (atomic_read(&adev->vce.handles[i]))
273 			break;
274 
275 	if (i == AMDGPU_MAX_VCE_HANDLES)
276 		return 0;
277 
278 	/* TODO: suspending running encoding sessions isn't supported */
279 	return -EINVAL;
280 }
281 
282 /**
283  * amdgpu_vce_resume - pin VCE fw memory
284  *
285  * @adev: amdgpu_device pointer
286  *
287  */
288 int amdgpu_vce_resume(struct amdgpu_device *adev)
289 {
290 	void *cpu_addr;
291 	const struct common_firmware_header *hdr;
292 	unsigned offset;
293 	int r;
294 
295 	if (adev->vce.vcpu_bo == NULL)
296 		return -EINVAL;
297 
298 	r = amdgpu_bo_reserve(adev->vce.vcpu_bo, false);
299 	if (r) {
300 		dev_err(adev->dev, "(%d) failed to reserve VCE bo\n", r);
301 		return r;
302 	}
303 
304 	r = amdgpu_bo_kmap(adev->vce.vcpu_bo, &cpu_addr);
305 	if (r) {
306 		amdgpu_bo_unreserve(adev->vce.vcpu_bo);
307 		dev_err(adev->dev, "(%d) VCE map failed\n", r);
308 		return r;
309 	}
310 
311 	hdr = (const struct common_firmware_header *)adev->vce.fw->data;
312 	offset = le32_to_cpu(hdr->ucode_array_offset_bytes);
313 	memcpy_toio(cpu_addr, adev->vce.fw->data + offset,
314 		    adev->vce.fw->size - offset);
315 
316 	amdgpu_bo_kunmap(adev->vce.vcpu_bo);
317 
318 	amdgpu_bo_unreserve(adev->vce.vcpu_bo);
319 
320 	return 0;
321 }
322 
323 /**
324  * amdgpu_vce_idle_work_handler - power off VCE
325  *
326  * @work: pointer to work structure
327  *
328  * power of VCE when it's not used any more
329  */
330 static void amdgpu_vce_idle_work_handler(struct work_struct *work)
331 {
332 	struct amdgpu_device *adev =
333 		container_of(work, struct amdgpu_device, vce.idle_work.work);
334 	unsigned i, count = 0;
335 
336 	for (i = 0; i < adev->vce.num_rings; i++)
337 		count += amdgpu_fence_count_emitted(&adev->vce.ring[i]);
338 
339 	if (count == 0) {
340 		if (adev->pm.dpm_enabled) {
341 			amdgpu_dpm_enable_vce(adev, false);
342 		} else {
343 			amdgpu_asic_set_vce_clocks(adev, 0, 0);
344 			amdgpu_device_ip_set_powergating_state(adev, AMD_IP_BLOCK_TYPE_VCE,
345 							       AMD_PG_STATE_GATE);
346 			amdgpu_device_ip_set_clockgating_state(adev, AMD_IP_BLOCK_TYPE_VCE,
347 							       AMD_CG_STATE_GATE);
348 		}
349 	} else {
350 		schedule_delayed_work(&adev->vce.idle_work, VCE_IDLE_TIMEOUT);
351 	}
352 }
353 
354 /**
355  * amdgpu_vce_ring_begin_use - power up VCE
356  *
357  * @ring: amdgpu ring
358  *
359  * Make sure VCE is powerd up when we want to use it
360  */
361 void amdgpu_vce_ring_begin_use(struct amdgpu_ring *ring)
362 {
363 	struct amdgpu_device *adev = ring->adev;
364 	bool set_clocks;
365 
366 	if (amdgpu_sriov_vf(adev))
367 		return;
368 
369 	mutex_lock(&adev->vce.idle_mutex);
370 	set_clocks = !cancel_delayed_work_sync(&adev->vce.idle_work);
371 	if (set_clocks) {
372 		if (adev->pm.dpm_enabled) {
373 			amdgpu_dpm_enable_vce(adev, true);
374 		} else {
375 			amdgpu_asic_set_vce_clocks(adev, 53300, 40000);
376 			amdgpu_device_ip_set_clockgating_state(adev, AMD_IP_BLOCK_TYPE_VCE,
377 							       AMD_CG_STATE_UNGATE);
378 			amdgpu_device_ip_set_powergating_state(adev, AMD_IP_BLOCK_TYPE_VCE,
379 							       AMD_PG_STATE_UNGATE);
380 
381 		}
382 	}
383 	mutex_unlock(&adev->vce.idle_mutex);
384 }
385 
386 /**
387  * amdgpu_vce_ring_end_use - power VCE down
388  *
389  * @ring: amdgpu ring
390  *
391  * Schedule work to power VCE down again
392  */
393 void amdgpu_vce_ring_end_use(struct amdgpu_ring *ring)
394 {
395 	if (!amdgpu_sriov_vf(ring->adev))
396 		schedule_delayed_work(&ring->adev->vce.idle_work, VCE_IDLE_TIMEOUT);
397 }
398 
399 /**
400  * amdgpu_vce_free_handles - free still open VCE handles
401  *
402  * @adev: amdgpu_device pointer
403  * @filp: drm file pointer
404  *
405  * Close all VCE handles still open by this file pointer
406  */
407 void amdgpu_vce_free_handles(struct amdgpu_device *adev, struct drm_file *filp)
408 {
409 	struct amdgpu_ring *ring = &adev->vce.ring[0];
410 	int i, r;
411 	for (i = 0; i < AMDGPU_MAX_VCE_HANDLES; ++i) {
412 		uint32_t handle = atomic_read(&adev->vce.handles[i]);
413 
414 		if (!handle || adev->vce.filp[i] != filp)
415 			continue;
416 
417 		r = amdgpu_vce_get_destroy_msg(ring, handle, false, NULL);
418 		if (r)
419 			DRM_ERROR("Error destroying VCE handle (%d)!\n", r);
420 
421 		adev->vce.filp[i] = NULL;
422 		atomic_set(&adev->vce.handles[i], 0);
423 	}
424 }
425 
426 /**
427  * amdgpu_vce_get_create_msg - generate a VCE create msg
428  *
429  * @adev: amdgpu_device pointer
430  * @ring: ring we should submit the msg to
431  * @handle: VCE session handle to use
432  * @fence: optional fence to return
433  *
434  * Open up a stream for HW test
435  */
436 static int amdgpu_vce_get_create_msg(struct amdgpu_ring *ring, uint32_t handle,
437 				     struct amdgpu_bo *bo,
438 				     struct dma_fence **fence)
439 {
440 	const unsigned ib_size_dw = 1024;
441 	struct amdgpu_job *job;
442 	struct amdgpu_ib *ib;
443 	struct dma_fence *f = NULL;
444 	uint64_t addr;
445 	int i, r;
446 
447 	r = amdgpu_job_alloc_with_ib(ring->adev, ib_size_dw * 4, &job);
448 	if (r)
449 		return r;
450 
451 	ib = &job->ibs[0];
452 
453 	addr = amdgpu_bo_gpu_offset(bo);
454 
455 	/* stitch together an VCE create msg */
456 	ib->length_dw = 0;
457 	ib->ptr[ib->length_dw++] = 0x0000000c; /* len */
458 	ib->ptr[ib->length_dw++] = 0x00000001; /* session cmd */
459 	ib->ptr[ib->length_dw++] = handle;
460 
461 	if ((ring->adev->vce.fw_version >> 24) >= 52)
462 		ib->ptr[ib->length_dw++] = 0x00000040; /* len */
463 	else
464 		ib->ptr[ib->length_dw++] = 0x00000030; /* len */
465 	ib->ptr[ib->length_dw++] = 0x01000001; /* create cmd */
466 	ib->ptr[ib->length_dw++] = 0x00000000;
467 	ib->ptr[ib->length_dw++] = 0x00000042;
468 	ib->ptr[ib->length_dw++] = 0x0000000a;
469 	ib->ptr[ib->length_dw++] = 0x00000001;
470 	ib->ptr[ib->length_dw++] = 0x00000080;
471 	ib->ptr[ib->length_dw++] = 0x00000060;
472 	ib->ptr[ib->length_dw++] = 0x00000100;
473 	ib->ptr[ib->length_dw++] = 0x00000100;
474 	ib->ptr[ib->length_dw++] = 0x0000000c;
475 	ib->ptr[ib->length_dw++] = 0x00000000;
476 	if ((ring->adev->vce.fw_version >> 24) >= 52) {
477 		ib->ptr[ib->length_dw++] = 0x00000000;
478 		ib->ptr[ib->length_dw++] = 0x00000000;
479 		ib->ptr[ib->length_dw++] = 0x00000000;
480 		ib->ptr[ib->length_dw++] = 0x00000000;
481 	}
482 
483 	ib->ptr[ib->length_dw++] = 0x00000014; /* len */
484 	ib->ptr[ib->length_dw++] = 0x05000005; /* feedback buffer */
485 	ib->ptr[ib->length_dw++] = upper_32_bits(addr);
486 	ib->ptr[ib->length_dw++] = addr;
487 	ib->ptr[ib->length_dw++] = 0x00000001;
488 
489 	for (i = ib->length_dw; i < ib_size_dw; ++i)
490 		ib->ptr[i] = 0x0;
491 
492 	r = amdgpu_job_submit_direct(job, ring, &f);
493 	if (r)
494 		goto err;
495 
496 	if (fence)
497 		*fence = dma_fence_get(f);
498 	dma_fence_put(f);
499 	return 0;
500 
501 err:
502 	amdgpu_job_free(job);
503 	return r;
504 }
505 
506 /**
507  * amdgpu_vce_get_destroy_msg - generate a VCE destroy msg
508  *
509  * @adev: amdgpu_device pointer
510  * @ring: ring we should submit the msg to
511  * @handle: VCE session handle to use
512  * @fence: optional fence to return
513  *
514  * Close up a stream for HW test or if userspace failed to do so
515  */
516 static int amdgpu_vce_get_destroy_msg(struct amdgpu_ring *ring, uint32_t handle,
517 				      bool direct, struct dma_fence **fence)
518 {
519 	const unsigned ib_size_dw = 1024;
520 	struct amdgpu_job *job;
521 	struct amdgpu_ib *ib;
522 	struct dma_fence *f = NULL;
523 	int i, r;
524 
525 	r = amdgpu_job_alloc_with_ib(ring->adev, ib_size_dw * 4, &job);
526 	if (r)
527 		return r;
528 
529 	ib = &job->ibs[0];
530 
531 	/* stitch together an VCE destroy msg */
532 	ib->length_dw = 0;
533 	ib->ptr[ib->length_dw++] = 0x0000000c; /* len */
534 	ib->ptr[ib->length_dw++] = 0x00000001; /* session cmd */
535 	ib->ptr[ib->length_dw++] = handle;
536 
537 	ib->ptr[ib->length_dw++] = 0x00000020; /* len */
538 	ib->ptr[ib->length_dw++] = 0x00000002; /* task info */
539 	ib->ptr[ib->length_dw++] = 0xffffffff; /* next task info, set to 0xffffffff if no */
540 	ib->ptr[ib->length_dw++] = 0x00000001; /* destroy session */
541 	ib->ptr[ib->length_dw++] = 0x00000000;
542 	ib->ptr[ib->length_dw++] = 0x00000000;
543 	ib->ptr[ib->length_dw++] = 0xffffffff; /* feedback is not needed, set to 0xffffffff and firmware will not output feedback */
544 	ib->ptr[ib->length_dw++] = 0x00000000;
545 
546 	ib->ptr[ib->length_dw++] = 0x00000008; /* len */
547 	ib->ptr[ib->length_dw++] = 0x02000001; /* destroy cmd */
548 
549 	for (i = ib->length_dw; i < ib_size_dw; ++i)
550 		ib->ptr[i] = 0x0;
551 
552 	if (direct)
553 		r = amdgpu_job_submit_direct(job, ring, &f);
554 	else
555 		r = amdgpu_job_submit(job, &ring->adev->vce.entity,
556 				      AMDGPU_FENCE_OWNER_UNDEFINED, &f);
557 	if (r)
558 		goto err;
559 
560 	if (fence)
561 		*fence = dma_fence_get(f);
562 	dma_fence_put(f);
563 	return 0;
564 
565 err:
566 	amdgpu_job_free(job);
567 	return r;
568 }
569 
570 /**
571  * amdgpu_vce_cs_validate_bo - make sure not to cross 4GB boundary
572  *
573  * @p: parser context
574  * @lo: address of lower dword
575  * @hi: address of higher dword
576  * @size: minimum size
577  * @index: bs/fb index
578  *
579  * Make sure that no BO cross a 4GB boundary.
580  */
581 static int amdgpu_vce_validate_bo(struct amdgpu_cs_parser *p, uint32_t ib_idx,
582 				  int lo, int hi, unsigned size, int32_t index)
583 {
584 	int64_t offset = ((uint64_t)size) * ((int64_t)index);
585 	struct ttm_operation_ctx ctx = { false, false };
586 	struct amdgpu_bo_va_mapping *mapping;
587 	unsigned i, fpfn, lpfn;
588 	struct amdgpu_bo *bo;
589 	uint64_t addr;
590 	int r;
591 
592 	addr = ((uint64_t)amdgpu_get_ib_value(p, ib_idx, lo)) |
593 	       ((uint64_t)amdgpu_get_ib_value(p, ib_idx, hi)) << 32;
594 	if (index >= 0) {
595 		addr += offset;
596 		fpfn = PAGE_ALIGN(offset) >> PAGE_SHIFT;
597 		lpfn = 0x100000000ULL >> PAGE_SHIFT;
598 	} else {
599 		fpfn = 0;
600 		lpfn = (0x100000000ULL - PAGE_ALIGN(offset)) >> PAGE_SHIFT;
601 	}
602 
603 	r = amdgpu_cs_find_mapping(p, addr, &bo, &mapping);
604 	if (r) {
605 		DRM_ERROR("Can't find BO for addr 0x%010Lx %d %d %d %d\n",
606 			  addr, lo, hi, size, index);
607 		return r;
608 	}
609 
610 	for (i = 0; i < bo->placement.num_placement; ++i) {
611 		bo->placements[i].fpfn = max(bo->placements[i].fpfn, fpfn);
612 		bo->placements[i].lpfn = bo->placements[i].lpfn ?
613 			min(bo->placements[i].lpfn, lpfn) : lpfn;
614 	}
615 	return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
616 }
617 
618 
619 /**
620  * amdgpu_vce_cs_reloc - command submission relocation
621  *
622  * @p: parser context
623  * @lo: address of lower dword
624  * @hi: address of higher dword
625  * @size: minimum size
626  *
627  * Patch relocation inside command stream with real buffer address
628  */
629 static int amdgpu_vce_cs_reloc(struct amdgpu_cs_parser *p, uint32_t ib_idx,
630 			       int lo, int hi, unsigned size, uint32_t index)
631 {
632 	struct amdgpu_bo_va_mapping *mapping;
633 	struct amdgpu_bo *bo;
634 	uint64_t addr;
635 	int r;
636 
637 	if (index == 0xffffffff)
638 		index = 0;
639 
640 	addr = ((uint64_t)amdgpu_get_ib_value(p, ib_idx, lo)) |
641 	       ((uint64_t)amdgpu_get_ib_value(p, ib_idx, hi)) << 32;
642 	addr += ((uint64_t)size) * ((uint64_t)index);
643 
644 	r = amdgpu_cs_find_mapping(p, addr, &bo, &mapping);
645 	if (r) {
646 		DRM_ERROR("Can't find BO for addr 0x%010Lx %d %d %d %d\n",
647 			  addr, lo, hi, size, index);
648 		return r;
649 	}
650 
651 	if ((addr + (uint64_t)size) >
652 	    (mapping->last + 1) * AMDGPU_GPU_PAGE_SIZE) {
653 		DRM_ERROR("BO to small for addr 0x%010Lx %d %d\n",
654 			  addr, lo, hi);
655 		return -EINVAL;
656 	}
657 
658 	addr -= mapping->start * AMDGPU_GPU_PAGE_SIZE;
659 	addr += amdgpu_bo_gpu_offset(bo);
660 	addr -= ((uint64_t)size) * ((uint64_t)index);
661 
662 	amdgpu_set_ib_value(p, ib_idx, lo, lower_32_bits(addr));
663 	amdgpu_set_ib_value(p, ib_idx, hi, upper_32_bits(addr));
664 
665 	return 0;
666 }
667 
668 /**
669  * amdgpu_vce_validate_handle - validate stream handle
670  *
671  * @p: parser context
672  * @handle: handle to validate
673  * @allocated: allocated a new handle?
674  *
675  * Validates the handle and return the found session index or -EINVAL
676  * we we don't have another free session index.
677  */
678 static int amdgpu_vce_validate_handle(struct amdgpu_cs_parser *p,
679 				      uint32_t handle, uint32_t *allocated)
680 {
681 	unsigned i;
682 
683 	/* validate the handle */
684 	for (i = 0; i < AMDGPU_MAX_VCE_HANDLES; ++i) {
685 		if (atomic_read(&p->adev->vce.handles[i]) == handle) {
686 			if (p->adev->vce.filp[i] != p->filp) {
687 				DRM_ERROR("VCE handle collision detected!\n");
688 				return -EINVAL;
689 			}
690 			return i;
691 		}
692 	}
693 
694 	/* handle not found try to alloc a new one */
695 	for (i = 0; i < AMDGPU_MAX_VCE_HANDLES; ++i) {
696 		if (!atomic_cmpxchg(&p->adev->vce.handles[i], 0, handle)) {
697 			p->adev->vce.filp[i] = p->filp;
698 			p->adev->vce.img_size[i] = 0;
699 			*allocated |= 1 << i;
700 			return i;
701 		}
702 	}
703 
704 	DRM_ERROR("No more free VCE handles!\n");
705 	return -EINVAL;
706 }
707 
708 /**
709  * amdgpu_vce_cs_parse - parse and validate the command stream
710  *
711  * @p: parser context
712  *
713  */
714 int amdgpu_vce_ring_parse_cs(struct amdgpu_cs_parser *p, uint32_t ib_idx)
715 {
716 	struct amdgpu_ib *ib = &p->job->ibs[ib_idx];
717 	unsigned fb_idx = 0, bs_idx = 0;
718 	int session_idx = -1;
719 	uint32_t destroyed = 0;
720 	uint32_t created = 0;
721 	uint32_t allocated = 0;
722 	uint32_t tmp, handle = 0;
723 	uint32_t *size = &tmp;
724 	unsigned idx;
725 	int i, r = 0;
726 
727 	p->job->vm = NULL;
728 	ib->gpu_addr = amdgpu_sa_bo_gpu_addr(ib->sa_bo);
729 
730 	for (idx = 0; idx < ib->length_dw;) {
731 		uint32_t len = amdgpu_get_ib_value(p, ib_idx, idx);
732 		uint32_t cmd = amdgpu_get_ib_value(p, ib_idx, idx + 1);
733 
734 		if ((len < 8) || (len & 3)) {
735 			DRM_ERROR("invalid VCE command length (%d)!\n", len);
736 			r = -EINVAL;
737 			goto out;
738 		}
739 
740 		switch (cmd) {
741 		case 0x00000002: /* task info */
742 			fb_idx = amdgpu_get_ib_value(p, ib_idx, idx + 6);
743 			bs_idx = amdgpu_get_ib_value(p, ib_idx, idx + 7);
744 			break;
745 
746 		case 0x03000001: /* encode */
747 			r = amdgpu_vce_validate_bo(p, ib_idx, idx + 10,
748 						   idx + 9, 0, 0);
749 			if (r)
750 				goto out;
751 
752 			r = amdgpu_vce_validate_bo(p, ib_idx, idx + 12,
753 						   idx + 11, 0, 0);
754 			if (r)
755 				goto out;
756 			break;
757 
758 		case 0x05000001: /* context buffer */
759 			r = amdgpu_vce_validate_bo(p, ib_idx, idx + 3,
760 						   idx + 2, 0, 0);
761 			if (r)
762 				goto out;
763 			break;
764 
765 		case 0x05000004: /* video bitstream buffer */
766 			tmp = amdgpu_get_ib_value(p, ib_idx, idx + 4);
767 			r = amdgpu_vce_validate_bo(p, ib_idx, idx + 3, idx + 2,
768 						   tmp, bs_idx);
769 			if (r)
770 				goto out;
771 			break;
772 
773 		case 0x05000005: /* feedback buffer */
774 			r = amdgpu_vce_validate_bo(p, ib_idx, idx + 3, idx + 2,
775 						   4096, fb_idx);
776 			if (r)
777 				goto out;
778 			break;
779 
780 		case 0x0500000d: /* MV buffer */
781 			r = amdgpu_vce_validate_bo(p, ib_idx, idx + 3,
782 							idx + 2, 0, 0);
783 			if (r)
784 				goto out;
785 
786 			r = amdgpu_vce_validate_bo(p, ib_idx, idx + 8,
787 							idx + 7, 0, 0);
788 			if (r)
789 				goto out;
790 			break;
791 		}
792 
793 		idx += len / 4;
794 	}
795 
796 	for (idx = 0; idx < ib->length_dw;) {
797 		uint32_t len = amdgpu_get_ib_value(p, ib_idx, idx);
798 		uint32_t cmd = amdgpu_get_ib_value(p, ib_idx, idx + 1);
799 
800 		switch (cmd) {
801 		case 0x00000001: /* session */
802 			handle = amdgpu_get_ib_value(p, ib_idx, idx + 2);
803 			session_idx = amdgpu_vce_validate_handle(p, handle,
804 								 &allocated);
805 			if (session_idx < 0) {
806 				r = session_idx;
807 				goto out;
808 			}
809 			size = &p->adev->vce.img_size[session_idx];
810 			break;
811 
812 		case 0x00000002: /* task info */
813 			fb_idx = amdgpu_get_ib_value(p, ib_idx, idx + 6);
814 			bs_idx = amdgpu_get_ib_value(p, ib_idx, idx + 7);
815 			break;
816 
817 		case 0x01000001: /* create */
818 			created |= 1 << session_idx;
819 			if (destroyed & (1 << session_idx)) {
820 				destroyed &= ~(1 << session_idx);
821 				allocated |= 1 << session_idx;
822 
823 			} else if (!(allocated & (1 << session_idx))) {
824 				DRM_ERROR("Handle already in use!\n");
825 				r = -EINVAL;
826 				goto out;
827 			}
828 
829 			*size = amdgpu_get_ib_value(p, ib_idx, idx + 8) *
830 				amdgpu_get_ib_value(p, ib_idx, idx + 10) *
831 				8 * 3 / 2;
832 			break;
833 
834 		case 0x04000001: /* config extension */
835 		case 0x04000002: /* pic control */
836 		case 0x04000005: /* rate control */
837 		case 0x04000007: /* motion estimation */
838 		case 0x04000008: /* rdo */
839 		case 0x04000009: /* vui */
840 		case 0x05000002: /* auxiliary buffer */
841 		case 0x05000009: /* clock table */
842 			break;
843 
844 		case 0x0500000c: /* hw config */
845 			switch (p->adev->asic_type) {
846 #ifdef CONFIG_DRM_AMDGPU_CIK
847 			case CHIP_KAVERI:
848 			case CHIP_MULLINS:
849 #endif
850 			case CHIP_CARRIZO:
851 				break;
852 			default:
853 				r = -EINVAL;
854 				goto out;
855 			}
856 			break;
857 
858 		case 0x03000001: /* encode */
859 			r = amdgpu_vce_cs_reloc(p, ib_idx, idx + 10, idx + 9,
860 						*size, 0);
861 			if (r)
862 				goto out;
863 
864 			r = amdgpu_vce_cs_reloc(p, ib_idx, idx + 12, idx + 11,
865 						*size / 3, 0);
866 			if (r)
867 				goto out;
868 			break;
869 
870 		case 0x02000001: /* destroy */
871 			destroyed |= 1 << session_idx;
872 			break;
873 
874 		case 0x05000001: /* context buffer */
875 			r = amdgpu_vce_cs_reloc(p, ib_idx, idx + 3, idx + 2,
876 						*size * 2, 0);
877 			if (r)
878 				goto out;
879 			break;
880 
881 		case 0x05000004: /* video bitstream buffer */
882 			tmp = amdgpu_get_ib_value(p, ib_idx, idx + 4);
883 			r = amdgpu_vce_cs_reloc(p, ib_idx, idx + 3, idx + 2,
884 						tmp, bs_idx);
885 			if (r)
886 				goto out;
887 			break;
888 
889 		case 0x05000005: /* feedback buffer */
890 			r = amdgpu_vce_cs_reloc(p, ib_idx, idx + 3, idx + 2,
891 						4096, fb_idx);
892 			if (r)
893 				goto out;
894 			break;
895 
896 		case 0x0500000d: /* MV buffer */
897 			r = amdgpu_vce_cs_reloc(p, ib_idx, idx + 3,
898 							idx + 2, *size, 0);
899 			if (r)
900 				goto out;
901 
902 			r = amdgpu_vce_cs_reloc(p, ib_idx, idx + 8,
903 							idx + 7, *size / 12, 0);
904 			if (r)
905 				goto out;
906 			break;
907 
908 		default:
909 			DRM_ERROR("invalid VCE command (0x%x)!\n", cmd);
910 			r = -EINVAL;
911 			goto out;
912 		}
913 
914 		if (session_idx == -1) {
915 			DRM_ERROR("no session command at start of IB\n");
916 			r = -EINVAL;
917 			goto out;
918 		}
919 
920 		idx += len / 4;
921 	}
922 
923 	if (allocated & ~created) {
924 		DRM_ERROR("New session without create command!\n");
925 		r = -ENOENT;
926 	}
927 
928 out:
929 	if (!r) {
930 		/* No error, free all destroyed handle slots */
931 		tmp = destroyed;
932 	} else {
933 		/* Error during parsing, free all allocated handle slots */
934 		tmp = allocated;
935 	}
936 
937 	for (i = 0; i < AMDGPU_MAX_VCE_HANDLES; ++i)
938 		if (tmp & (1 << i))
939 			atomic_set(&p->adev->vce.handles[i], 0);
940 
941 	return r;
942 }
943 
944 /**
945  * amdgpu_vce_cs_parse_vm - parse the command stream in VM mode
946  *
947  * @p: parser context
948  *
949  */
950 int amdgpu_vce_ring_parse_cs_vm(struct amdgpu_cs_parser *p, uint32_t ib_idx)
951 {
952 	struct amdgpu_ib *ib = &p->job->ibs[ib_idx];
953 	int session_idx = -1;
954 	uint32_t destroyed = 0;
955 	uint32_t created = 0;
956 	uint32_t allocated = 0;
957 	uint32_t tmp, handle = 0;
958 	int i, r = 0, idx = 0;
959 
960 	while (idx < ib->length_dw) {
961 		uint32_t len = amdgpu_get_ib_value(p, ib_idx, idx);
962 		uint32_t cmd = amdgpu_get_ib_value(p, ib_idx, idx + 1);
963 
964 		if ((len < 8) || (len & 3)) {
965 			DRM_ERROR("invalid VCE command length (%d)!\n", len);
966 			r = -EINVAL;
967 			goto out;
968 		}
969 
970 		switch (cmd) {
971 		case 0x00000001: /* session */
972 			handle = amdgpu_get_ib_value(p, ib_idx, idx + 2);
973 			session_idx = amdgpu_vce_validate_handle(p, handle,
974 								 &allocated);
975 			if (session_idx < 0) {
976 				r = session_idx;
977 				goto out;
978 			}
979 			break;
980 
981 		case 0x01000001: /* create */
982 			created |= 1 << session_idx;
983 			if (destroyed & (1 << session_idx)) {
984 				destroyed &= ~(1 << session_idx);
985 				allocated |= 1 << session_idx;
986 
987 			} else if (!(allocated & (1 << session_idx))) {
988 				DRM_ERROR("Handle already in use!\n");
989 				r = -EINVAL;
990 				goto out;
991 			}
992 
993 			break;
994 
995 		case 0x02000001: /* destroy */
996 			destroyed |= 1 << session_idx;
997 			break;
998 
999 		default:
1000 			break;
1001 		}
1002 
1003 		if (session_idx == -1) {
1004 			DRM_ERROR("no session command at start of IB\n");
1005 			r = -EINVAL;
1006 			goto out;
1007 		}
1008 
1009 		idx += len / 4;
1010 	}
1011 
1012 	if (allocated & ~created) {
1013 		DRM_ERROR("New session without create command!\n");
1014 		r = -ENOENT;
1015 	}
1016 
1017 out:
1018 	if (!r) {
1019 		/* No error, free all destroyed handle slots */
1020 		tmp = destroyed;
1021 		amdgpu_ib_free(p->adev, ib, NULL);
1022 	} else {
1023 		/* Error during parsing, free all allocated handle slots */
1024 		tmp = allocated;
1025 	}
1026 
1027 	for (i = 0; i < AMDGPU_MAX_VCE_HANDLES; ++i)
1028 		if (tmp & (1 << i))
1029 			atomic_set(&p->adev->vce.handles[i], 0);
1030 
1031 	return r;
1032 }
1033 
1034 /**
1035  * amdgpu_vce_ring_emit_ib - execute indirect buffer
1036  *
1037  * @ring: engine to use
1038  * @ib: the IB to execute
1039  *
1040  */
1041 void amdgpu_vce_ring_emit_ib(struct amdgpu_ring *ring,
1042 				struct amdgpu_job *job,
1043 				struct amdgpu_ib *ib,
1044 				uint32_t flags)
1045 {
1046 	amdgpu_ring_write(ring, VCE_CMD_IB);
1047 	amdgpu_ring_write(ring, lower_32_bits(ib->gpu_addr));
1048 	amdgpu_ring_write(ring, upper_32_bits(ib->gpu_addr));
1049 	amdgpu_ring_write(ring, ib->length_dw);
1050 }
1051 
1052 /**
1053  * amdgpu_vce_ring_emit_fence - add a fence command to the ring
1054  *
1055  * @ring: engine to use
1056  * @fence: the fence
1057  *
1058  */
1059 void amdgpu_vce_ring_emit_fence(struct amdgpu_ring *ring, u64 addr, u64 seq,
1060 				unsigned flags)
1061 {
1062 	WARN_ON(flags & AMDGPU_FENCE_FLAG_64BIT);
1063 
1064 	amdgpu_ring_write(ring, VCE_CMD_FENCE);
1065 	amdgpu_ring_write(ring, addr);
1066 	amdgpu_ring_write(ring, upper_32_bits(addr));
1067 	amdgpu_ring_write(ring, seq);
1068 	amdgpu_ring_write(ring, VCE_CMD_TRAP);
1069 	amdgpu_ring_write(ring, VCE_CMD_END);
1070 }
1071 
1072 /**
1073  * amdgpu_vce_ring_test_ring - test if VCE ring is working
1074  *
1075  * @ring: the engine to test on
1076  *
1077  */
1078 int amdgpu_vce_ring_test_ring(struct amdgpu_ring *ring)
1079 {
1080 	struct amdgpu_device *adev = ring->adev;
1081 	uint32_t rptr;
1082 	unsigned i;
1083 	int r, timeout = adev->usec_timeout;
1084 
1085 	/* skip ring test for sriov*/
1086 	if (amdgpu_sriov_vf(adev))
1087 		return 0;
1088 
1089 	r = amdgpu_ring_alloc(ring, 16);
1090 	if (r)
1091 		return r;
1092 
1093 	rptr = amdgpu_ring_get_rptr(ring);
1094 
1095 	amdgpu_ring_write(ring, VCE_CMD_END);
1096 	amdgpu_ring_commit(ring);
1097 
1098 	for (i = 0; i < timeout; i++) {
1099 		if (amdgpu_ring_get_rptr(ring) != rptr)
1100 			break;
1101 		udelay(1);
1102 	}
1103 
1104 	if (i >= timeout)
1105 		r = -ETIMEDOUT;
1106 
1107 	return r;
1108 }
1109 
1110 /**
1111  * amdgpu_vce_ring_test_ib - test if VCE IBs are working
1112  *
1113  * @ring: the engine to test on
1114  *
1115  */
1116 int amdgpu_vce_ring_test_ib(struct amdgpu_ring *ring, long timeout)
1117 {
1118 	struct dma_fence *fence = NULL;
1119 	struct amdgpu_bo *bo = NULL;
1120 	long r;
1121 
1122 	/* skip vce ring1/2 ib test for now, since it's not reliable */
1123 	if (ring != &ring->adev->vce.ring[0])
1124 		return 0;
1125 
1126 	r = amdgpu_bo_create_reserved(ring->adev, 512, PAGE_SIZE,
1127 				      AMDGPU_GEM_DOMAIN_VRAM,
1128 				      &bo, NULL, NULL);
1129 	if (r)
1130 		return r;
1131 
1132 	r = amdgpu_vce_get_create_msg(ring, 1, bo, NULL);
1133 	if (r)
1134 		goto error;
1135 
1136 	r = amdgpu_vce_get_destroy_msg(ring, 1, true, &fence);
1137 	if (r)
1138 		goto error;
1139 
1140 	r = dma_fence_wait_timeout(fence, false, timeout);
1141 	if (r == 0)
1142 		r = -ETIMEDOUT;
1143 	else if (r > 0)
1144 		r = 0;
1145 
1146 error:
1147 	dma_fence_put(fence);
1148 	amdgpu_bo_unreserve(bo);
1149 	amdgpu_bo_unref(&bo);
1150 	return r;
1151 }
1152