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