1 /*
2  * Copyright 2011 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  */
26 /*
27  * Authors:
28  *    Christian König <deathsimple@vodafone.de>
29  */
30 
31 #include <linux/firmware.h>
32 #include <linux/module.h>
33 #include <drm/drmP.h>
34 #include <drm/drm.h>
35 
36 #include "amdgpu.h"
37 #include "amdgpu_pm.h"
38 #include "amdgpu_uvd.h"
39 #include "cikd.h"
40 #include "uvd/uvd_4_2_d.h"
41 
42 /* 1 second timeout */
43 #define UVD_IDLE_TIMEOUT	msecs_to_jiffies(1000)
44 
45 /* Firmware versions for VI */
46 #define FW_1_65_10	((1 << 24) | (65 << 16) | (10 << 8))
47 #define FW_1_87_11	((1 << 24) | (87 << 16) | (11 << 8))
48 #define FW_1_87_12	((1 << 24) | (87 << 16) | (12 << 8))
49 #define FW_1_37_15	((1 << 24) | (37 << 16) | (15 << 8))
50 
51 /* Polaris10/11 firmware version */
52 #define FW_1_66_16	((1 << 24) | (66 << 16) | (16 << 8))
53 
54 /* Firmware Names */
55 #ifdef CONFIG_DRM_AMDGPU_CIK
56 #define FIRMWARE_BONAIRE	"radeon/bonaire_uvd.bin"
57 #define FIRMWARE_KABINI	"radeon/kabini_uvd.bin"
58 #define FIRMWARE_KAVERI	"radeon/kaveri_uvd.bin"
59 #define FIRMWARE_HAWAII	"radeon/hawaii_uvd.bin"
60 #define FIRMWARE_MULLINS	"radeon/mullins_uvd.bin"
61 #endif
62 #define FIRMWARE_TONGA		"amdgpu/tonga_uvd.bin"
63 #define FIRMWARE_CARRIZO	"amdgpu/carrizo_uvd.bin"
64 #define FIRMWARE_FIJI		"amdgpu/fiji_uvd.bin"
65 #define FIRMWARE_STONEY		"amdgpu/stoney_uvd.bin"
66 #define FIRMWARE_POLARIS10	"amdgpu/polaris10_uvd.bin"
67 #define FIRMWARE_POLARIS11	"amdgpu/polaris11_uvd.bin"
68 
69 /**
70  * amdgpu_uvd_cs_ctx - Command submission parser context
71  *
72  * Used for emulating virtual memory support on UVD 4.2.
73  */
74 struct amdgpu_uvd_cs_ctx {
75 	struct amdgpu_cs_parser *parser;
76 	unsigned reg, count;
77 	unsigned data0, data1;
78 	unsigned idx;
79 	unsigned ib_idx;
80 
81 	/* does the IB has a msg command */
82 	bool has_msg_cmd;
83 
84 	/* minimum buffer sizes */
85 	unsigned *buf_sizes;
86 };
87 
88 #ifdef CONFIG_DRM_AMDGPU_CIK
89 MODULE_FIRMWARE(FIRMWARE_BONAIRE);
90 MODULE_FIRMWARE(FIRMWARE_KABINI);
91 MODULE_FIRMWARE(FIRMWARE_KAVERI);
92 MODULE_FIRMWARE(FIRMWARE_HAWAII);
93 MODULE_FIRMWARE(FIRMWARE_MULLINS);
94 #endif
95 MODULE_FIRMWARE(FIRMWARE_TONGA);
96 MODULE_FIRMWARE(FIRMWARE_CARRIZO);
97 MODULE_FIRMWARE(FIRMWARE_FIJI);
98 MODULE_FIRMWARE(FIRMWARE_STONEY);
99 MODULE_FIRMWARE(FIRMWARE_POLARIS10);
100 MODULE_FIRMWARE(FIRMWARE_POLARIS11);
101 
102 static void amdgpu_uvd_idle_work_handler(struct work_struct *work);
103 
104 int amdgpu_uvd_sw_init(struct amdgpu_device *adev)
105 {
106 	struct amdgpu_ring *ring;
107 	struct amd_sched_rq *rq;
108 	unsigned long bo_size;
109 	const char *fw_name;
110 	const struct common_firmware_header *hdr;
111 	unsigned version_major, version_minor, family_id;
112 	int i, r;
113 
114 	INIT_DELAYED_WORK(&adev->uvd.idle_work, amdgpu_uvd_idle_work_handler);
115 
116 	switch (adev->asic_type) {
117 #ifdef CONFIG_DRM_AMDGPU_CIK
118 	case CHIP_BONAIRE:
119 		fw_name = FIRMWARE_BONAIRE;
120 		break;
121 	case CHIP_KABINI:
122 		fw_name = FIRMWARE_KABINI;
123 		break;
124 	case CHIP_KAVERI:
125 		fw_name = FIRMWARE_KAVERI;
126 		break;
127 	case CHIP_HAWAII:
128 		fw_name = FIRMWARE_HAWAII;
129 		break;
130 	case CHIP_MULLINS:
131 		fw_name = FIRMWARE_MULLINS;
132 		break;
133 #endif
134 	case CHIP_TONGA:
135 		fw_name = FIRMWARE_TONGA;
136 		break;
137 	case CHIP_FIJI:
138 		fw_name = FIRMWARE_FIJI;
139 		break;
140 	case CHIP_CARRIZO:
141 		fw_name = FIRMWARE_CARRIZO;
142 		break;
143 	case CHIP_STONEY:
144 		fw_name = FIRMWARE_STONEY;
145 		break;
146 	case CHIP_POLARIS10:
147 		fw_name = FIRMWARE_POLARIS10;
148 		break;
149 	case CHIP_POLARIS11:
150 		fw_name = FIRMWARE_POLARIS11;
151 		break;
152 	default:
153 		return -EINVAL;
154 	}
155 
156 	r = request_firmware(&adev->uvd.fw, fw_name, adev->dev);
157 	if (r) {
158 		dev_err(adev->dev, "amdgpu_uvd: Can't load firmware \"%s\"\n",
159 			fw_name);
160 		return r;
161 	}
162 
163 	r = amdgpu_ucode_validate(adev->uvd.fw);
164 	if (r) {
165 		dev_err(adev->dev, "amdgpu_uvd: Can't validate firmware \"%s\"\n",
166 			fw_name);
167 		release_firmware(adev->uvd.fw);
168 		adev->uvd.fw = NULL;
169 		return r;
170 	}
171 
172 	/* Set the default UVD handles that the firmware can handle */
173 	adev->uvd.max_handles = AMDGPU_DEFAULT_UVD_HANDLES;
174 
175 	hdr = (const struct common_firmware_header *)adev->uvd.fw->data;
176 	family_id = le32_to_cpu(hdr->ucode_version) & 0xff;
177 	version_major = (le32_to_cpu(hdr->ucode_version) >> 24) & 0xff;
178 	version_minor = (le32_to_cpu(hdr->ucode_version) >> 8) & 0xff;
179 	DRM_INFO("Found UVD firmware Version: %hu.%hu Family ID: %hu\n",
180 		version_major, version_minor, family_id);
181 
182 	/*
183 	 * Limit the number of UVD handles depending on microcode major
184 	 * and minor versions. The firmware version which has 40 UVD
185 	 * instances support is 1.80. So all subsequent versions should
186 	 * also have the same support.
187 	 */
188 	if ((version_major > 0x01) ||
189 	    ((version_major == 0x01) && (version_minor >= 0x50)))
190 		adev->uvd.max_handles = AMDGPU_MAX_UVD_HANDLES;
191 
192 	adev->uvd.fw_version = ((version_major << 24) | (version_minor << 16) |
193 				(family_id << 8));
194 
195 	if ((adev->asic_type == CHIP_POLARIS10 ||
196 	     adev->asic_type == CHIP_POLARIS11) &&
197 	    (adev->uvd.fw_version < FW_1_66_16))
198 		DRM_ERROR("POLARIS10/11 UVD firmware version %hu.%hu is too old.\n",
199 			  version_major, version_minor);
200 
201 	bo_size = AMDGPU_GPU_PAGE_ALIGN(le32_to_cpu(hdr->ucode_size_bytes) + 8)
202 		  +  AMDGPU_UVD_STACK_SIZE + AMDGPU_UVD_HEAP_SIZE
203 		  +  AMDGPU_UVD_SESSION_SIZE * adev->uvd.max_handles;
204 	r = amdgpu_bo_create(adev, bo_size, PAGE_SIZE, true,
205 			     AMDGPU_GEM_DOMAIN_VRAM,
206 			     AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
207 			     NULL, NULL, &adev->uvd.vcpu_bo);
208 	if (r) {
209 		dev_err(adev->dev, "(%d) failed to allocate UVD bo\n", r);
210 		return r;
211 	}
212 
213 	r = amdgpu_bo_reserve(adev->uvd.vcpu_bo, false);
214 	if (r) {
215 		amdgpu_bo_unref(&adev->uvd.vcpu_bo);
216 		dev_err(adev->dev, "(%d) failed to reserve UVD bo\n", r);
217 		return r;
218 	}
219 
220 	r = amdgpu_bo_pin(adev->uvd.vcpu_bo, AMDGPU_GEM_DOMAIN_VRAM,
221 			  &adev->uvd.gpu_addr);
222 	if (r) {
223 		amdgpu_bo_unreserve(adev->uvd.vcpu_bo);
224 		amdgpu_bo_unref(&adev->uvd.vcpu_bo);
225 		dev_err(adev->dev, "(%d) UVD bo pin failed\n", r);
226 		return r;
227 	}
228 
229 	r = amdgpu_bo_kmap(adev->uvd.vcpu_bo, &adev->uvd.cpu_addr);
230 	if (r) {
231 		dev_err(adev->dev, "(%d) UVD map failed\n", r);
232 		return r;
233 	}
234 
235 	amdgpu_bo_unreserve(adev->uvd.vcpu_bo);
236 
237 	ring = &adev->uvd.ring;
238 	rq = &ring->sched.sched_rq[AMD_SCHED_PRIORITY_NORMAL];
239 	r = amd_sched_entity_init(&ring->sched, &adev->uvd.entity,
240 				  rq, amdgpu_sched_jobs);
241 	if (r != 0) {
242 		DRM_ERROR("Failed setting up UVD run queue.\n");
243 		return r;
244 	}
245 
246 	for (i = 0; i < adev->uvd.max_handles; ++i) {
247 		atomic_set(&adev->uvd.handles[i], 0);
248 		adev->uvd.filp[i] = NULL;
249 	}
250 
251 	/* from uvd v5.0 HW addressing capacity increased to 64 bits */
252 	if (!amdgpu_ip_block_version_cmp(adev, AMD_IP_BLOCK_TYPE_UVD, 5, 0))
253 		adev->uvd.address_64_bit = true;
254 
255 	switch (adev->asic_type) {
256 	case CHIP_TONGA:
257 		adev->uvd.use_ctx_buf = adev->uvd.fw_version >= FW_1_65_10;
258 		break;
259 	case CHIP_CARRIZO:
260 		adev->uvd.use_ctx_buf = adev->uvd.fw_version >= FW_1_87_11;
261 		break;
262 	case CHIP_FIJI:
263 		adev->uvd.use_ctx_buf = adev->uvd.fw_version >= FW_1_87_12;
264 		break;
265 	case CHIP_STONEY:
266 		adev->uvd.use_ctx_buf = adev->uvd.fw_version >= FW_1_37_15;
267 		break;
268 	default:
269 		adev->uvd.use_ctx_buf = adev->asic_type >= CHIP_POLARIS10;
270 	}
271 
272 	return 0;
273 }
274 
275 int amdgpu_uvd_sw_fini(struct amdgpu_device *adev)
276 {
277 	int r;
278 
279 	kfree(adev->uvd.saved_bo);
280 
281 	amd_sched_entity_fini(&adev->uvd.ring.sched, &adev->uvd.entity);
282 
283 	if (adev->uvd.vcpu_bo) {
284 		r = amdgpu_bo_reserve(adev->uvd.vcpu_bo, false);
285 		if (!r) {
286 			amdgpu_bo_kunmap(adev->uvd.vcpu_bo);
287 			amdgpu_bo_unpin(adev->uvd.vcpu_bo);
288 			amdgpu_bo_unreserve(adev->uvd.vcpu_bo);
289 		}
290 
291 		amdgpu_bo_unref(&adev->uvd.vcpu_bo);
292 	}
293 
294 	amdgpu_ring_fini(&adev->uvd.ring);
295 
296 	release_firmware(adev->uvd.fw);
297 
298 	return 0;
299 }
300 
301 int amdgpu_uvd_suspend(struct amdgpu_device *adev)
302 {
303 	unsigned size;
304 	void *ptr;
305 	int i;
306 
307 	if (adev->uvd.vcpu_bo == NULL)
308 		return 0;
309 
310 	for (i = 0; i < adev->uvd.max_handles; ++i)
311 		if (atomic_read(&adev->uvd.handles[i]))
312 			break;
313 
314 	if (i == AMDGPU_MAX_UVD_HANDLES)
315 		return 0;
316 
317 	cancel_delayed_work_sync(&adev->uvd.idle_work);
318 
319 	size = amdgpu_bo_size(adev->uvd.vcpu_bo);
320 	ptr = adev->uvd.cpu_addr;
321 
322 	adev->uvd.saved_bo = kmalloc(size, GFP_KERNEL);
323 	if (!adev->uvd.saved_bo)
324 		return -ENOMEM;
325 
326 	memcpy(adev->uvd.saved_bo, ptr, size);
327 
328 	return 0;
329 }
330 
331 int amdgpu_uvd_resume(struct amdgpu_device *adev)
332 {
333 	unsigned size;
334 	void *ptr;
335 
336 	if (adev->uvd.vcpu_bo == NULL)
337 		return -EINVAL;
338 
339 	size = amdgpu_bo_size(adev->uvd.vcpu_bo);
340 	ptr = adev->uvd.cpu_addr;
341 
342 	if (adev->uvd.saved_bo != NULL) {
343 		memcpy(ptr, adev->uvd.saved_bo, size);
344 		kfree(adev->uvd.saved_bo);
345 		adev->uvd.saved_bo = NULL;
346 	} else {
347 		const struct common_firmware_header *hdr;
348 		unsigned offset;
349 
350 		hdr = (const struct common_firmware_header *)adev->uvd.fw->data;
351 		offset = le32_to_cpu(hdr->ucode_array_offset_bytes);
352 		memcpy(adev->uvd.cpu_addr, (adev->uvd.fw->data) + offset,
353 			(adev->uvd.fw->size) - offset);
354 		size -= le32_to_cpu(hdr->ucode_size_bytes);
355 		ptr += le32_to_cpu(hdr->ucode_size_bytes);
356 		memset(ptr, 0, size);
357 	}
358 
359 	return 0;
360 }
361 
362 void amdgpu_uvd_free_handles(struct amdgpu_device *adev, struct drm_file *filp)
363 {
364 	struct amdgpu_ring *ring = &adev->uvd.ring;
365 	int i, r;
366 
367 	for (i = 0; i < adev->uvd.max_handles; ++i) {
368 		uint32_t handle = atomic_read(&adev->uvd.handles[i]);
369 		if (handle != 0 && adev->uvd.filp[i] == filp) {
370 			struct fence *fence;
371 
372 			r = amdgpu_uvd_get_destroy_msg(ring, handle,
373 						       false, &fence);
374 			if (r) {
375 				DRM_ERROR("Error destroying UVD (%d)!\n", r);
376 				continue;
377 			}
378 
379 			fence_wait(fence, false);
380 			fence_put(fence);
381 
382 			adev->uvd.filp[i] = NULL;
383 			atomic_set(&adev->uvd.handles[i], 0);
384 		}
385 	}
386 }
387 
388 static void amdgpu_uvd_force_into_uvd_segment(struct amdgpu_bo *rbo)
389 {
390 	int i;
391 	for (i = 0; i < rbo->placement.num_placement; ++i) {
392 		rbo->placements[i].fpfn = 0 >> PAGE_SHIFT;
393 		rbo->placements[i].lpfn = (256 * 1024 * 1024) >> PAGE_SHIFT;
394 	}
395 }
396 
397 /**
398  * amdgpu_uvd_cs_pass1 - first parsing round
399  *
400  * @ctx: UVD parser context
401  *
402  * Make sure UVD message and feedback buffers are in VRAM and
403  * nobody is violating an 256MB boundary.
404  */
405 static int amdgpu_uvd_cs_pass1(struct amdgpu_uvd_cs_ctx *ctx)
406 {
407 	struct amdgpu_bo_va_mapping *mapping;
408 	struct amdgpu_bo *bo;
409 	uint32_t cmd, lo, hi;
410 	uint64_t addr;
411 	int r = 0;
412 
413 	lo = amdgpu_get_ib_value(ctx->parser, ctx->ib_idx, ctx->data0);
414 	hi = amdgpu_get_ib_value(ctx->parser, ctx->ib_idx, ctx->data1);
415 	addr = ((uint64_t)lo) | (((uint64_t)hi) << 32);
416 
417 	mapping = amdgpu_cs_find_mapping(ctx->parser, addr, &bo);
418 	if (mapping == NULL) {
419 		DRM_ERROR("Can't find BO for addr 0x%08Lx\n", addr);
420 		return -EINVAL;
421 	}
422 
423 	if (!ctx->parser->adev->uvd.address_64_bit) {
424 		/* check if it's a message or feedback command */
425 		cmd = amdgpu_get_ib_value(ctx->parser, ctx->ib_idx, ctx->idx) >> 1;
426 		if (cmd == 0x0 || cmd == 0x3) {
427 			/* yes, force it into VRAM */
428 			uint32_t domain = AMDGPU_GEM_DOMAIN_VRAM;
429 			amdgpu_ttm_placement_from_domain(bo, domain);
430 		}
431 		amdgpu_uvd_force_into_uvd_segment(bo);
432 
433 		r = ttm_bo_validate(&bo->tbo, &bo->placement, false, false);
434 	}
435 
436 	return r;
437 }
438 
439 /**
440  * amdgpu_uvd_cs_msg_decode - handle UVD decode message
441  *
442  * @msg: pointer to message structure
443  * @buf_sizes: returned buffer sizes
444  *
445  * Peek into the decode message and calculate the necessary buffer sizes.
446  */
447 static int amdgpu_uvd_cs_msg_decode(struct amdgpu_device *adev, uint32_t *msg,
448 	unsigned buf_sizes[])
449 {
450 	unsigned stream_type = msg[4];
451 	unsigned width = msg[6];
452 	unsigned height = msg[7];
453 	unsigned dpb_size = msg[9];
454 	unsigned pitch = msg[28];
455 	unsigned level = msg[57];
456 
457 	unsigned width_in_mb = width / 16;
458 	unsigned height_in_mb = ALIGN(height / 16, 2);
459 	unsigned fs_in_mb = width_in_mb * height_in_mb;
460 
461 	unsigned image_size, tmp, min_dpb_size, num_dpb_buffer;
462 	unsigned min_ctx_size = ~0;
463 
464 	image_size = width * height;
465 	image_size += image_size / 2;
466 	image_size = ALIGN(image_size, 1024);
467 
468 	switch (stream_type) {
469 	case 0: /* H264 */
470 		switch(level) {
471 		case 30:
472 			num_dpb_buffer = 8100 / fs_in_mb;
473 			break;
474 		case 31:
475 			num_dpb_buffer = 18000 / fs_in_mb;
476 			break;
477 		case 32:
478 			num_dpb_buffer = 20480 / fs_in_mb;
479 			break;
480 		case 41:
481 			num_dpb_buffer = 32768 / fs_in_mb;
482 			break;
483 		case 42:
484 			num_dpb_buffer = 34816 / fs_in_mb;
485 			break;
486 		case 50:
487 			num_dpb_buffer = 110400 / fs_in_mb;
488 			break;
489 		case 51:
490 			num_dpb_buffer = 184320 / fs_in_mb;
491 			break;
492 		default:
493 			num_dpb_buffer = 184320 / fs_in_mb;
494 			break;
495 		}
496 		num_dpb_buffer++;
497 		if (num_dpb_buffer > 17)
498 			num_dpb_buffer = 17;
499 
500 		/* reference picture buffer */
501 		min_dpb_size = image_size * num_dpb_buffer;
502 
503 		/* macroblock context buffer */
504 		min_dpb_size += width_in_mb * height_in_mb * num_dpb_buffer * 192;
505 
506 		/* IT surface buffer */
507 		min_dpb_size += width_in_mb * height_in_mb * 32;
508 		break;
509 
510 	case 1: /* VC1 */
511 
512 		/* reference picture buffer */
513 		min_dpb_size = image_size * 3;
514 
515 		/* CONTEXT_BUFFER */
516 		min_dpb_size += width_in_mb * height_in_mb * 128;
517 
518 		/* IT surface buffer */
519 		min_dpb_size += width_in_mb * 64;
520 
521 		/* DB surface buffer */
522 		min_dpb_size += width_in_mb * 128;
523 
524 		/* BP */
525 		tmp = max(width_in_mb, height_in_mb);
526 		min_dpb_size += ALIGN(tmp * 7 * 16, 64);
527 		break;
528 
529 	case 3: /* MPEG2 */
530 
531 		/* reference picture buffer */
532 		min_dpb_size = image_size * 3;
533 		break;
534 
535 	case 4: /* MPEG4 */
536 
537 		/* reference picture buffer */
538 		min_dpb_size = image_size * 3;
539 
540 		/* CM */
541 		min_dpb_size += width_in_mb * height_in_mb * 64;
542 
543 		/* IT surface buffer */
544 		min_dpb_size += ALIGN(width_in_mb * height_in_mb * 32, 64);
545 		break;
546 
547 	case 7: /* H264 Perf */
548 		switch(level) {
549 		case 30:
550 			num_dpb_buffer = 8100 / fs_in_mb;
551 			break;
552 		case 31:
553 			num_dpb_buffer = 18000 / fs_in_mb;
554 			break;
555 		case 32:
556 			num_dpb_buffer = 20480 / fs_in_mb;
557 			break;
558 		case 41:
559 			num_dpb_buffer = 32768 / fs_in_mb;
560 			break;
561 		case 42:
562 			num_dpb_buffer = 34816 / fs_in_mb;
563 			break;
564 		case 50:
565 			num_dpb_buffer = 110400 / fs_in_mb;
566 			break;
567 		case 51:
568 			num_dpb_buffer = 184320 / fs_in_mb;
569 			break;
570 		default:
571 			num_dpb_buffer = 184320 / fs_in_mb;
572 			break;
573 		}
574 		num_dpb_buffer++;
575 		if (num_dpb_buffer > 17)
576 			num_dpb_buffer = 17;
577 
578 		/* reference picture buffer */
579 		min_dpb_size = image_size * num_dpb_buffer;
580 
581 		if (!adev->uvd.use_ctx_buf){
582 			/* macroblock context buffer */
583 			min_dpb_size +=
584 				width_in_mb * height_in_mb * num_dpb_buffer * 192;
585 
586 			/* IT surface buffer */
587 			min_dpb_size += width_in_mb * height_in_mb * 32;
588 		} else {
589 			/* macroblock context buffer */
590 			min_ctx_size =
591 				width_in_mb * height_in_mb * num_dpb_buffer * 192;
592 		}
593 		break;
594 
595 	case 16: /* H265 */
596 		image_size = (ALIGN(width, 16) * ALIGN(height, 16) * 3) / 2;
597 		image_size = ALIGN(image_size, 256);
598 
599 		num_dpb_buffer = (le32_to_cpu(msg[59]) & 0xff) + 2;
600 		min_dpb_size = image_size * num_dpb_buffer;
601 		min_ctx_size = ((width + 255) / 16) * ((height + 255) / 16)
602 					   * 16 * num_dpb_buffer + 52 * 1024;
603 		break;
604 
605 	default:
606 		DRM_ERROR("UVD codec not handled %d!\n", stream_type);
607 		return -EINVAL;
608 	}
609 
610 	if (width > pitch) {
611 		DRM_ERROR("Invalid UVD decoding target pitch!\n");
612 		return -EINVAL;
613 	}
614 
615 	if (dpb_size < min_dpb_size) {
616 		DRM_ERROR("Invalid dpb_size in UVD message (%d / %d)!\n",
617 			  dpb_size, min_dpb_size);
618 		return -EINVAL;
619 	}
620 
621 	buf_sizes[0x1] = dpb_size;
622 	buf_sizes[0x2] = image_size;
623 	buf_sizes[0x4] = min_ctx_size;
624 	return 0;
625 }
626 
627 /**
628  * amdgpu_uvd_cs_msg - handle UVD message
629  *
630  * @ctx: UVD parser context
631  * @bo: buffer object containing the message
632  * @offset: offset into the buffer object
633  *
634  * Peek into the UVD message and extract the session id.
635  * Make sure that we don't open up to many sessions.
636  */
637 static int amdgpu_uvd_cs_msg(struct amdgpu_uvd_cs_ctx *ctx,
638 			     struct amdgpu_bo *bo, unsigned offset)
639 {
640 	struct amdgpu_device *adev = ctx->parser->adev;
641 	int32_t *msg, msg_type, handle;
642 	void *ptr;
643 	long r;
644 	int i;
645 
646 	if (offset & 0x3F) {
647 		DRM_ERROR("UVD messages must be 64 byte aligned!\n");
648 		return -EINVAL;
649 	}
650 
651 	r = amdgpu_bo_kmap(bo, &ptr);
652 	if (r) {
653 		DRM_ERROR("Failed mapping the UVD message (%ld)!\n", r);
654 		return r;
655 	}
656 
657 	msg = ptr + offset;
658 
659 	msg_type = msg[1];
660 	handle = msg[2];
661 
662 	if (handle == 0) {
663 		DRM_ERROR("Invalid UVD handle!\n");
664 		return -EINVAL;
665 	}
666 
667 	switch (msg_type) {
668 	case 0:
669 		/* it's a create msg, calc image size (width * height) */
670 		amdgpu_bo_kunmap(bo);
671 
672 		/* try to alloc a new handle */
673 		for (i = 0; i < adev->uvd.max_handles; ++i) {
674 			if (atomic_read(&adev->uvd.handles[i]) == handle) {
675 				DRM_ERROR("Handle 0x%x already in use!\n", handle);
676 				return -EINVAL;
677 			}
678 
679 			if (!atomic_cmpxchg(&adev->uvd.handles[i], 0, handle)) {
680 				adev->uvd.filp[i] = ctx->parser->filp;
681 				return 0;
682 			}
683 		}
684 
685 		DRM_ERROR("No more free UVD handles!\n");
686 		return -ENOSPC;
687 
688 	case 1:
689 		/* it's a decode msg, calc buffer sizes */
690 		r = amdgpu_uvd_cs_msg_decode(adev, msg, ctx->buf_sizes);
691 		amdgpu_bo_kunmap(bo);
692 		if (r)
693 			return r;
694 
695 		/* validate the handle */
696 		for (i = 0; i < adev->uvd.max_handles; ++i) {
697 			if (atomic_read(&adev->uvd.handles[i]) == handle) {
698 				if (adev->uvd.filp[i] != ctx->parser->filp) {
699 					DRM_ERROR("UVD handle collision detected!\n");
700 					return -EINVAL;
701 				}
702 				return 0;
703 			}
704 		}
705 
706 		DRM_ERROR("Invalid UVD handle 0x%x!\n", handle);
707 		return -ENOENT;
708 
709 	case 2:
710 		/* it's a destroy msg, free the handle */
711 		for (i = 0; i < adev->uvd.max_handles; ++i)
712 			atomic_cmpxchg(&adev->uvd.handles[i], handle, 0);
713 		amdgpu_bo_kunmap(bo);
714 		return 0;
715 
716 	default:
717 		DRM_ERROR("Illegal UVD message type (%d)!\n", msg_type);
718 		return -EINVAL;
719 	}
720 	BUG();
721 	return -EINVAL;
722 }
723 
724 /**
725  * amdgpu_uvd_cs_pass2 - second parsing round
726  *
727  * @ctx: UVD parser context
728  *
729  * Patch buffer addresses, make sure buffer sizes are correct.
730  */
731 static int amdgpu_uvd_cs_pass2(struct amdgpu_uvd_cs_ctx *ctx)
732 {
733 	struct amdgpu_bo_va_mapping *mapping;
734 	struct amdgpu_bo *bo;
735 	uint32_t cmd, lo, hi;
736 	uint64_t start, end;
737 	uint64_t addr;
738 	int r;
739 
740 	lo = amdgpu_get_ib_value(ctx->parser, ctx->ib_idx, ctx->data0);
741 	hi = amdgpu_get_ib_value(ctx->parser, ctx->ib_idx, ctx->data1);
742 	addr = ((uint64_t)lo) | (((uint64_t)hi) << 32);
743 
744 	mapping = amdgpu_cs_find_mapping(ctx->parser, addr, &bo);
745 	if (mapping == NULL)
746 		return -EINVAL;
747 
748 	start = amdgpu_bo_gpu_offset(bo);
749 
750 	end = (mapping->it.last + 1 - mapping->it.start);
751 	end = end * AMDGPU_GPU_PAGE_SIZE + start;
752 
753 	addr -= ((uint64_t)mapping->it.start) * AMDGPU_GPU_PAGE_SIZE;
754 	start += addr;
755 
756 	amdgpu_set_ib_value(ctx->parser, ctx->ib_idx, ctx->data0,
757 			    lower_32_bits(start));
758 	amdgpu_set_ib_value(ctx->parser, ctx->ib_idx, ctx->data1,
759 			    upper_32_bits(start));
760 
761 	cmd = amdgpu_get_ib_value(ctx->parser, ctx->ib_idx, ctx->idx) >> 1;
762 	if (cmd < 0x4) {
763 		if ((end - start) < ctx->buf_sizes[cmd]) {
764 			DRM_ERROR("buffer (%d) to small (%d / %d)!\n", cmd,
765 				  (unsigned)(end - start),
766 				  ctx->buf_sizes[cmd]);
767 			return -EINVAL;
768 		}
769 
770 	} else if (cmd == 0x206) {
771 		if ((end - start) < ctx->buf_sizes[4]) {
772 			DRM_ERROR("buffer (%d) to small (%d / %d)!\n", cmd,
773 					  (unsigned)(end - start),
774 					  ctx->buf_sizes[4]);
775 			return -EINVAL;
776 		}
777 	} else if ((cmd != 0x100) && (cmd != 0x204)) {
778 		DRM_ERROR("invalid UVD command %X!\n", cmd);
779 		return -EINVAL;
780 	}
781 
782 	if (!ctx->parser->adev->uvd.address_64_bit) {
783 		if ((start >> 28) != ((end - 1) >> 28)) {
784 			DRM_ERROR("reloc %LX-%LX crossing 256MB boundary!\n",
785 				  start, end);
786 			return -EINVAL;
787 		}
788 
789 		if ((cmd == 0 || cmd == 0x3) &&
790 		    (start >> 28) != (ctx->parser->adev->uvd.gpu_addr >> 28)) {
791 			DRM_ERROR("msg/fb buffer %LX-%LX out of 256MB segment!\n",
792 				  start, end);
793 			return -EINVAL;
794 		}
795 	}
796 
797 	if (cmd == 0) {
798 		ctx->has_msg_cmd = true;
799 		r = amdgpu_uvd_cs_msg(ctx, bo, addr);
800 		if (r)
801 			return r;
802 	} else if (!ctx->has_msg_cmd) {
803 		DRM_ERROR("Message needed before other commands are send!\n");
804 		return -EINVAL;
805 	}
806 
807 	return 0;
808 }
809 
810 /**
811  * amdgpu_uvd_cs_reg - parse register writes
812  *
813  * @ctx: UVD parser context
814  * @cb: callback function
815  *
816  * Parse the register writes, call cb on each complete command.
817  */
818 static int amdgpu_uvd_cs_reg(struct amdgpu_uvd_cs_ctx *ctx,
819 			     int (*cb)(struct amdgpu_uvd_cs_ctx *ctx))
820 {
821 	struct amdgpu_ib *ib = &ctx->parser->job->ibs[ctx->ib_idx];
822 	int i, r;
823 
824 	ctx->idx++;
825 	for (i = 0; i <= ctx->count; ++i) {
826 		unsigned reg = ctx->reg + i;
827 
828 		if (ctx->idx >= ib->length_dw) {
829 			DRM_ERROR("Register command after end of CS!\n");
830 			return -EINVAL;
831 		}
832 
833 		switch (reg) {
834 		case mmUVD_GPCOM_VCPU_DATA0:
835 			ctx->data0 = ctx->idx;
836 			break;
837 		case mmUVD_GPCOM_VCPU_DATA1:
838 			ctx->data1 = ctx->idx;
839 			break;
840 		case mmUVD_GPCOM_VCPU_CMD:
841 			r = cb(ctx);
842 			if (r)
843 				return r;
844 			break;
845 		case mmUVD_ENGINE_CNTL:
846 			break;
847 		default:
848 			DRM_ERROR("Invalid reg 0x%X!\n", reg);
849 			return -EINVAL;
850 		}
851 		ctx->idx++;
852 	}
853 	return 0;
854 }
855 
856 /**
857  * amdgpu_uvd_cs_packets - parse UVD packets
858  *
859  * @ctx: UVD parser context
860  * @cb: callback function
861  *
862  * Parse the command stream packets.
863  */
864 static int amdgpu_uvd_cs_packets(struct amdgpu_uvd_cs_ctx *ctx,
865 				 int (*cb)(struct amdgpu_uvd_cs_ctx *ctx))
866 {
867 	struct amdgpu_ib *ib = &ctx->parser->job->ibs[ctx->ib_idx];
868 	int r;
869 
870 	for (ctx->idx = 0 ; ctx->idx < ib->length_dw; ) {
871 		uint32_t cmd = amdgpu_get_ib_value(ctx->parser, ctx->ib_idx, ctx->idx);
872 		unsigned type = CP_PACKET_GET_TYPE(cmd);
873 		switch (type) {
874 		case PACKET_TYPE0:
875 			ctx->reg = CP_PACKET0_GET_REG(cmd);
876 			ctx->count = CP_PACKET_GET_COUNT(cmd);
877 			r = amdgpu_uvd_cs_reg(ctx, cb);
878 			if (r)
879 				return r;
880 			break;
881 		case PACKET_TYPE2:
882 			++ctx->idx;
883 			break;
884 		default:
885 			DRM_ERROR("Unknown packet type %d !\n", type);
886 			return -EINVAL;
887 		}
888 	}
889 	return 0;
890 }
891 
892 /**
893  * amdgpu_uvd_ring_parse_cs - UVD command submission parser
894  *
895  * @parser: Command submission parser context
896  *
897  * Parse the command stream, patch in addresses as necessary.
898  */
899 int amdgpu_uvd_ring_parse_cs(struct amdgpu_cs_parser *parser, uint32_t ib_idx)
900 {
901 	struct amdgpu_uvd_cs_ctx ctx = {};
902 	unsigned buf_sizes[] = {
903 		[0x00000000]	=	2048,
904 		[0x00000001]	=	0xFFFFFFFF,
905 		[0x00000002]	=	0xFFFFFFFF,
906 		[0x00000003]	=	2048,
907 		[0x00000004]	=	0xFFFFFFFF,
908 	};
909 	struct amdgpu_ib *ib = &parser->job->ibs[ib_idx];
910 	int r;
911 
912 	if (ib->length_dw % 16) {
913 		DRM_ERROR("UVD IB length (%d) not 16 dwords aligned!\n",
914 			  ib->length_dw);
915 		return -EINVAL;
916 	}
917 
918 	ctx.parser = parser;
919 	ctx.buf_sizes = buf_sizes;
920 	ctx.ib_idx = ib_idx;
921 
922 	/* first round, make sure the buffers are actually in the UVD segment */
923 	r = amdgpu_uvd_cs_packets(&ctx, amdgpu_uvd_cs_pass1);
924 	if (r)
925 		return r;
926 
927 	/* second round, patch buffer addresses into the command stream */
928 	r = amdgpu_uvd_cs_packets(&ctx, amdgpu_uvd_cs_pass2);
929 	if (r)
930 		return r;
931 
932 	if (!ctx.has_msg_cmd) {
933 		DRM_ERROR("UVD-IBs need a msg command!\n");
934 		return -EINVAL;
935 	}
936 
937 	return 0;
938 }
939 
940 static int amdgpu_uvd_send_msg(struct amdgpu_ring *ring, struct amdgpu_bo *bo,
941 			       bool direct, struct fence **fence)
942 {
943 	struct ttm_validate_buffer tv;
944 	struct ww_acquire_ctx ticket;
945 	struct list_head head;
946 	struct amdgpu_job *job;
947 	struct amdgpu_ib *ib;
948 	struct fence *f = NULL;
949 	struct amdgpu_device *adev = ring->adev;
950 	uint64_t addr;
951 	int i, r;
952 
953 	memset(&tv, 0, sizeof(tv));
954 	tv.bo = &bo->tbo;
955 
956 	INIT_LIST_HEAD(&head);
957 	list_add(&tv.head, &head);
958 
959 	r = ttm_eu_reserve_buffers(&ticket, &head, true, NULL);
960 	if (r)
961 		return r;
962 
963 	if (!bo->adev->uvd.address_64_bit) {
964 		amdgpu_ttm_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_VRAM);
965 		amdgpu_uvd_force_into_uvd_segment(bo);
966 	}
967 
968 	r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
969 	if (r)
970 		goto err;
971 
972 	r = amdgpu_job_alloc_with_ib(adev, 64, &job);
973 	if (r)
974 		goto err;
975 
976 	ib = &job->ibs[0];
977 	addr = amdgpu_bo_gpu_offset(bo);
978 	ib->ptr[0] = PACKET0(mmUVD_GPCOM_VCPU_DATA0, 0);
979 	ib->ptr[1] = addr;
980 	ib->ptr[2] = PACKET0(mmUVD_GPCOM_VCPU_DATA1, 0);
981 	ib->ptr[3] = addr >> 32;
982 	ib->ptr[4] = PACKET0(mmUVD_GPCOM_VCPU_CMD, 0);
983 	ib->ptr[5] = 0;
984 	for (i = 6; i < 16; ++i)
985 		ib->ptr[i] = PACKET2(0);
986 	ib->length_dw = 16;
987 
988 	if (direct) {
989 		r = amdgpu_ib_schedule(ring, 1, ib, NULL, NULL, &f);
990 		job->fence = fence_get(f);
991 		if (r)
992 			goto err_free;
993 
994 		amdgpu_job_free(job);
995 	} else {
996 		r = amdgpu_job_submit(job, ring, &adev->uvd.entity,
997 				      AMDGPU_FENCE_OWNER_UNDEFINED, &f);
998 		if (r)
999 			goto err_free;
1000 	}
1001 
1002 	ttm_eu_fence_buffer_objects(&ticket, &head, f);
1003 
1004 	if (fence)
1005 		*fence = fence_get(f);
1006 	amdgpu_bo_unref(&bo);
1007 	fence_put(f);
1008 
1009 	return 0;
1010 
1011 err_free:
1012 	amdgpu_job_free(job);
1013 
1014 err:
1015 	ttm_eu_backoff_reservation(&ticket, &head);
1016 	return r;
1017 }
1018 
1019 /* multiple fence commands without any stream commands in between can
1020    crash the vcpu so just try to emmit a dummy create/destroy msg to
1021    avoid this */
1022 int amdgpu_uvd_get_create_msg(struct amdgpu_ring *ring, uint32_t handle,
1023 			      struct fence **fence)
1024 {
1025 	struct amdgpu_device *adev = ring->adev;
1026 	struct amdgpu_bo *bo;
1027 	uint32_t *msg;
1028 	int r, i;
1029 
1030 	r = amdgpu_bo_create(adev, 1024, PAGE_SIZE, true,
1031 			     AMDGPU_GEM_DOMAIN_VRAM,
1032 			     AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
1033 			     NULL, NULL, &bo);
1034 	if (r)
1035 		return r;
1036 
1037 	r = amdgpu_bo_reserve(bo, false);
1038 	if (r) {
1039 		amdgpu_bo_unref(&bo);
1040 		return r;
1041 	}
1042 
1043 	r = amdgpu_bo_kmap(bo, (void **)&msg);
1044 	if (r) {
1045 		amdgpu_bo_unreserve(bo);
1046 		amdgpu_bo_unref(&bo);
1047 		return r;
1048 	}
1049 
1050 	/* stitch together an UVD create msg */
1051 	msg[0] = cpu_to_le32(0x00000de4);
1052 	msg[1] = cpu_to_le32(0x00000000);
1053 	msg[2] = cpu_to_le32(handle);
1054 	msg[3] = cpu_to_le32(0x00000000);
1055 	msg[4] = cpu_to_le32(0x00000000);
1056 	msg[5] = cpu_to_le32(0x00000000);
1057 	msg[6] = cpu_to_le32(0x00000000);
1058 	msg[7] = cpu_to_le32(0x00000780);
1059 	msg[8] = cpu_to_le32(0x00000440);
1060 	msg[9] = cpu_to_le32(0x00000000);
1061 	msg[10] = cpu_to_le32(0x01b37000);
1062 	for (i = 11; i < 1024; ++i)
1063 		msg[i] = cpu_to_le32(0x0);
1064 
1065 	amdgpu_bo_kunmap(bo);
1066 	amdgpu_bo_unreserve(bo);
1067 
1068 	return amdgpu_uvd_send_msg(ring, bo, true, fence);
1069 }
1070 
1071 int amdgpu_uvd_get_destroy_msg(struct amdgpu_ring *ring, uint32_t handle,
1072 			       bool direct, struct fence **fence)
1073 {
1074 	struct amdgpu_device *adev = ring->adev;
1075 	struct amdgpu_bo *bo;
1076 	uint32_t *msg;
1077 	int r, i;
1078 
1079 	r = amdgpu_bo_create(adev, 1024, PAGE_SIZE, true,
1080 			     AMDGPU_GEM_DOMAIN_VRAM,
1081 			     AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
1082 			     NULL, NULL, &bo);
1083 	if (r)
1084 		return r;
1085 
1086 	r = amdgpu_bo_reserve(bo, false);
1087 	if (r) {
1088 		amdgpu_bo_unref(&bo);
1089 		return r;
1090 	}
1091 
1092 	r = amdgpu_bo_kmap(bo, (void **)&msg);
1093 	if (r) {
1094 		amdgpu_bo_unreserve(bo);
1095 		amdgpu_bo_unref(&bo);
1096 		return r;
1097 	}
1098 
1099 	/* stitch together an UVD destroy msg */
1100 	msg[0] = cpu_to_le32(0x00000de4);
1101 	msg[1] = cpu_to_le32(0x00000002);
1102 	msg[2] = cpu_to_le32(handle);
1103 	msg[3] = cpu_to_le32(0x00000000);
1104 	for (i = 4; i < 1024; ++i)
1105 		msg[i] = cpu_to_le32(0x0);
1106 
1107 	amdgpu_bo_kunmap(bo);
1108 	amdgpu_bo_unreserve(bo);
1109 
1110 	return amdgpu_uvd_send_msg(ring, bo, direct, fence);
1111 }
1112 
1113 static void amdgpu_uvd_idle_work_handler(struct work_struct *work)
1114 {
1115 	struct amdgpu_device *adev =
1116 		container_of(work, struct amdgpu_device, uvd.idle_work.work);
1117 	unsigned i, fences, handles = 0;
1118 
1119 	fences = amdgpu_fence_count_emitted(&adev->uvd.ring);
1120 
1121 	for (i = 0; i < adev->uvd.max_handles; ++i)
1122 		if (atomic_read(&adev->uvd.handles[i]))
1123 			++handles;
1124 
1125 	if (fences == 0 && handles == 0) {
1126 		if (adev->pm.dpm_enabled) {
1127 			amdgpu_dpm_enable_uvd(adev, false);
1128 		} else {
1129 			amdgpu_asic_set_uvd_clocks(adev, 0, 0);
1130 		}
1131 	} else {
1132 		schedule_delayed_work(&adev->uvd.idle_work, UVD_IDLE_TIMEOUT);
1133 	}
1134 }
1135 
1136 void amdgpu_uvd_ring_begin_use(struct amdgpu_ring *ring)
1137 {
1138 	struct amdgpu_device *adev = ring->adev;
1139 	bool set_clocks = !cancel_delayed_work_sync(&adev->uvd.idle_work);
1140 
1141 	if (set_clocks) {
1142 		if (adev->pm.dpm_enabled) {
1143 			amdgpu_dpm_enable_uvd(adev, true);
1144 		} else {
1145 			amdgpu_asic_set_uvd_clocks(adev, 53300, 40000);
1146 		}
1147 	}
1148 }
1149 
1150 void amdgpu_uvd_ring_end_use(struct amdgpu_ring *ring)
1151 {
1152 	schedule_delayed_work(&ring->adev->uvd.idle_work, UVD_IDLE_TIMEOUT);
1153 }
1154 
1155 /**
1156  * amdgpu_uvd_ring_test_ib - test ib execution
1157  *
1158  * @ring: amdgpu_ring pointer
1159  *
1160  * Test if we can successfully execute an IB
1161  */
1162 int amdgpu_uvd_ring_test_ib(struct amdgpu_ring *ring, long timeout)
1163 {
1164 	struct fence *fence;
1165 	long r;
1166 
1167 	r = amdgpu_uvd_get_create_msg(ring, 1, NULL);
1168 	if (r) {
1169 		DRM_ERROR("amdgpu: failed to get create msg (%ld).\n", r);
1170 		goto error;
1171 	}
1172 
1173 	r = amdgpu_uvd_get_destroy_msg(ring, 1, true, &fence);
1174 	if (r) {
1175 		DRM_ERROR("amdgpu: failed to get destroy ib (%ld).\n", r);
1176 		goto error;
1177 	}
1178 
1179 	r = fence_wait_timeout(fence, false, timeout);
1180 	if (r == 0) {
1181 		DRM_ERROR("amdgpu: IB test timed out.\n");
1182 		r = -ETIMEDOUT;
1183 	} else if (r < 0) {
1184 		DRM_ERROR("amdgpu: fence wait failed (%ld).\n", r);
1185 	} else {
1186 		DRM_INFO("ib test on ring %d succeeded\n",  ring->idx);
1187 		r = 0;
1188 	}
1189 
1190 error:
1191 	fence_put(fence);
1192 	return r;
1193 }
1194