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