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