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