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