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