drm: Sync vblank handling code with Linux 3.14
[dragonfly.git] / sys / dev / drm / radeon / radeon_display.c
1 /*
2  * Copyright 2007-8 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  *
23  * Authors: Dave Airlie
24  *          Alex Deucher
25  *
26  * $FreeBSD: head/sys/dev/drm2/radeon/radeon_display.c 254885 2013-08-25 19:37:15Z dumbbell $
27  */
28
29 #include <drm/drmP.h>
30 #include <uapi_drm/radeon_drm.h>
31 #include "radeon.h"
32
33 #include "atom.h"
34
35 #include <drm/drm_crtc_helper.h>
36 #include <drm/drm_edid.h>
37 #include <linux/err.h>
38
39 static void avivo_crtc_load_lut(struct drm_crtc *crtc)
40 {
41         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
42         struct drm_device *dev = crtc->dev;
43         struct radeon_device *rdev = dev->dev_private;
44         int i;
45
46         DRM_DEBUG_KMS("%d\n", radeon_crtc->crtc_id);
47         WREG32(AVIVO_DC_LUTA_CONTROL + radeon_crtc->crtc_offset, 0);
48
49         WREG32(AVIVO_DC_LUTA_BLACK_OFFSET_BLUE + radeon_crtc->crtc_offset, 0);
50         WREG32(AVIVO_DC_LUTA_BLACK_OFFSET_GREEN + radeon_crtc->crtc_offset, 0);
51         WREG32(AVIVO_DC_LUTA_BLACK_OFFSET_RED + radeon_crtc->crtc_offset, 0);
52
53         WREG32(AVIVO_DC_LUTA_WHITE_OFFSET_BLUE + radeon_crtc->crtc_offset, 0xffff);
54         WREG32(AVIVO_DC_LUTA_WHITE_OFFSET_GREEN + radeon_crtc->crtc_offset, 0xffff);
55         WREG32(AVIVO_DC_LUTA_WHITE_OFFSET_RED + radeon_crtc->crtc_offset, 0xffff);
56
57         WREG32(AVIVO_DC_LUT_RW_SELECT, radeon_crtc->crtc_id);
58         WREG32(AVIVO_DC_LUT_RW_MODE, 0);
59         WREG32(AVIVO_DC_LUT_WRITE_EN_MASK, 0x0000003f);
60
61         WREG8(AVIVO_DC_LUT_RW_INDEX, 0);
62         for (i = 0; i < 256; i++) {
63                 WREG32(AVIVO_DC_LUT_30_COLOR,
64                              (radeon_crtc->lut_r[i] << 20) |
65                              (radeon_crtc->lut_g[i] << 10) |
66                              (radeon_crtc->lut_b[i] << 0));
67         }
68
69         WREG32(AVIVO_D1GRPH_LUT_SEL + radeon_crtc->crtc_offset, radeon_crtc->crtc_id);
70 }
71
72 static void dce4_crtc_load_lut(struct drm_crtc *crtc)
73 {
74         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
75         struct drm_device *dev = crtc->dev;
76         struct radeon_device *rdev = dev->dev_private;
77         int i;
78
79         DRM_DEBUG_KMS("%d\n", radeon_crtc->crtc_id);
80         WREG32(EVERGREEN_DC_LUT_CONTROL + radeon_crtc->crtc_offset, 0);
81
82         WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_BLUE + radeon_crtc->crtc_offset, 0);
83         WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_GREEN + radeon_crtc->crtc_offset, 0);
84         WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_RED + radeon_crtc->crtc_offset, 0);
85
86         WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_BLUE + radeon_crtc->crtc_offset, 0xffff);
87         WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_GREEN + radeon_crtc->crtc_offset, 0xffff);
88         WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_RED + radeon_crtc->crtc_offset, 0xffff);
89
90         WREG32(EVERGREEN_DC_LUT_RW_MODE + radeon_crtc->crtc_offset, 0);
91         WREG32(EVERGREEN_DC_LUT_WRITE_EN_MASK + radeon_crtc->crtc_offset, 0x00000007);
92
93         WREG32(EVERGREEN_DC_LUT_RW_INDEX + radeon_crtc->crtc_offset, 0);
94         for (i = 0; i < 256; i++) {
95                 WREG32(EVERGREEN_DC_LUT_30_COLOR + radeon_crtc->crtc_offset,
96                        (radeon_crtc->lut_r[i] << 20) |
97                        (radeon_crtc->lut_g[i] << 10) |
98                        (radeon_crtc->lut_b[i] << 0));
99         }
100 }
101
102 static void dce5_crtc_load_lut(struct drm_crtc *crtc)
103 {
104         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
105         struct drm_device *dev = crtc->dev;
106         struct radeon_device *rdev = dev->dev_private;
107         int i;
108
109         DRM_DEBUG_KMS("%d\n", radeon_crtc->crtc_id);
110
111         WREG32(NI_INPUT_CSC_CONTROL + radeon_crtc->crtc_offset,
112                (NI_INPUT_CSC_GRPH_MODE(NI_INPUT_CSC_BYPASS) |
113                 NI_INPUT_CSC_OVL_MODE(NI_INPUT_CSC_BYPASS)));
114         WREG32(NI_PRESCALE_GRPH_CONTROL + radeon_crtc->crtc_offset,
115                NI_GRPH_PRESCALE_BYPASS);
116         WREG32(NI_PRESCALE_OVL_CONTROL + radeon_crtc->crtc_offset,
117                NI_OVL_PRESCALE_BYPASS);
118         WREG32(NI_INPUT_GAMMA_CONTROL + radeon_crtc->crtc_offset,
119                (NI_GRPH_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT) |
120                 NI_OVL_INPUT_GAMMA_MODE(NI_INPUT_GAMMA_USE_LUT)));
121
122         WREG32(EVERGREEN_DC_LUT_CONTROL + radeon_crtc->crtc_offset, 0);
123
124         WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_BLUE + radeon_crtc->crtc_offset, 0);
125         WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_GREEN + radeon_crtc->crtc_offset, 0);
126         WREG32(EVERGREEN_DC_LUT_BLACK_OFFSET_RED + radeon_crtc->crtc_offset, 0);
127
128         WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_BLUE + radeon_crtc->crtc_offset, 0xffff);
129         WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_GREEN + radeon_crtc->crtc_offset, 0xffff);
130         WREG32(EVERGREEN_DC_LUT_WHITE_OFFSET_RED + radeon_crtc->crtc_offset, 0xffff);
131
132         WREG32(EVERGREEN_DC_LUT_RW_MODE + radeon_crtc->crtc_offset, 0);
133         WREG32(EVERGREEN_DC_LUT_WRITE_EN_MASK + radeon_crtc->crtc_offset, 0x00000007);
134
135         WREG32(EVERGREEN_DC_LUT_RW_INDEX + radeon_crtc->crtc_offset, 0);
136         for (i = 0; i < 256; i++) {
137                 WREG32(EVERGREEN_DC_LUT_30_COLOR + radeon_crtc->crtc_offset,
138                        (radeon_crtc->lut_r[i] << 20) |
139                        (radeon_crtc->lut_g[i] << 10) |
140                        (radeon_crtc->lut_b[i] << 0));
141         }
142
143         WREG32(NI_DEGAMMA_CONTROL + radeon_crtc->crtc_offset,
144                (NI_GRPH_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
145                 NI_OVL_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
146                 NI_ICON_DEGAMMA_MODE(NI_DEGAMMA_BYPASS) |
147                 NI_CURSOR_DEGAMMA_MODE(NI_DEGAMMA_BYPASS)));
148         WREG32(NI_GAMUT_REMAP_CONTROL + radeon_crtc->crtc_offset,
149                (NI_GRPH_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS) |
150                 NI_OVL_GAMUT_REMAP_MODE(NI_GAMUT_REMAP_BYPASS)));
151         WREG32(NI_REGAMMA_CONTROL + radeon_crtc->crtc_offset,
152                (NI_GRPH_REGAMMA_MODE(NI_REGAMMA_BYPASS) |
153                 NI_OVL_REGAMMA_MODE(NI_REGAMMA_BYPASS)));
154         WREG32(NI_OUTPUT_CSC_CONTROL + radeon_crtc->crtc_offset,
155                (NI_OUTPUT_CSC_GRPH_MODE(NI_OUTPUT_CSC_BYPASS) |
156                 NI_OUTPUT_CSC_OVL_MODE(NI_OUTPUT_CSC_BYPASS)));
157         /* XXX match this to the depth of the crtc fmt block, move to modeset? */
158         WREG32(0x6940 + radeon_crtc->crtc_offset, 0);
159         if (ASIC_IS_DCE8(rdev)) {
160                 /* XXX this only needs to be programmed once per crtc at startup,
161                  * not sure where the best place for it is
162                  */
163                 WREG32(CIK_ALPHA_CONTROL + radeon_crtc->crtc_offset,
164                        CIK_CURSOR_ALPHA_BLND_ENA);
165         }
166 }
167
168 static void legacy_crtc_load_lut(struct drm_crtc *crtc)
169 {
170         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
171         struct drm_device *dev = crtc->dev;
172         struct radeon_device *rdev = dev->dev_private;
173         int i;
174         uint32_t dac2_cntl;
175
176         dac2_cntl = RREG32(RADEON_DAC_CNTL2);
177         if (radeon_crtc->crtc_id == 0)
178                 dac2_cntl &= (uint32_t)~RADEON_DAC2_PALETTE_ACC_CTL;
179         else
180                 dac2_cntl |= RADEON_DAC2_PALETTE_ACC_CTL;
181         WREG32(RADEON_DAC_CNTL2, dac2_cntl);
182
183         WREG8(RADEON_PALETTE_INDEX, 0);
184         for (i = 0; i < 256; i++) {
185                 WREG32(RADEON_PALETTE_30_DATA,
186                              (radeon_crtc->lut_r[i] << 20) |
187                              (radeon_crtc->lut_g[i] << 10) |
188                              (radeon_crtc->lut_b[i] << 0));
189         }
190 }
191
192 void radeon_crtc_load_lut(struct drm_crtc *crtc)
193 {
194         struct drm_device *dev = crtc->dev;
195         struct radeon_device *rdev = dev->dev_private;
196
197         if (!crtc->enabled)
198                 return;
199
200         if (ASIC_IS_DCE5(rdev))
201                 dce5_crtc_load_lut(crtc);
202         else if (ASIC_IS_DCE4(rdev))
203                 dce4_crtc_load_lut(crtc);
204         else if (ASIC_IS_AVIVO(rdev))
205                 avivo_crtc_load_lut(crtc);
206         else
207                 legacy_crtc_load_lut(crtc);
208 }
209
210 /** Sets the color ramps on behalf of fbcon */
211 void radeon_crtc_fb_gamma_set(struct drm_crtc *crtc, u16 red, u16 green,
212                               u16 blue, int regno)
213 {
214         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
215
216         radeon_crtc->lut_r[regno] = red >> 6;
217         radeon_crtc->lut_g[regno] = green >> 6;
218         radeon_crtc->lut_b[regno] = blue >> 6;
219 }
220
221 /** Gets the color ramps on behalf of fbcon */
222 void radeon_crtc_fb_gamma_get(struct drm_crtc *crtc, u16 *red, u16 *green,
223                               u16 *blue, int regno)
224 {
225         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
226
227         *red = radeon_crtc->lut_r[regno] << 6;
228         *green = radeon_crtc->lut_g[regno] << 6;
229         *blue = radeon_crtc->lut_b[regno] << 6;
230 }
231
232 static void radeon_crtc_gamma_set(struct drm_crtc *crtc, u16 *red, u16 *green,
233                                   u16 *blue, uint32_t start, uint32_t size)
234 {
235         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
236         int end = (start + size > 256) ? 256 : start + size, i;
237
238         /* userspace palettes are always correct as is */
239         for (i = start; i < end; i++) {
240                 radeon_crtc->lut_r[i] = red[i] >> 6;
241                 radeon_crtc->lut_g[i] = green[i] >> 6;
242                 radeon_crtc->lut_b[i] = blue[i] >> 6;
243         }
244         radeon_crtc_load_lut(crtc);
245 }
246
247 static void radeon_crtc_destroy(struct drm_crtc *crtc)
248 {
249         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
250
251         drm_crtc_cleanup(crtc);
252         drm_free(radeon_crtc, M_DRM);
253 }
254
255 /*
256  * Handle unpin events outside the interrupt handler proper.
257  */
258 static void radeon_unpin_work_func(void *arg, int pending)
259 {
260         struct radeon_unpin_work *work = arg;
261         int r;
262
263         /* unpin of the old buffer */
264         r = radeon_bo_reserve(work->old_rbo, false);
265         if (likely(r == 0)) {
266                 r = radeon_bo_unpin(work->old_rbo);
267                 if (unlikely(r != 0)) {
268                         DRM_ERROR("failed to unpin buffer after flip\n");
269                 }
270                 radeon_bo_unreserve(work->old_rbo);
271         } else
272                 DRM_ERROR("failed to reserve buffer after flip\n");
273
274         drm_gem_object_unreference_unlocked(&work->old_rbo->gem_base);
275         drm_free(work, M_DRM);
276 }
277
278 void radeon_crtc_handle_flip(struct radeon_device *rdev, int crtc_id)
279 {
280         struct radeon_crtc *radeon_crtc = rdev->mode_info.crtcs[crtc_id];
281         struct radeon_unpin_work *work;
282         u32 update_pending;
283         int vpos, hpos;
284
285         lockmgr(&rdev->ddev->event_lock, LK_EXCLUSIVE);
286         work = radeon_crtc->unpin_work;
287         if (work == NULL ||
288             (work->fence && !radeon_fence_signaled(work->fence))) {
289                 lockmgr(&rdev->ddev->event_lock, LK_RELEASE);
290                 return;
291         }
292         /* New pageflip, or just completion of a previous one? */
293         if (!radeon_crtc->deferred_flip_completion) {
294                 /* do the flip (mmio) */
295                 update_pending = radeon_page_flip(rdev, crtc_id, work->new_crtc_base);
296         } else {
297                 /* This is just a completion of a flip queued in crtc
298                  * at last invocation. Make sure we go directly to
299                  * completion routine.
300                  */
301                 update_pending = 0;
302                 radeon_crtc->deferred_flip_completion = 0;
303         }
304
305         /* Has the pageflip already completed in crtc, or is it certain
306          * to complete in this vblank?
307          */
308         if (update_pending &&
309             (DRM_SCANOUTPOS_VALID & radeon_get_crtc_scanoutpos(rdev->ddev, crtc_id, 0,
310                                                                &vpos, &hpos, NULL, NULL)) &&
311             ((vpos >= (99 * rdev->mode_info.crtcs[crtc_id]->base.hwmode.crtc_vdisplay)/100) ||
312              (vpos < 0 && !ASIC_IS_AVIVO(rdev)))) {
313                 /* crtc didn't flip in this target vblank interval,
314                  * but flip is pending in crtc. Based on the current
315                  * scanout position we know that the current frame is
316                  * (nearly) complete and the flip will (likely)
317                  * complete before the start of the next frame.
318                  */
319                 update_pending = 0;
320         }
321         if (update_pending) {
322                 /* crtc didn't flip in this target vblank interval,
323                  * but flip is pending in crtc. It will complete it
324                  * in next vblank interval, so complete the flip at
325                  * next vblank irq.
326                  */
327                 radeon_crtc->deferred_flip_completion = 1;
328                 lockmgr(&rdev->ddev->event_lock, LK_RELEASE);
329                 return;
330         }
331
332         /* Pageflip (will be) certainly completed in this vblank. Clean up. */
333         radeon_crtc->unpin_work = NULL;
334
335         /* wakeup userspace */
336         if (work->event)
337                 drm_send_vblank_event(rdev->ddev, crtc_id, work->event);
338
339         lockmgr(&rdev->ddev->event_lock, LK_RELEASE);
340
341         drm_vblank_put(rdev->ddev, radeon_crtc->crtc_id);
342         radeon_fence_unref(&work->fence);
343         radeon_post_page_flip(work->rdev, work->crtc_id);
344         taskqueue_enqueue(rdev->tq, &work->work);
345 }
346
347 static int radeon_crtc_page_flip(struct drm_crtc *crtc,
348                                  struct drm_framebuffer *fb,
349                                  struct drm_pending_vblank_event *event,
350                                  uint32_t page_flip_flags)
351 {
352         struct drm_device *dev = crtc->dev;
353         struct radeon_device *rdev = dev->dev_private;
354         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
355         struct radeon_framebuffer *old_radeon_fb;
356         struct radeon_framebuffer *new_radeon_fb;
357         struct drm_gem_object *obj;
358         struct radeon_bo *rbo;
359         struct radeon_unpin_work *work;
360         u32 tiling_flags, pitch_pixels;
361         u64 base;
362         int r;
363
364         work = kmalloc(sizeof *work, M_DRM, M_WAITOK | M_ZERO);
365         if (work == NULL)
366                 return -ENOMEM;
367
368         work->event = event;
369         work->rdev = rdev;
370         work->crtc_id = radeon_crtc->crtc_id;
371         old_radeon_fb = to_radeon_framebuffer(crtc->fb);
372         new_radeon_fb = to_radeon_framebuffer(fb);
373         /* schedule unpin of the old buffer */
374         obj = old_radeon_fb->obj;
375         /* take a reference to the old object */
376         drm_gem_object_reference(obj);
377         rbo = gem_to_radeon_bo(obj);
378         work->old_rbo = rbo;
379         obj = new_radeon_fb->obj;
380         rbo = gem_to_radeon_bo(obj);
381
382         lockmgr(&rbo->tbo.bdev->fence_lock, LK_EXCLUSIVE);
383         if (rbo->tbo.sync_obj)
384                 work->fence = radeon_fence_ref(rbo->tbo.sync_obj);
385         lockmgr(&rbo->tbo.bdev->fence_lock, LK_RELEASE);
386
387         TASK_INIT(&work->work, 0, radeon_unpin_work_func, work);
388
389         /* We borrow the event spin lock for protecting unpin_work */
390         lockmgr(&dev->event_lock, LK_EXCLUSIVE);
391         if (radeon_crtc->unpin_work) {
392                 DRM_DEBUG_DRIVER("flip queue: crtc already busy\n");
393                 r = -EBUSY;
394                 goto unlock_free;
395         }
396         radeon_crtc->unpin_work = work;
397         radeon_crtc->deferred_flip_completion = 0;
398         lockmgr(&dev->event_lock, LK_RELEASE);
399
400         /* pin the new buffer */
401         DRM_DEBUG_DRIVER("flip-ioctl() cur_fbo = %p, cur_bbo = %p\n",
402                          work->old_rbo, rbo);
403
404         r = radeon_bo_reserve(rbo, false);
405         if (unlikely(r != 0)) {
406                 DRM_ERROR("failed to reserve new rbo buffer before flip\n");
407                 goto pflip_cleanup;
408         }
409         /* Only 27 bit offset for legacy CRTC */
410         r = radeon_bo_pin_restricted(rbo, RADEON_GEM_DOMAIN_VRAM,
411                                      ASIC_IS_AVIVO(rdev) ? 0 : 1 << 27, &base);
412         if (unlikely(r != 0)) {
413                 radeon_bo_unreserve(rbo);
414                 r = -EINVAL;
415                 DRM_ERROR("failed to pin new rbo buffer before flip\n");
416                 goto pflip_cleanup;
417         }
418         radeon_bo_get_tiling_flags(rbo, &tiling_flags, NULL);
419         radeon_bo_unreserve(rbo);
420
421         if (!ASIC_IS_AVIVO(rdev)) {
422                 /* crtc offset is from display base addr not FB location */
423                 base -= radeon_crtc->legacy_display_base_addr;
424                 pitch_pixels = fb->pitches[0] / (fb->bits_per_pixel / 8);
425
426                 if (tiling_flags & RADEON_TILING_MACRO) {
427                         if (ASIC_IS_R300(rdev)) {
428                                 base &= ~0x7ff;
429                         } else {
430                                 int byteshift = fb->bits_per_pixel >> 4;
431                                 int tile_addr = (((crtc->y >> 3) * pitch_pixels +  crtc->x) >> (8 - byteshift)) << 11;
432                                 base += tile_addr + ((crtc->x << byteshift) % 256) + ((crtc->y % 8) << 8);
433                         }
434                 } else {
435                         int offset = crtc->y * pitch_pixels + crtc->x;
436                         switch (fb->bits_per_pixel) {
437                         case 8:
438                         default:
439                                 offset *= 1;
440                                 break;
441                         case 15:
442                         case 16:
443                                 offset *= 2;
444                                 break;
445                         case 24:
446                                 offset *= 3;
447                                 break;
448                         case 32:
449                                 offset *= 4;
450                                 break;
451                         }
452                         base += offset;
453                 }
454                 base &= ~7;
455         }
456
457         lockmgr(&dev->event_lock, LK_EXCLUSIVE);
458         work->new_crtc_base = base;
459         lockmgr(&dev->event_lock, LK_RELEASE);
460
461         /* update crtc fb */
462         crtc->fb = fb;
463
464         r = drm_vblank_get(dev, radeon_crtc->crtc_id);
465         if (r) {
466                 DRM_ERROR("failed to get vblank before flip\n");
467                 goto pflip_cleanup1;
468         }
469
470         /* set the proper interrupt */
471         radeon_pre_page_flip(rdev, radeon_crtc->crtc_id);
472
473         return 0;
474
475 pflip_cleanup1:
476         if (unlikely(radeon_bo_reserve(rbo, false) != 0)) {
477                 DRM_ERROR("failed to reserve new rbo in error path\n");
478                 goto pflip_cleanup;
479         }
480         if (unlikely(radeon_bo_unpin(rbo) != 0)) {
481                 DRM_ERROR("failed to unpin new rbo in error path\n");
482         }
483         radeon_bo_unreserve(rbo);
484
485 pflip_cleanup:
486         lockmgr(&dev->event_lock, LK_EXCLUSIVE);
487         radeon_crtc->unpin_work = NULL;
488 unlock_free:
489         lockmgr(&dev->event_lock, LK_RELEASE);
490         drm_gem_object_unreference_unlocked(old_radeon_fb->obj);
491         radeon_fence_unref(&work->fence);
492         drm_free(work, M_DRM);
493
494         return r;
495 }
496
497 static const struct drm_crtc_funcs radeon_crtc_funcs = {
498         .cursor_set = radeon_crtc_cursor_set,
499         .cursor_move = radeon_crtc_cursor_move,
500         .gamma_set = radeon_crtc_gamma_set,
501         .set_config = drm_crtc_helper_set_config,
502         .destroy = radeon_crtc_destroy,
503         .page_flip = radeon_crtc_page_flip,
504 };
505
506 static void radeon_crtc_init(struct drm_device *dev, int index)
507 {
508         struct radeon_device *rdev = dev->dev_private;
509         struct radeon_crtc *radeon_crtc;
510         int i;
511
512         radeon_crtc = kmalloc(sizeof(struct radeon_crtc) + (RADEONFB_CONN_LIMIT * sizeof(struct drm_connector *)),
513                               M_DRM, M_WAITOK | M_ZERO);
514         if (radeon_crtc == NULL)
515                 return;
516
517         drm_crtc_init(dev, &radeon_crtc->base, &radeon_crtc_funcs);
518
519         drm_mode_crtc_set_gamma_size(&radeon_crtc->base, 256);
520         radeon_crtc->crtc_id = index;
521         rdev->mode_info.crtcs[index] = radeon_crtc;
522
523         if (rdev->family >= CHIP_BONAIRE) {
524                 radeon_crtc->max_cursor_width = CIK_CURSOR_WIDTH;
525                 radeon_crtc->max_cursor_height = CIK_CURSOR_HEIGHT;
526         } else {
527                 radeon_crtc->max_cursor_width = CURSOR_WIDTH;
528                 radeon_crtc->max_cursor_height = CURSOR_HEIGHT;
529         }
530
531 #if 0
532         radeon_crtc->mode_set.crtc = &radeon_crtc->base;
533         radeon_crtc->mode_set.connectors = (struct drm_connector **)(radeon_crtc + 1);
534         radeon_crtc->mode_set.num_connectors = 0;
535 #endif
536
537         for (i = 0; i < 256; i++) {
538                 radeon_crtc->lut_r[i] = i << 2;
539                 radeon_crtc->lut_g[i] = i << 2;
540                 radeon_crtc->lut_b[i] = i << 2;
541         }
542
543         if (rdev->is_atom_bios && (ASIC_IS_AVIVO(rdev) || radeon_r4xx_atom))
544                 radeon_atombios_init_crtc(dev, radeon_crtc);
545         else
546                 radeon_legacy_init_crtc(dev, radeon_crtc);
547 }
548
549 static const char *encoder_names[38] = {
550         "NONE",
551         "INTERNAL_LVDS",
552         "INTERNAL_TMDS1",
553         "INTERNAL_TMDS2",
554         "INTERNAL_DAC1",
555         "INTERNAL_DAC2",
556         "INTERNAL_SDVOA",
557         "INTERNAL_SDVOB",
558         "SI170B",
559         "CH7303",
560         "CH7301",
561         "INTERNAL_DVO1",
562         "EXTERNAL_SDVOA",
563         "EXTERNAL_SDVOB",
564         "TITFP513",
565         "INTERNAL_LVTM1",
566         "VT1623",
567         "HDMI_SI1930",
568         "HDMI_INTERNAL",
569         "INTERNAL_KLDSCP_TMDS1",
570         "INTERNAL_KLDSCP_DVO1",
571         "INTERNAL_KLDSCP_DAC1",
572         "INTERNAL_KLDSCP_DAC2",
573         "SI178",
574         "MVPU_FPGA",
575         "INTERNAL_DDI",
576         "VT1625",
577         "HDMI_SI1932",
578         "DP_AN9801",
579         "DP_DP501",
580         "INTERNAL_UNIPHY",
581         "INTERNAL_KLDSCP_LVTMA",
582         "INTERNAL_UNIPHY1",
583         "INTERNAL_UNIPHY2",
584         "NUTMEG",
585         "TRAVIS",
586         "INTERNAL_VCE",
587         "INTERNAL_UNIPHY3",
588 };
589
590 static const char *hpd_names[6] = {
591         "HPD1",
592         "HPD2",
593         "HPD3",
594         "HPD4",
595         "HPD5",
596         "HPD6",
597 };
598
599 static void radeon_print_display_setup(struct drm_device *dev)
600 {
601         struct drm_connector *connector;
602         struct radeon_connector *radeon_connector;
603         struct drm_encoder *encoder;
604         struct radeon_encoder *radeon_encoder;
605         uint32_t devices;
606         int i = 0;
607
608         DRM_INFO("Radeon Display Connectors\n");
609         list_for_each_entry(connector, &dev->mode_config.connector_list, head) {
610                 radeon_connector = to_radeon_connector(connector);
611                 DRM_INFO("Connector %d:\n", i);
612                 DRM_INFO("  %s\n", drm_get_connector_name(connector));
613                 if (radeon_connector->hpd.hpd != RADEON_HPD_NONE)
614                         DRM_INFO("  %s\n", hpd_names[radeon_connector->hpd.hpd]);
615                 if (radeon_connector->ddc_bus) {
616                         DRM_INFO("  DDC: 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
617                                  radeon_connector->ddc_bus->rec.mask_clk_reg,
618                                  radeon_connector->ddc_bus->rec.mask_data_reg,
619                                  radeon_connector->ddc_bus->rec.a_clk_reg,
620                                  radeon_connector->ddc_bus->rec.a_data_reg,
621                                  radeon_connector->ddc_bus->rec.en_clk_reg,
622                                  radeon_connector->ddc_bus->rec.en_data_reg,
623                                  radeon_connector->ddc_bus->rec.y_clk_reg,
624                                  radeon_connector->ddc_bus->rec.y_data_reg);
625                         if (radeon_connector->router.ddc_valid)
626                                 DRM_INFO("  DDC Router 0x%x/0x%x\n",
627                                          radeon_connector->router.ddc_mux_control_pin,
628                                          radeon_connector->router.ddc_mux_state);
629                         if (radeon_connector->router.cd_valid)
630                                 DRM_INFO("  Clock/Data Router 0x%x/0x%x\n",
631                                          radeon_connector->router.cd_mux_control_pin,
632                                          radeon_connector->router.cd_mux_state);
633                 } else {
634                         if (connector->connector_type == DRM_MODE_CONNECTOR_VGA ||
635                             connector->connector_type == DRM_MODE_CONNECTOR_DVII ||
636                             connector->connector_type == DRM_MODE_CONNECTOR_DVID ||
637                             connector->connector_type == DRM_MODE_CONNECTOR_DVIA ||
638                             connector->connector_type == DRM_MODE_CONNECTOR_HDMIA ||
639                             connector->connector_type == DRM_MODE_CONNECTOR_HDMIB)
640                                 DRM_INFO("  DDC: no ddc bus - possible BIOS bug - please report to xorg-driver-ati@lists.x.org\n");
641                 }
642                 DRM_INFO("  Encoders:\n");
643                 list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
644                         radeon_encoder = to_radeon_encoder(encoder);
645                         devices = radeon_encoder->devices & radeon_connector->devices;
646                         if (devices) {
647                                 if (devices & ATOM_DEVICE_CRT1_SUPPORT)
648                                         DRM_INFO("    CRT1: %s\n", encoder_names[radeon_encoder->encoder_id]);
649                                 if (devices & ATOM_DEVICE_CRT2_SUPPORT)
650                                         DRM_INFO("    CRT2: %s\n", encoder_names[radeon_encoder->encoder_id]);
651                                 if (devices & ATOM_DEVICE_LCD1_SUPPORT)
652                                         DRM_INFO("    LCD1: %s\n", encoder_names[radeon_encoder->encoder_id]);
653                                 if (devices & ATOM_DEVICE_DFP1_SUPPORT)
654                                         DRM_INFO("    DFP1: %s\n", encoder_names[radeon_encoder->encoder_id]);
655                                 if (devices & ATOM_DEVICE_DFP2_SUPPORT)
656                                         DRM_INFO("    DFP2: %s\n", encoder_names[radeon_encoder->encoder_id]);
657                                 if (devices & ATOM_DEVICE_DFP3_SUPPORT)
658                                         DRM_INFO("    DFP3: %s\n", encoder_names[radeon_encoder->encoder_id]);
659                                 if (devices & ATOM_DEVICE_DFP4_SUPPORT)
660                                         DRM_INFO("    DFP4: %s\n", encoder_names[radeon_encoder->encoder_id]);
661                                 if (devices & ATOM_DEVICE_DFP5_SUPPORT)
662                                         DRM_INFO("    DFP5: %s\n", encoder_names[radeon_encoder->encoder_id]);
663                                 if (devices & ATOM_DEVICE_DFP6_SUPPORT)
664                                         DRM_INFO("    DFP6: %s\n", encoder_names[radeon_encoder->encoder_id]);
665                                 if (devices & ATOM_DEVICE_TV1_SUPPORT)
666                                         DRM_INFO("    TV1: %s\n", encoder_names[radeon_encoder->encoder_id]);
667                                 if (devices & ATOM_DEVICE_CV_SUPPORT)
668                                         DRM_INFO("    CV: %s\n", encoder_names[radeon_encoder->encoder_id]);
669                         }
670                 }
671                 i++;
672         }
673 }
674
675 static bool radeon_setup_enc_conn(struct drm_device *dev)
676 {
677         struct radeon_device *rdev = dev->dev_private;
678         bool ret = false;
679
680         if (rdev->bios) {
681                 if (rdev->is_atom_bios) {
682                         ret = radeon_get_atom_connector_info_from_supported_devices_table(dev);
683                         if (ret == false)
684                                 ret = radeon_get_atom_connector_info_from_object_table(dev);
685                 } else {
686                         ret = radeon_get_legacy_connector_info_from_bios(dev);
687                         if (ret == false)
688                                 ret = radeon_get_legacy_connector_info_from_table(dev);
689                 }
690         } else {
691                 if (!ASIC_IS_AVIVO(rdev))
692                         ret = radeon_get_legacy_connector_info_from_table(dev);
693         }
694         if (ret) {
695                 radeon_setup_encoder_clones(dev);
696                 radeon_print_display_setup(dev);
697         }
698
699         return ret;
700 }
701
702 int radeon_ddc_get_modes(struct radeon_connector *radeon_connector)
703 {
704         struct drm_device *dev = radeon_connector->base.dev;
705         struct radeon_device *rdev = dev->dev_private;
706         int ret = 0;
707
708         /* on hw with routers, select right port */
709         if (radeon_connector->router.ddc_valid)
710                 radeon_router_select_ddc_port(radeon_connector);
711
712         if (radeon_connector_encoder_get_dp_bridge_encoder_id(&radeon_connector->base) !=
713             ENCODER_OBJECT_ID_NONE) {
714                 struct radeon_connector_atom_dig *dig = radeon_connector->con_priv;
715
716                 if (dig->dp_i2c_bus)
717                         radeon_connector->edid = drm_get_edid(&radeon_connector->base,
718                                                               dig->dp_i2c_bus->adapter);
719         } else if ((radeon_connector->base.connector_type == DRM_MODE_CONNECTOR_DisplayPort) ||
720                    (radeon_connector->base.connector_type == DRM_MODE_CONNECTOR_eDP)) {
721                 struct radeon_connector_atom_dig *dig = radeon_connector->con_priv;
722
723                 if ((dig->dp_sink_type == CONNECTOR_OBJECT_ID_DISPLAYPORT ||
724                      dig->dp_sink_type == CONNECTOR_OBJECT_ID_eDP) && dig->dp_i2c_bus)
725                         radeon_connector->edid = drm_get_edid(&radeon_connector->base,
726                                                               dig->dp_i2c_bus->adapter);
727                 else if (radeon_connector->ddc_bus && !radeon_connector->edid)
728                         radeon_connector->edid = drm_get_edid(&radeon_connector->base,
729                                                               radeon_connector->ddc_bus->adapter);
730         } else {
731                 if (radeon_connector->ddc_bus && !radeon_connector->edid)
732                         radeon_connector->edid = drm_get_edid(&radeon_connector->base,
733                                                               radeon_connector->ddc_bus->adapter);
734         }
735
736         if (!radeon_connector->edid) {
737                 if (rdev->is_atom_bios) {
738                         /* some laptops provide a hardcoded edid in rom for LCDs */
739                         if (((radeon_connector->base.connector_type == DRM_MODE_CONNECTOR_LVDS) ||
740                              (radeon_connector->base.connector_type == DRM_MODE_CONNECTOR_eDP)))
741                                 radeon_connector->edid = radeon_bios_get_hardcoded_edid(rdev);
742                 } else
743                         /* some servers provide a hardcoded edid in rom for KVMs */
744                         radeon_connector->edid = radeon_bios_get_hardcoded_edid(rdev);
745         }
746         if (radeon_connector->edid) {
747                 drm_mode_connector_update_edid_property(&radeon_connector->base, radeon_connector->edid);
748                 ret = drm_add_edid_modes(&radeon_connector->base, radeon_connector->edid);
749                 return ret;
750         }
751         drm_mode_connector_update_edid_property(&radeon_connector->base, NULL);
752         return 0;
753 }
754
755 /* avivo */
756 static void avivo_get_fb_div(struct radeon_pll *pll,
757                              u32 target_clock,
758                              u32 post_div,
759                              u32 ref_div,
760                              u32 *fb_div,
761                              u32 *frac_fb_div)
762 {
763         u32 tmp = post_div * ref_div;
764
765         tmp *= target_clock;
766         *fb_div = tmp / pll->reference_freq;
767         *frac_fb_div = tmp % pll->reference_freq;
768
769         if (*fb_div > pll->max_feedback_div)
770                 *fb_div = pll->max_feedback_div;
771         else if (*fb_div < pll->min_feedback_div)
772                 *fb_div = pll->min_feedback_div;
773 }
774
775 static u32 avivo_get_post_div(struct radeon_pll *pll,
776                               u32 target_clock)
777 {
778         u32 vco, post_div, tmp;
779
780         if (pll->flags & RADEON_PLL_USE_POST_DIV)
781                 return pll->post_div;
782
783         if (pll->flags & RADEON_PLL_PREFER_MINM_OVER_MAXP) {
784                 if (pll->flags & RADEON_PLL_IS_LCD)
785                         vco = pll->lcd_pll_out_min;
786                 else
787                         vco = pll->pll_out_min;
788         } else {
789                 if (pll->flags & RADEON_PLL_IS_LCD)
790                         vco = pll->lcd_pll_out_max;
791                 else
792                         vco = pll->pll_out_max;
793         }
794
795         post_div = vco / target_clock;
796         tmp = vco % target_clock;
797
798         if (pll->flags & RADEON_PLL_PREFER_MINM_OVER_MAXP) {
799                 if (tmp)
800                         post_div++;
801         } else {
802                 if (!tmp)
803                         post_div--;
804         }
805
806         if (post_div > pll->max_post_div)
807                 post_div = pll->max_post_div;
808         else if (post_div < pll->min_post_div)
809                 post_div = pll->min_post_div;
810
811         return post_div;
812 }
813
814 #define MAX_TOLERANCE 10
815
816 void radeon_compute_pll_avivo(struct radeon_pll *pll,
817                               u32 freq,
818                               u32 *dot_clock_p,
819                               u32 *fb_div_p,
820                               u32 *frac_fb_div_p,
821                               u32 *ref_div_p,
822                               u32 *post_div_p)
823 {
824         u32 target_clock = freq / 10;
825         u32 post_div = avivo_get_post_div(pll, target_clock);
826         u32 ref_div = pll->min_ref_div;
827         u32 fb_div = 0, frac_fb_div = 0, tmp;
828
829         if (pll->flags & RADEON_PLL_USE_REF_DIV)
830                 ref_div = pll->reference_div;
831
832         if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV) {
833                 avivo_get_fb_div(pll, target_clock, post_div, ref_div, &fb_div, &frac_fb_div);
834                 frac_fb_div = (100 * frac_fb_div) / pll->reference_freq;
835                 if (frac_fb_div >= 5) {
836                         frac_fb_div -= 5;
837                         frac_fb_div = frac_fb_div / 10;
838                         frac_fb_div++;
839                 }
840                 if (frac_fb_div >= 10) {
841                         fb_div++;
842                         frac_fb_div = 0;
843                 }
844         } else {
845                 while (ref_div <= pll->max_ref_div) {
846                         avivo_get_fb_div(pll, target_clock, post_div, ref_div,
847                                          &fb_div, &frac_fb_div);
848                         if (frac_fb_div >= (pll->reference_freq / 2))
849                                 fb_div++;
850                         frac_fb_div = 0;
851                         tmp = (pll->reference_freq * fb_div) / (post_div * ref_div);
852                         tmp = (tmp * 10000) / target_clock;
853
854                         if (tmp > (10000 + MAX_TOLERANCE))
855                                 ref_div++;
856                         else if (tmp >= (10000 - MAX_TOLERANCE))
857                                 break;
858                         else
859                                 ref_div++;
860                 }
861         }
862
863         *dot_clock_p = ((pll->reference_freq * fb_div * 10) + (pll->reference_freq * frac_fb_div)) /
864                 (ref_div * post_div * 10);
865         *fb_div_p = fb_div;
866         *frac_fb_div_p = frac_fb_div;
867         *ref_div_p = ref_div;
868         *post_div_p = post_div;
869         DRM_DEBUG_KMS("%d, pll dividers - fb: %d.%d ref: %d, post %d\n",
870                       *dot_clock_p, fb_div, frac_fb_div, ref_div, post_div);
871 }
872
873 /* pre-avivo */
874 static inline uint32_t radeon_div(uint64_t n, uint32_t d)
875 {
876         uint64_t mod;
877
878         n += d / 2;
879
880         mod = do_div(n, d);
881         return n;
882 }
883
884 void radeon_compute_pll_legacy(struct radeon_pll *pll,
885                                uint64_t freq,
886                                uint32_t *dot_clock_p,
887                                uint32_t *fb_div_p,
888                                uint32_t *frac_fb_div_p,
889                                uint32_t *ref_div_p,
890                                uint32_t *post_div_p)
891 {
892         uint32_t min_ref_div = pll->min_ref_div;
893         uint32_t max_ref_div = pll->max_ref_div;
894         uint32_t min_post_div = pll->min_post_div;
895         uint32_t max_post_div = pll->max_post_div;
896         uint32_t min_fractional_feed_div = 0;
897         uint32_t max_fractional_feed_div = 0;
898         uint32_t best_vco = pll->best_vco;
899         uint32_t best_post_div = 1;
900         uint32_t best_ref_div = 1;
901         uint32_t best_feedback_div = 1;
902         uint32_t best_frac_feedback_div = 0;
903         uint32_t best_freq = -1;
904         uint32_t best_error = 0xffffffff;
905         uint32_t best_vco_diff = 1;
906         uint32_t post_div;
907         u32 pll_out_min, pll_out_max;
908
909         DRM_DEBUG_KMS("PLL freq %ju %u %u\n", (uintmax_t)freq, pll->min_ref_div, pll->max_ref_div);
910         freq = freq * 1000;
911
912         if (pll->flags & RADEON_PLL_IS_LCD) {
913                 pll_out_min = pll->lcd_pll_out_min;
914                 pll_out_max = pll->lcd_pll_out_max;
915         } else {
916                 pll_out_min = pll->pll_out_min;
917                 pll_out_max = pll->pll_out_max;
918         }
919
920         if (pll_out_min > 64800)
921                 pll_out_min = 64800;
922
923         if (pll->flags & RADEON_PLL_USE_REF_DIV)
924                 min_ref_div = max_ref_div = pll->reference_div;
925         else {
926                 while (min_ref_div < max_ref_div-1) {
927                         uint32_t mid = (min_ref_div + max_ref_div) / 2;
928                         uint32_t pll_in = pll->reference_freq / mid;
929                         if (pll_in < pll->pll_in_min)
930                                 max_ref_div = mid;
931                         else if (pll_in > pll->pll_in_max)
932                                 min_ref_div = mid;
933                         else
934                                 break;
935                 }
936         }
937
938         if (pll->flags & RADEON_PLL_USE_POST_DIV)
939                 min_post_div = max_post_div = pll->post_div;
940
941         if (pll->flags & RADEON_PLL_USE_FRAC_FB_DIV) {
942                 min_fractional_feed_div = pll->min_frac_feedback_div;
943                 max_fractional_feed_div = pll->max_frac_feedback_div;
944         }
945
946         for (post_div = max_post_div; post_div >= min_post_div; --post_div) {
947                 uint32_t ref_div;
948
949                 if ((pll->flags & RADEON_PLL_NO_ODD_POST_DIV) && (post_div & 1))
950                         continue;
951
952                 /* legacy radeons only have a few post_divs */
953                 if (pll->flags & RADEON_PLL_LEGACY) {
954                         if ((post_div == 5) ||
955                             (post_div == 7) ||
956                             (post_div == 9) ||
957                             (post_div == 10) ||
958                             (post_div == 11) ||
959                             (post_div == 13) ||
960                             (post_div == 14) ||
961                             (post_div == 15))
962                                 continue;
963                 }
964
965                 for (ref_div = min_ref_div; ref_div <= max_ref_div; ++ref_div) {
966                         uint32_t feedback_div, current_freq = 0, error, vco_diff;
967                         uint32_t pll_in = pll->reference_freq / ref_div;
968                         uint32_t min_feed_div = pll->min_feedback_div;
969                         uint32_t max_feed_div = pll->max_feedback_div + 1;
970
971                         if (pll_in < pll->pll_in_min || pll_in > pll->pll_in_max)
972                                 continue;
973
974                         while (min_feed_div < max_feed_div) {
975                                 uint32_t vco;
976                                 uint32_t min_frac_feed_div = min_fractional_feed_div;
977                                 uint32_t max_frac_feed_div = max_fractional_feed_div + 1;
978                                 uint32_t frac_feedback_div;
979                                 uint64_t tmp;
980
981                                 feedback_div = (min_feed_div + max_feed_div) / 2;
982
983                                 tmp = (uint64_t)pll->reference_freq * feedback_div;
984                                 vco = radeon_div(tmp, ref_div);
985
986                                 if (vco < pll_out_min) {
987                                         min_feed_div = feedback_div + 1;
988                                         continue;
989                                 } else if (vco > pll_out_max) {
990                                         max_feed_div = feedback_div;
991                                         continue;
992                                 }
993
994                                 while (min_frac_feed_div < max_frac_feed_div) {
995                                         frac_feedback_div = (min_frac_feed_div + max_frac_feed_div) / 2;
996                                         tmp = (uint64_t)pll->reference_freq * 10000 * feedback_div;
997                                         tmp += (uint64_t)pll->reference_freq * 1000 * frac_feedback_div;
998                                         current_freq = radeon_div(tmp, ref_div * post_div);
999
1000                                         if (pll->flags & RADEON_PLL_PREFER_CLOSEST_LOWER) {
1001                                                 if (freq < current_freq)
1002                                                         error = 0xffffffff;
1003                                                 else
1004                                                         error = freq - current_freq;
1005                                         } else
1006                                                 error = abs(current_freq - freq);
1007                                         vco_diff = abs(vco - best_vco);
1008
1009                                         if ((best_vco == 0 && error < best_error) ||
1010                                             (best_vco != 0 &&
1011                                              ((best_error > 100 && error < best_error - 100) ||
1012                                               (abs(error - best_error) < 100 && vco_diff < best_vco_diff)))) {
1013                                                 best_post_div = post_div;
1014                                                 best_ref_div = ref_div;
1015                                                 best_feedback_div = feedback_div;
1016                                                 best_frac_feedback_div = frac_feedback_div;
1017                                                 best_freq = current_freq;
1018                                                 best_error = error;
1019                                                 best_vco_diff = vco_diff;
1020                                         } else if (current_freq == freq) {
1021                                                 if (best_freq == -1) {
1022                                                         best_post_div = post_div;
1023                                                         best_ref_div = ref_div;
1024                                                         best_feedback_div = feedback_div;
1025                                                         best_frac_feedback_div = frac_feedback_div;
1026                                                         best_freq = current_freq;
1027                                                         best_error = error;
1028                                                         best_vco_diff = vco_diff;
1029                                                 } else if (((pll->flags & RADEON_PLL_PREFER_LOW_REF_DIV) && (ref_div < best_ref_div)) ||
1030                                                            ((pll->flags & RADEON_PLL_PREFER_HIGH_REF_DIV) && (ref_div > best_ref_div)) ||
1031                                                            ((pll->flags & RADEON_PLL_PREFER_LOW_FB_DIV) && (feedback_div < best_feedback_div)) ||
1032                                                            ((pll->flags & RADEON_PLL_PREFER_HIGH_FB_DIV) && (feedback_div > best_feedback_div)) ||
1033                                                            ((pll->flags & RADEON_PLL_PREFER_LOW_POST_DIV) && (post_div < best_post_div)) ||
1034                                                            ((pll->flags & RADEON_PLL_PREFER_HIGH_POST_DIV) && (post_div > best_post_div))) {
1035                                                         best_post_div = post_div;
1036                                                         best_ref_div = ref_div;
1037                                                         best_feedback_div = feedback_div;
1038                                                         best_frac_feedback_div = frac_feedback_div;
1039                                                         best_freq = current_freq;
1040                                                         best_error = error;
1041                                                         best_vco_diff = vco_diff;
1042                                                 }
1043                                         }
1044                                         if (current_freq < freq)
1045                                                 min_frac_feed_div = frac_feedback_div + 1;
1046                                         else
1047                                                 max_frac_feed_div = frac_feedback_div;
1048                                 }
1049                                 if (current_freq < freq)
1050                                         min_feed_div = feedback_div + 1;
1051                                 else
1052                                         max_feed_div = feedback_div;
1053                         }
1054                 }
1055         }
1056
1057         *dot_clock_p = best_freq / 10000;
1058         *fb_div_p = best_feedback_div;
1059         *frac_fb_div_p = best_frac_feedback_div;
1060         *ref_div_p = best_ref_div;
1061         *post_div_p = best_post_div;
1062         DRM_DEBUG_KMS("%lld %d, pll dividers - fb: %d.%d ref: %d, post %d\n",
1063                       (long long)freq,
1064                       best_freq / 1000, best_feedback_div, best_frac_feedback_div,
1065                       best_ref_div, best_post_div);
1066
1067 }
1068
1069 static void radeon_user_framebuffer_destroy(struct drm_framebuffer *fb)
1070 {
1071         struct radeon_framebuffer *radeon_fb = to_radeon_framebuffer(fb);
1072
1073         if (radeon_fb->obj) {
1074                 drm_gem_object_unreference_unlocked(radeon_fb->obj);
1075         }
1076         drm_framebuffer_cleanup(fb);
1077         drm_free(radeon_fb, M_DRM);
1078 }
1079
1080 static int radeon_user_framebuffer_create_handle(struct drm_framebuffer *fb,
1081                                                   struct drm_file *file_priv,
1082                                                   unsigned int *handle)
1083 {
1084         struct radeon_framebuffer *radeon_fb = to_radeon_framebuffer(fb);
1085
1086         return drm_gem_handle_create(file_priv, radeon_fb->obj, handle);
1087 }
1088
1089 static const struct drm_framebuffer_funcs radeon_fb_funcs = {
1090         .destroy = radeon_user_framebuffer_destroy,
1091         .create_handle = radeon_user_framebuffer_create_handle,
1092 };
1093
1094 int
1095 radeon_framebuffer_init(struct drm_device *dev,
1096                         struct radeon_framebuffer *rfb,
1097                         struct drm_mode_fb_cmd2 *mode_cmd,
1098                         struct drm_gem_object *obj)
1099 {
1100         int ret;
1101         rfb->obj = obj;
1102         drm_helper_mode_fill_fb_struct(&rfb->base, mode_cmd);
1103         ret = drm_framebuffer_init(dev, &rfb->base, &radeon_fb_funcs);
1104         if (ret) {
1105                 rfb->obj = NULL;
1106                 return ret;
1107         }
1108         return 0;
1109 }
1110
1111 static struct drm_framebuffer *
1112 radeon_user_framebuffer_create(struct drm_device *dev,
1113                                struct drm_file *file_priv,
1114                                struct drm_mode_fb_cmd2 *mode_cmd)
1115 {
1116         struct drm_gem_object *obj;
1117         struct radeon_framebuffer *radeon_fb;
1118         int ret;
1119
1120         obj = drm_gem_object_lookup(dev, file_priv, mode_cmd->handles[0]);
1121         if (obj ==  NULL) {
1122                 dev_err(dev->dev, "No GEM object associated to handle 0x%08X, "
1123                         "can't create framebuffer\n", mode_cmd->handles[0]);
1124                 return ERR_PTR(-ENOENT);
1125         }
1126
1127         radeon_fb = kmalloc(sizeof(*radeon_fb), M_DRM,
1128                             M_WAITOK | M_ZERO);
1129         if (radeon_fb == NULL) {
1130                 drm_gem_object_unreference_unlocked(obj);
1131                 return ERR_PTR(-ENOMEM);
1132         }
1133
1134         ret = radeon_framebuffer_init(dev, radeon_fb, mode_cmd, obj);
1135         if (ret) {
1136                 kfree(radeon_fb);
1137                 drm_gem_object_unreference_unlocked(obj);
1138                 return ERR_PTR(ret);
1139         }
1140
1141         return &radeon_fb->base;
1142 }
1143
1144 static void radeon_output_poll_changed(struct drm_device *dev)
1145 {
1146         struct radeon_device *rdev = dev->dev_private;
1147         radeon_fb_output_poll_changed(rdev);
1148 }
1149
1150 static const struct drm_mode_config_funcs radeon_mode_funcs = {
1151         .fb_create = radeon_user_framebuffer_create,
1152         .output_poll_changed = radeon_output_poll_changed
1153 };
1154
1155 static struct drm_prop_enum_list radeon_tmds_pll_enum_list[] =
1156 {       { 0, "driver" },
1157         { 1, "bios" },
1158 };
1159
1160 static struct drm_prop_enum_list radeon_tv_std_enum_list[] =
1161 {       { TV_STD_NTSC, "ntsc" },
1162         { TV_STD_PAL, "pal" },
1163         { TV_STD_PAL_M, "pal-m" },
1164         { TV_STD_PAL_60, "pal-60" },
1165         { TV_STD_NTSC_J, "ntsc-j" },
1166         { TV_STD_SCART_PAL, "scart-pal" },
1167         { TV_STD_PAL_CN, "pal-cn" },
1168         { TV_STD_SECAM, "secam" },
1169 };
1170
1171 static struct drm_prop_enum_list radeon_underscan_enum_list[] =
1172 {       { UNDERSCAN_OFF, "off" },
1173         { UNDERSCAN_ON, "on" },
1174         { UNDERSCAN_AUTO, "auto" },
1175 };
1176
1177 static int radeon_modeset_create_props(struct radeon_device *rdev)
1178 {
1179         int sz;
1180
1181         if (rdev->is_atom_bios) {
1182                 rdev->mode_info.coherent_mode_property =
1183                         drm_property_create_range(rdev->ddev, 0 , "coherent", 0, 1);
1184                 if (!rdev->mode_info.coherent_mode_property)
1185                         return -ENOMEM;
1186         }
1187
1188         if (!ASIC_IS_AVIVO(rdev)) {
1189                 sz = DRM_ARRAY_SIZE(radeon_tmds_pll_enum_list);
1190                 rdev->mode_info.tmds_pll_property =
1191                         drm_property_create_enum(rdev->ddev, 0,
1192                                             "tmds_pll",
1193                                             radeon_tmds_pll_enum_list, sz);
1194         }
1195
1196         rdev->mode_info.load_detect_property =
1197                 drm_property_create_range(rdev->ddev, 0, "load detection", 0, 1);
1198         if (!rdev->mode_info.load_detect_property)
1199                 return -ENOMEM;
1200
1201         drm_mode_create_scaling_mode_property(rdev->ddev);
1202
1203         sz = DRM_ARRAY_SIZE(radeon_tv_std_enum_list);
1204         rdev->mode_info.tv_std_property =
1205                 drm_property_create_enum(rdev->ddev, 0,
1206                                     "tv standard",
1207                                     radeon_tv_std_enum_list, sz);
1208
1209         sz = DRM_ARRAY_SIZE(radeon_underscan_enum_list);
1210         rdev->mode_info.underscan_property =
1211                 drm_property_create_enum(rdev->ddev, 0,
1212                                     "underscan",
1213                                     radeon_underscan_enum_list, sz);
1214
1215         rdev->mode_info.underscan_hborder_property =
1216                 drm_property_create_range(rdev->ddev, 0,
1217                                         "underscan hborder", 0, 128);
1218         if (!rdev->mode_info.underscan_hborder_property)
1219                 return -ENOMEM;
1220
1221         rdev->mode_info.underscan_vborder_property =
1222                 drm_property_create_range(rdev->ddev, 0,
1223                                         "underscan vborder", 0, 128);
1224         if (!rdev->mode_info.underscan_vborder_property)
1225                 return -ENOMEM;
1226
1227         return 0;
1228 }
1229
1230 void radeon_update_display_priority(struct radeon_device *rdev)
1231 {
1232         /* adjustment options for the display watermarks */
1233         if ((radeon_disp_priority == 0) || (radeon_disp_priority > 2)) {
1234                 /* set display priority to high for r3xx, rv515 chips
1235                  * this avoids flickering due to underflow to the
1236                  * display controllers during heavy acceleration.
1237                  * Don't force high on rs4xx igp chips as it seems to
1238                  * affect the sound card.  See kernel bug 15982.
1239                  */
1240                 if ((ASIC_IS_R300(rdev) || (rdev->family == CHIP_RV515)) &&
1241                     !(rdev->flags & RADEON_IS_IGP))
1242                         rdev->disp_priority = 2;
1243                 else
1244                         rdev->disp_priority = 0;
1245         } else
1246                 rdev->disp_priority = radeon_disp_priority;
1247
1248 }
1249
1250 /*
1251  * Allocate hdmi structs and determine register offsets
1252  */
1253 static void radeon_afmt_init(struct radeon_device *rdev)
1254 {
1255         int i;
1256
1257         for (i = 0; i < RADEON_MAX_AFMT_BLOCKS; i++)
1258                 rdev->mode_info.afmt[i] = NULL;
1259
1260         if (ASIC_IS_DCE6(rdev)) {
1261                 /* todo */
1262         } else if (ASIC_IS_DCE4(rdev)) {
1263                 /* DCE4/5 has 6 audio blocks tied to DIG encoders */
1264                 /* DCE4.1 has 2 audio blocks tied to DIG encoders */
1265                 rdev->mode_info.afmt[0] = kmalloc(sizeof(struct radeon_afmt),
1266                                                   M_DRM,
1267                                                   M_WAITOK | M_ZERO);
1268                 if (rdev->mode_info.afmt[0]) {
1269                         rdev->mode_info.afmt[0]->offset = EVERGREEN_CRTC0_REGISTER_OFFSET;
1270                         rdev->mode_info.afmt[0]->id = 0;
1271                 }
1272                 rdev->mode_info.afmt[1] = kmalloc(sizeof(struct radeon_afmt),
1273                                                   M_DRM,
1274                                                   M_WAITOK | M_ZERO);
1275                 if (rdev->mode_info.afmt[1]) {
1276                         rdev->mode_info.afmt[1]->offset = EVERGREEN_CRTC1_REGISTER_OFFSET;
1277                         rdev->mode_info.afmt[1]->id = 1;
1278                 }
1279                 if (!ASIC_IS_DCE41(rdev)) {
1280                         rdev->mode_info.afmt[2] = kmalloc(sizeof(struct radeon_afmt),
1281                                                           M_DRM,
1282                                                           M_WAITOK | M_ZERO);
1283                         if (rdev->mode_info.afmt[2]) {
1284                                 rdev->mode_info.afmt[2]->offset = EVERGREEN_CRTC2_REGISTER_OFFSET;
1285                                 rdev->mode_info.afmt[2]->id = 2;
1286                         }
1287                         rdev->mode_info.afmt[3] = kmalloc(sizeof(struct radeon_afmt),
1288                                                           M_DRM,
1289                                                           M_WAITOK | M_ZERO);
1290                         if (rdev->mode_info.afmt[3]) {
1291                                 rdev->mode_info.afmt[3]->offset = EVERGREEN_CRTC3_REGISTER_OFFSET;
1292                                 rdev->mode_info.afmt[3]->id = 3;
1293                         }
1294                         rdev->mode_info.afmt[4] = kmalloc(sizeof(struct radeon_afmt),
1295                                                           M_DRM,
1296                                                           M_WAITOK | M_ZERO);
1297                         if (rdev->mode_info.afmt[4]) {
1298                                 rdev->mode_info.afmt[4]->offset = EVERGREEN_CRTC4_REGISTER_OFFSET;
1299                                 rdev->mode_info.afmt[4]->id = 4;
1300                         }
1301                         rdev->mode_info.afmt[5] = kmalloc(sizeof(struct radeon_afmt),
1302                                                           M_DRM,
1303                                                           M_WAITOK | M_ZERO);
1304                         if (rdev->mode_info.afmt[5]) {
1305                                 rdev->mode_info.afmt[5]->offset = EVERGREEN_CRTC5_REGISTER_OFFSET;
1306                                 rdev->mode_info.afmt[5]->id = 5;
1307                         }
1308                 }
1309         } else if (ASIC_IS_DCE3(rdev)) {
1310                 /* DCE3.x has 2 audio blocks tied to DIG encoders */
1311                 rdev->mode_info.afmt[0] = kmalloc(sizeof(struct radeon_afmt),
1312                                                   M_DRM,
1313                                                   M_WAITOK | M_ZERO);
1314                 if (rdev->mode_info.afmt[0]) {
1315                         rdev->mode_info.afmt[0]->offset = DCE3_HDMI_OFFSET0;
1316                         rdev->mode_info.afmt[0]->id = 0;
1317                 }
1318                 rdev->mode_info.afmt[1] = kmalloc(sizeof(struct radeon_afmt),
1319                                                   M_DRM,
1320                                                   M_WAITOK | M_ZERO);
1321                 if (rdev->mode_info.afmt[1]) {
1322                         rdev->mode_info.afmt[1]->offset = DCE3_HDMI_OFFSET1;
1323                         rdev->mode_info.afmt[1]->id = 1;
1324                 }
1325         } else if (ASIC_IS_DCE2(rdev)) {
1326                 /* DCE2 has at least 1 routable audio block */
1327                 rdev->mode_info.afmt[0] = kmalloc(sizeof(struct radeon_afmt),
1328                                                   M_DRM,
1329                                                   M_WAITOK | M_ZERO);
1330                 if (rdev->mode_info.afmt[0]) {
1331                         rdev->mode_info.afmt[0]->offset = DCE2_HDMI_OFFSET0;
1332                         rdev->mode_info.afmt[0]->id = 0;
1333                 }
1334                 /* r6xx has 2 routable audio blocks */
1335                 if (rdev->family >= CHIP_R600) {
1336                         rdev->mode_info.afmt[1] = kmalloc(sizeof(struct radeon_afmt),
1337                                                           M_DRM,
1338                                                           M_WAITOK | M_ZERO);
1339                         if (rdev->mode_info.afmt[1]) {
1340                                 rdev->mode_info.afmt[1]->offset = DCE2_HDMI_OFFSET1;
1341                                 rdev->mode_info.afmt[1]->id = 1;
1342                         }
1343                 }
1344         }
1345 }
1346
1347 static void radeon_afmt_fini(struct radeon_device *rdev)
1348 {
1349         int i;
1350
1351         for (i = 0; i < RADEON_MAX_AFMT_BLOCKS; i++) {
1352                 drm_free(rdev->mode_info.afmt[i], M_DRM);
1353                 rdev->mode_info.afmt[i] = NULL;
1354         }
1355 }
1356
1357 int radeon_modeset_init(struct radeon_device *rdev)
1358 {
1359         int i;
1360         int ret;
1361
1362         drm_mode_config_init(rdev->ddev);
1363         rdev->mode_info.mode_config_initialized = true;
1364
1365         rdev->ddev->mode_config.funcs = &radeon_mode_funcs;
1366
1367         if (ASIC_IS_DCE5(rdev)) {
1368                 rdev->ddev->mode_config.max_width = 16384;
1369                 rdev->ddev->mode_config.max_height = 16384;
1370         } else if (ASIC_IS_AVIVO(rdev)) {
1371                 rdev->ddev->mode_config.max_width = 8192;
1372                 rdev->ddev->mode_config.max_height = 8192;
1373         } else {
1374                 rdev->ddev->mode_config.max_width = 4096;
1375                 rdev->ddev->mode_config.max_height = 4096;
1376         }
1377
1378         rdev->ddev->mode_config.preferred_depth = 24;
1379         rdev->ddev->mode_config.prefer_shadow = 1;
1380
1381         rdev->ddev->mode_config.fb_base = rdev->mc.aper_base;
1382
1383         ret = radeon_modeset_create_props(rdev);
1384         if (ret) {
1385                 return ret;
1386         }
1387
1388         /* init i2c buses */
1389         radeon_i2c_init(rdev);
1390
1391         /* check combios for a valid hardcoded EDID - Sun servers */
1392         if (!rdev->is_atom_bios) {
1393                 /* check for hardcoded EDID in BIOS */
1394                 radeon_combios_check_hardcoded_edid(rdev);
1395         }
1396
1397         /* allocate crtcs */
1398         for (i = 0; i < rdev->num_crtc; i++) {
1399                 radeon_crtc_init(rdev->ddev, i);
1400         }
1401
1402         /* okay we should have all the bios connectors */
1403         ret = radeon_setup_enc_conn(rdev->ddev);
1404         if (!ret) {
1405                 return ret;
1406         }
1407
1408         /* init dig PHYs, disp eng pll */
1409         if (rdev->is_atom_bios) {
1410                 radeon_atom_encoder_init(rdev);
1411                 radeon_atom_disp_eng_pll_init(rdev);
1412         }
1413
1414         /* initialize hpd */
1415         radeon_hpd_init(rdev);
1416
1417         /* setup afmt */
1418         radeon_afmt_init(rdev);
1419
1420         /* Initialize power management */
1421         radeon_pm_init(rdev);
1422
1423         radeon_fbdev_init(rdev);
1424         drm_kms_helper_poll_init(rdev->ddev);
1425
1426         return 0;
1427 }
1428
1429 void radeon_modeset_fini(struct radeon_device *rdev)
1430 {
1431         radeon_fbdev_fini(rdev);
1432         drm_free(rdev->mode_info.bios_hardcoded_edid, M_DRM);
1433         radeon_pm_fini(rdev);
1434
1435         if (rdev->mode_info.mode_config_initialized) {
1436                 radeon_afmt_fini(rdev);
1437                 drm_kms_helper_poll_fini(rdev->ddev);
1438                 radeon_hpd_fini(rdev);
1439                 DRM_UNLOCK(rdev->ddev); /* Work around lock recursion. dumbbell@ */
1440                 drm_mode_config_cleanup(rdev->ddev);
1441                 DRM_LOCK(rdev->ddev);
1442                 rdev->mode_info.mode_config_initialized = false;
1443         }
1444         /* free i2c buses */
1445         radeon_i2c_fini(rdev);
1446 }
1447
1448 static bool is_hdtv_mode(const struct drm_display_mode *mode)
1449 {
1450         /* try and guess if this is a tv or a monitor */
1451         if ((mode->vdisplay == 480 && mode->hdisplay == 720) || /* 480p */
1452             (mode->vdisplay == 576) || /* 576p */
1453             (mode->vdisplay == 720) || /* 720p */
1454             (mode->vdisplay == 1080)) /* 1080p */
1455                 return true;
1456         else
1457                 return false;
1458 }
1459
1460 bool radeon_crtc_scaling_mode_fixup(struct drm_crtc *crtc,
1461                                 const struct drm_display_mode *mode,
1462                                 struct drm_display_mode *adjusted_mode)
1463 {
1464         struct drm_device *dev = crtc->dev;
1465         struct radeon_device *rdev = dev->dev_private;
1466         struct drm_encoder *encoder;
1467         struct radeon_crtc *radeon_crtc = to_radeon_crtc(crtc);
1468         struct radeon_encoder *radeon_encoder;
1469         struct drm_connector *connector;
1470         struct radeon_connector *radeon_connector;
1471         bool first = true;
1472         u32 src_v = 1, dst_v = 1;
1473         u32 src_h = 1, dst_h = 1;
1474
1475         radeon_crtc->h_border = 0;
1476         radeon_crtc->v_border = 0;
1477
1478         list_for_each_entry(encoder, &dev->mode_config.encoder_list, head) {
1479                 if (encoder->crtc != crtc)
1480                         continue;
1481                 radeon_encoder = to_radeon_encoder(encoder);
1482                 connector = radeon_get_connector_for_encoder(encoder);
1483                 radeon_connector = to_radeon_connector(connector);
1484
1485                 if (first) {
1486                         /* set scaling */
1487                         if (radeon_encoder->rmx_type == RMX_OFF)
1488                                 radeon_crtc->rmx_type = RMX_OFF;
1489                         else if (mode->hdisplay < radeon_encoder->native_mode.hdisplay ||
1490                                  mode->vdisplay < radeon_encoder->native_mode.vdisplay)
1491                                 radeon_crtc->rmx_type = radeon_encoder->rmx_type;
1492                         else
1493                                 radeon_crtc->rmx_type = RMX_OFF;
1494                         /* copy native mode */
1495                         memcpy(&radeon_crtc->native_mode,
1496                                &radeon_encoder->native_mode,
1497                                 sizeof(struct drm_display_mode));
1498                         src_v = crtc->mode.vdisplay;
1499                         dst_v = radeon_crtc->native_mode.vdisplay;
1500                         src_h = crtc->mode.hdisplay;
1501                         dst_h = radeon_crtc->native_mode.hdisplay;
1502
1503                         /* fix up for overscan on hdmi */
1504                         if (ASIC_IS_AVIVO(rdev) &&
1505                             (!(mode->flags & DRM_MODE_FLAG_INTERLACE)) &&
1506                             ((radeon_encoder->underscan_type == UNDERSCAN_ON) ||
1507                              ((radeon_encoder->underscan_type == UNDERSCAN_AUTO) &&
1508                               drm_detect_hdmi_monitor(radeon_connector->edid) &&
1509                               is_hdtv_mode(mode)))) {
1510                                 if (radeon_encoder->underscan_hborder != 0)
1511                                         radeon_crtc->h_border = radeon_encoder->underscan_hborder;
1512                                 else
1513                                         radeon_crtc->h_border = (mode->hdisplay >> 5) + 16;
1514                                 if (radeon_encoder->underscan_vborder != 0)
1515                                         radeon_crtc->v_border = radeon_encoder->underscan_vborder;
1516                                 else
1517                                         radeon_crtc->v_border = (mode->vdisplay >> 5) + 16;
1518                                 radeon_crtc->rmx_type = RMX_FULL;
1519                                 src_v = crtc->mode.vdisplay;
1520                                 dst_v = crtc->mode.vdisplay - (radeon_crtc->v_border * 2);
1521                                 src_h = crtc->mode.hdisplay;
1522                                 dst_h = crtc->mode.hdisplay - (radeon_crtc->h_border * 2);
1523                         }
1524                         first = false;
1525                 } else {
1526                         if (radeon_crtc->rmx_type != radeon_encoder->rmx_type) {
1527                                 /* WARNING: Right now this can't happen but
1528                                  * in the future we need to check that scaling
1529                                  * are consistent across different encoder
1530                                  * (ie all encoder can work with the same
1531                                  *  scaling).
1532                                  */
1533                                 DRM_ERROR("Scaling not consistent across encoder.\n");
1534                                 return false;
1535                         }
1536                 }
1537         }
1538         if (radeon_crtc->rmx_type != RMX_OFF) {
1539                 fixed20_12 a, b;
1540                 a.full = dfixed_const(src_v);
1541                 b.full = dfixed_const(dst_v);
1542                 radeon_crtc->vsc.full = dfixed_div(a, b);
1543                 a.full = dfixed_const(src_h);
1544                 b.full = dfixed_const(dst_h);
1545                 radeon_crtc->hsc.full = dfixed_div(a, b);
1546         } else {
1547                 radeon_crtc->vsc.full = dfixed_const(1);
1548                 radeon_crtc->hsc.full = dfixed_const(1);
1549         }
1550         return true;
1551 }
1552
1553 /*
1554  * Retrieve current video scanout position of crtc on a given gpu, and
1555  * an optional accurate timestamp of when query happened.
1556  *
1557  * \param dev Device to query.
1558  * \param crtc Crtc to query.
1559  * \param flags Flags from caller (DRM_CALLED_FROM_VBLIRQ or 0).
1560  * \param *vpos Location where vertical scanout position should be stored.
1561  * \param *hpos Location where horizontal scanout position should go.
1562  * \param *stime Target location for timestamp taken immediately before
1563  *               scanout position query. Can be NULL to skip timestamp.
1564  * \param *etime Target location for timestamp taken immediately after
1565  *               scanout position query. Can be NULL to skip timestamp.
1566  *
1567  * Returns vpos as a positive number while in active scanout area.
1568  * Returns vpos as a negative number inside vblank, counting the number
1569  * of scanlines to go until end of vblank, e.g., -1 means "one scanline
1570  * until start of active scanout / end of vblank."
1571  *
1572  * \return Flags, or'ed together as follows:
1573  *
1574  * DRM_SCANOUTPOS_VALID = Query successful.
1575  * DRM_SCANOUTPOS_INVBL = Inside vblank.
1576  * DRM_SCANOUTPOS_ACCURATE = Returned position is accurate. A lack of
1577  * this flag means that returned position may be offset by a constant but
1578  * unknown small number of scanlines wrt. real scanout position.
1579  *
1580  */
1581 int radeon_get_crtc_scanoutpos(struct drm_device *dev, int crtc, unsigned int flags,
1582                                int *vpos, int *hpos, ktime_t *stime, ktime_t *etime)
1583 {
1584         u32 stat_crtc = 0, vbl = 0, position = 0;
1585         int vbl_start, vbl_end, vtotal, ret = 0;
1586         bool in_vbl = true;
1587
1588         struct radeon_device *rdev = dev->dev_private;
1589
1590         /* preempt_disable_rt() should go right here in PREEMPT_RT patchset. */
1591
1592         /* Get optional system timestamp before query. */
1593         if (stime)
1594                 *stime = ktime_get();
1595
1596         if (ASIC_IS_DCE4(rdev)) {
1597                 if (crtc == 0) {
1598                         vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1599                                      EVERGREEN_CRTC0_REGISTER_OFFSET);
1600                         position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1601                                           EVERGREEN_CRTC0_REGISTER_OFFSET);
1602                         ret |= DRM_SCANOUTPOS_VALID;
1603                 }
1604                 if (crtc == 1) {
1605                         vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1606                                      EVERGREEN_CRTC1_REGISTER_OFFSET);
1607                         position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1608                                           EVERGREEN_CRTC1_REGISTER_OFFSET);
1609                         ret |= DRM_SCANOUTPOS_VALID;
1610                 }
1611                 if (crtc == 2) {
1612                         vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1613                                      EVERGREEN_CRTC2_REGISTER_OFFSET);
1614                         position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1615                                           EVERGREEN_CRTC2_REGISTER_OFFSET);
1616                         ret |= DRM_SCANOUTPOS_VALID;
1617                 }
1618                 if (crtc == 3) {
1619                         vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1620                                      EVERGREEN_CRTC3_REGISTER_OFFSET);
1621                         position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1622                                           EVERGREEN_CRTC3_REGISTER_OFFSET);
1623                         ret |= DRM_SCANOUTPOS_VALID;
1624                 }
1625                 if (crtc == 4) {
1626                         vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1627                                      EVERGREEN_CRTC4_REGISTER_OFFSET);
1628                         position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1629                                           EVERGREEN_CRTC4_REGISTER_OFFSET);
1630                         ret |= DRM_SCANOUTPOS_VALID;
1631                 }
1632                 if (crtc == 5) {
1633                         vbl = RREG32(EVERGREEN_CRTC_V_BLANK_START_END +
1634                                      EVERGREEN_CRTC5_REGISTER_OFFSET);
1635                         position = RREG32(EVERGREEN_CRTC_STATUS_POSITION +
1636                                           EVERGREEN_CRTC5_REGISTER_OFFSET);
1637                         ret |= DRM_SCANOUTPOS_VALID;
1638                 }
1639         } else if (ASIC_IS_AVIVO(rdev)) {
1640                 if (crtc == 0) {
1641                         vbl = RREG32(AVIVO_D1CRTC_V_BLANK_START_END);
1642                         position = RREG32(AVIVO_D1CRTC_STATUS_POSITION);
1643                         ret |= DRM_SCANOUTPOS_VALID;
1644                 }
1645                 if (crtc == 1) {
1646                         vbl = RREG32(AVIVO_D2CRTC_V_BLANK_START_END);
1647                         position = RREG32(AVIVO_D2CRTC_STATUS_POSITION);
1648                         ret |= DRM_SCANOUTPOS_VALID;
1649                 }
1650         } else {
1651                 /* Pre-AVIVO: Different encoding of scanout pos and vblank interval. */
1652                 if (crtc == 0) {
1653                         /* Assume vbl_end == 0, get vbl_start from
1654                          * upper 16 bits.
1655                          */
1656                         vbl = (RREG32(RADEON_CRTC_V_TOTAL_DISP) &
1657                                 RADEON_CRTC_V_DISP) >> RADEON_CRTC_V_DISP_SHIFT;
1658                         /* Only retrieve vpos from upper 16 bits, set hpos == 0. */
1659                         position = (RREG32(RADEON_CRTC_VLINE_CRNT_VLINE) >> 16) & RADEON_CRTC_V_TOTAL;
1660                         stat_crtc = RREG32(RADEON_CRTC_STATUS);
1661                         if (!(stat_crtc & 1))
1662                                 in_vbl = false;
1663
1664                         ret |= DRM_SCANOUTPOS_VALID;
1665                 }
1666                 if (crtc == 1) {
1667                         vbl = (RREG32(RADEON_CRTC2_V_TOTAL_DISP) &
1668                                 RADEON_CRTC_V_DISP) >> RADEON_CRTC_V_DISP_SHIFT;
1669                         position = (RREG32(RADEON_CRTC2_VLINE_CRNT_VLINE) >> 16) & RADEON_CRTC_V_TOTAL;
1670                         stat_crtc = RREG32(RADEON_CRTC2_STATUS);
1671                         if (!(stat_crtc & 1))
1672                                 in_vbl = false;
1673
1674                         ret |= DRM_SCANOUTPOS_VALID;
1675                 }
1676         }
1677
1678         /* Get optional system timestamp after query. */
1679         if (etime)
1680                 *etime = ktime_get();
1681
1682         /* preempt_enable_rt() should go right here in PREEMPT_RT patchset. */
1683
1684         /* Decode into vertical and horizontal scanout position. */
1685         *vpos = position & 0x1fff;
1686         *hpos = (position >> 16) & 0x1fff;
1687
1688         /* Valid vblank area boundaries from gpu retrieved? */
1689         if (vbl > 0) {
1690                 /* Yes: Decode. */
1691                 ret |= DRM_SCANOUTPOS_ACCURATE;
1692                 vbl_start = vbl & 0x1fff;
1693                 vbl_end = (vbl >> 16) & 0x1fff;
1694         }
1695         else {
1696                 /* No: Fake something reasonable which gives at least ok results. */
1697                 vbl_start = rdev->mode_info.crtcs[crtc]->base.hwmode.crtc_vdisplay;
1698                 vbl_end = 0;
1699         }
1700
1701         /* Test scanout position against vblank region. */
1702         if ((*vpos < vbl_start) && (*vpos >= vbl_end))
1703                 in_vbl = false;
1704
1705         /* Check if inside vblank area and apply corrective offsets:
1706          * vpos will then be >=0 in video scanout area, but negative
1707          * within vblank area, counting down the number of lines until
1708          * start of scanout.
1709          */
1710
1711         /* Inside "upper part" of vblank area? Apply corrective offset if so: */
1712         if (in_vbl && (*vpos >= vbl_start)) {
1713                 vtotal = rdev->mode_info.crtcs[crtc]->base.hwmode.crtc_vtotal;
1714                 *vpos = *vpos - vtotal;
1715         }
1716
1717         /* Correct for shifted end of vbl at vbl_end. */
1718         *vpos = *vpos - vbl_end;
1719
1720         /* In vblank? */
1721         if (in_vbl)
1722                 ret |= DRM_SCANOUTPOS_INVBL;
1723
1724         /* Is vpos outside nominal vblank area, but less than
1725          * 1/100 of a frame height away from start of vblank?
1726          * If so, assume this isn't a massively delayed vblank
1727          * interrupt, but a vblank interrupt that fired a few
1728          * microseconds before true start of vblank. Compensate
1729          * by adding a full frame duration to the final timestamp.
1730          * Happens, e.g., on ATI R500, R600.
1731          *
1732          * We only do this if DRM_CALLED_FROM_VBLIRQ.
1733          */
1734         if ((flags & DRM_CALLED_FROM_VBLIRQ) && !in_vbl) {
1735                 vbl_start = rdev->mode_info.crtcs[crtc]->base.hwmode.crtc_vdisplay;
1736                 vtotal = rdev->mode_info.crtcs[crtc]->base.hwmode.crtc_vtotal;
1737
1738                 if (vbl_start - *vpos < vtotal / 100) {
1739                         *vpos -= vtotal;
1740
1741                         /* Signal this correction as "applied". */
1742                         ret |= 0x8;
1743                 }
1744         }
1745
1746         return ret;
1747 }