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